{"text": "function b = r8vm_to_r8ge ( m, n, a, b )\n\n%*****************************************************************************80\n%\n%% R8VM_TO_R8GE copies a R8VM matrix to a R8GE matrix.\n%\n% Discussion:\n%\n% The R8VM storage format is used for an M by N Vandermonde matrix.\n% An M by N Vandermonde matrix is defined by the values in its second\n% row, which will be written here as X(1:N). The matrix has a first \n% row of 1's, a second row equal to X(1:N), a third row whose entries\n% are the squares of the X values, up to the M-th row whose entries\n% are the (M-1)th powers of the X values. The matrix can be stored\n% compactly by listing just the values X(1:N).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of the matrix.\n%\n% Input, real A(N,1), the R8VM matrix.\n%\n% Output, real B(M,N), the R8GE matrix.\n%\n a = a(:);\n\n for i = 1 : m\n for j = 1 : n\n if ( i == 1 )\n b(i,j) = 1.0;\n else\n b(i,j) = b(i-1,j) * a(j,1);\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8vm_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.6499654486397392}} {"text": "function [v_0_vec, v_vec, a, e, p] = LambertBattin_v2(r_0_vec, r_vec, delta_t, t_m, N)\n%\n% USAGE = [v_0_vec, v_vec, a, e, p] = LambertBattin_v2(r_0_vec, r_vec, delta_t, t_m, N)\n%\n\n% Function constants\n% mu = 3.986e5;\nmu = 398600.4418; % Sun gravitational constant (km^3/sec^2)\ntol = 1e-6;\niter_max = 500;\n\nr_0 = norm(r_0_vec);\nr = norm(r_vec);\n\ncos_delta_nu = dot(r_0_vec, r_vec) / (r_0 * r);\nsin_delta_nu = t_m * sqrt(1 - cos_delta_nu^2);\ndelta_nu = atan2(sin_delta_nu, cos_delta_nu);\nif delta_nu < 0\n \n delta_nu = 2 * pi + delta_nu;\n \nend\n\nc = sqrt(r_0^2 + r^2 - 2 * r_0 * r * cos_delta_nu);\ns = (r_0 + r + c) / 2;\n\nepsilon = (r - r_0) / r_0;\ntan_sq_2w = (epsilon^2 / 4) / (sqrt(r / r_0) + (r / r_0) * (2 + sqrt(r / r_0)));\nr_0p = sqrt(r_0 * r) * ((cos(delta_nu / 4))^2 + tan_sq_2w);\n\nsin_sq_delta_nu_4 = (sin(delta_nu / 4))^2;\ncos_sq_delta_nu_4 = (cos(delta_nu / 4))^2;\ncos_delta_nu_2 = cos(delta_nu / 2);\nif (delta_nu > 0) && (delta_nu < pi)\n \n l = (sin_sq_delta_nu_4 + tan_sq_2w) / (sin_sq_delta_nu_4 + tan_sq_2w + cos_delta_nu_2);\n \nelseif (delta_nu > pi) && (delta_nu < 2*pi)\n \n l = (cos_sq_delta_nu_4 + tan_sq_2w - cos_delta_nu_2) / (cos_sq_delta_nu_4 + tan_sq_2w);\n \nelse\n \n error('Delta_nu out of range');\n \nend\n\nm = (mu * delta_t^2) / (8 * r_0p^3); \n\nif N == 0 \n \n % Initial estimate for x\n x_new = l;\n \n loop_flag = 1;\n i_iter = 1;\n while loop_flag == 1\n \n x_old = x_new;\n [x_new, y] = original_sub(x_old, l, m, N);\n \n if abs(x_new - x_old) < tol\n \n loop_flag = 0;\n \n elseif i_iter < iter_max\n \n i_iter = i_iter + 1;\n \n else\n \n loop_flag = 0;\n x_new = NaN;\n y = NaN;\n \n end\n \n end\n \n x_f = x_new;\n y_f = y;\n \nelse % N > 0\n \n loop_flag_R = 1;\n loop_flag_L = 1;\n i_iter_R = 1;\n i_iter_L = 1;\n \n % Initial estimate for x_R\n x_new = l;\n \n while loop_flag_R == 1\n \n x_old = x_new;\n [x_new, y] = reverse_sub(x_old, l, m, N);\n \n if y < 1\n \n % In divergent region for the reversed successive substitution\n % Begin original successive substitution to find x_L\n x_new = l;\n x_old = x_new;\n [x_new, y] = original_sub(x_old, l, m, N);\n \n while loop_flag_L == 1\n \n x_old = x_new;\n [x_new, y] = original_sub(x_old, l, m, N);\n\n if abs(x_new - x_old) < tol\n\n loop_flag_L = 0;\n\n elseif i_iter_R < iter_max\n\n i_iter_R = i_iter_R + 1;\n\n else\n\n loop_flag_L = 0;\n x_new = NaN;\n y = NaN;\n\n end\n \n end\n \n y_L = y;\n x_L = x_new;\n \n % Reset initial guess for x_R\n x_new = x_new / 2;\n x_old = x_new - 2 * tol;\n \n end\n \n if abs(x_new - x_old) < tol\n \n loop_flag_R = 0;\n \n elseif i_iter_R < iter_max\n \n i_iter_R = i_iter_R + 1;\n \n else\n \n loop_flag_R = 0;\n x_new = NaN;\n y = NaN;\n \n end\n \n end\n \n y_R = y;\n x_R = x_new;\n \n % Only continue if x_L and y_L were not found in above iteration\n if loop_flag_L == 1\n \n % Initial estimate for x_L & y\n x_new = 2 * x_R;\n \n while loop_flag_L == 1\n\n x_old = x_new;\n [x_new, y] = original_sub(x_old, l, m, N);\n\n if abs(x_new - x_old) < tol\n\n loop_flag_L = 0;\n\n elseif i_iter_L < iter_max\n\n i_iter_L = i_iter_L + 1;\n\n else\n\n loop_flag_L = 0;\n x_new = NaN;\n y = NaN;\n\n end\n\n end\n \n y_L = y;\n x_L = x_new;\n \n end\n \n y_f = [y_R; y_L];\n x_f = [x_R; x_L];\n \nend\n\nif N == 0\n \n n = 1;\n \nelse\n \n n = 2;\n \nend\n\na = zeros(n,1);\ne = zeros(n,1);\np = zeros(n,1);\nv_vec = zeros(n,3);\nv_0_vec = zeros(n,3);\nfor i = 1:n\n\n a(i) = mu * delta_t^2 / (16 * r_0p^2 * x_f(i) * y_f(i)^2);\n e(i) = sqrt((epsilon^2 + 4 * (r / r_0) * (sin(delta_nu / 2))^2 * ((l - x_f(i)) / (l + x_f(i)))^2) / (epsilon^2 + 4 * (r / r_0) * (sin(delta_nu / 2))^2));\n p(i) = (4 * r_0p^2 * r_0 * r * y_f(i)^2 * (1 + x_f(i))^2 * (sin(delta_nu / 2))^2) / (mu * delta_t^2);\n if a(i) > 0\n \n f = 1 - (r / p(i)) * (1 - cos_delta_nu);\n g = (r * r_0 * sin_delta_nu) / sqrt(mu * p(i));\n g_dot = 1 - (r_0 / p(i)) * (1 - cos_delta_nu);\n \n else\n \n alpha_h = 2 * asinh(sqrt(s / (-2 * a(i))));\n beta_h = 2 * asinh(sqrt((s - c) / (-2 * a(i))));\n \n delta_H = alpha_h - beta_h;\n \n f = 1 - a(i) * (1 - cosh(delta_H)) / r;\n g = delta_t - sqrt(-a(i)^3 / mu) * (sinh(delta_H) - delta_H);\n g_dot = 1 - a(i) * (1 - cosh(delta_H)) / r;\n \n end\n \n v_0_vec(i,:) = (1 / g) .* (r_vec - f .* r_0_vec);\n v_vec(i,:) = (1 / g) .* (g_dot .* r_vec - r_0_vec);\n \nend\n\n%--------------------------------------------------------------------------\n\nfunction [y] = cubic_solv(c1, c2, c3)\n\nP = c2 - c1^2 / 3;\nQ = c3 + (2 * c1^3 - 9 * c1 * c2) / 27;\nD = Q^2 / 4 + P^3 / 27;\n\nT = (-Q / 2 + sqrt(D))^(1/3) + (-Q/2 - sqrt(D))^(1/3);\ny = T - c1 / 3;\n\n%--------------------------------------------------------------------------\n\nfunction [x_new, y] = original_sub(x_old, l, m, N)\n\nE = 2 * atan(sqrt(x_old));\nc = -m * (N * pi + E - sin(E)) / (4 * (tan(E / 2))^3);\ny = cubic_solv(-1, 0, c);\nx_new = sqrt(((1 - l) / 2)^2 + (m / y^2)) - ((1 + l) / 2);\n\n%--------------------------------------------------------------------------\n\nfunction [x_new, y] = reverse_sub(x_old, l, m, N)\n\ny = sqrt(m / ((l + x_old) * (1 + x_old)));\nE_0 = 2 * atan(sqrt(x_old));\nE = y2E(E_0, y, m, N);\nx_new = (tan(E / 2))^2;\n\n%--------------------------------------------------------------------------\n\nfunction [E] = y2E(E_0, y, m, N)\n\ntol = 1e-6;\niter_max = 200;\n\nq = 4 * (y^3 - y^2) / m;\nh = (N * pi + E_0 - sin(E_0)) / (tan(E_0 / 2))^3 - q;\n\nif h < 0\n \n loop_flag_h = 1;\n i_iter_h = 1;\n while loop_flag_h == 1\n \n E_0 = E_0 / 2;\n h = (N * pi + E_0 - sin(E_0)) / (tan(E_0 / 2))^3 - q;\n \n if h >= 0\n \n loop_flag_h = 0;\n \n elseif i_iter_h < iter_max\n \n i_iter_h = i_iter_h + 1;\n \n else\n \n loop_flag_h = 0;\n E_0 = NaN;\n \n end\n \n end\n \nend\n\ni_iter_E = 1;\nloop_flag_E = 1;\nwhile loop_flag_E == 1\n\n h = (N * pi + E_0 - sin(E_0)) / (tan(E_0 / 2))^3 - q; \n h_prime = (-3 * (cos(E_0 / 2))^2) * (N * pi + E_0 - sin(E_0)) / (2 * (sin(E_0 / 2))^4) + (1 - cos(E_0)) / (tan(E_0 / 2))^3;\n E = E_0 - h / h_prime;\n \n if abs(E - E_0) < tol\n \n loop_flag_E = 0;\n \n elseif i_iter_E < iter_max\n \n i_iter_E = i_iter_E + 1;\n E_0 = E;\n \n else\n \n loop_flag_E = 0;\n E = NaN;\n \n end\n \nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/shupe/LambertBattin_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6499512444195181}} {"text": "function [ n_data, x, fx ] = struve_h0_values ( n_data )\n\n%*****************************************************************************80\n%\n%% STRUVE_H0_VALUES returns some values of the Struve H0 function.\n%\n% Discussion:\n%\n% The function is defined by:\n%\n% HO(x) = 2/pi * Integral ( 0 <= t <= pi/2 ) sin ( x * cos ( t ) ) dt\n%\n% In Mathematica, the function can be evaluated by:\n%\n% StruveH[0,x]\n%\n% The data was reported by McLeod.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Allan McLeod,\n% Algorithm 757, MISCFUN: A software package to compute uncommon\n% special functions,\n% ACM Transactions on Mathematical Software,\n% Volume 22, Number 3, September 1996, pages 288-301.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 20;\n\n fx_vec = [ ...\n 0.12433974658847434366E-02, ...\n -0.49735582423748415045E-02, ...\n 0.39771469054536941564E-01, ...\n -0.15805246001653314198E+00, ...\n 0.56865662704828795099E+00, ...\n 0.66598399314899916605E+00, ...\n 0.79085884950809589255E+00, ...\n -0.13501457342248639716E+00, ...\n 0.20086479668164503137E+00, ...\n -0.11142097800261991552E+00, ...\n -0.17026804865989885869E+00, ...\n -0.13544931808186467594E+00, ...\n 0.94393698081323450897E-01, ...\n -0.10182482016001510271E+00, ...\n 0.96098421554162110012E-01, ...\n -0.85337674826118998952E-01, ...\n -0.76882290637052720045E-01, ...\n 0.47663833591418256339E-01, ...\n -0.70878751689647343204E-01, ...\n 0.65752908073352785368E-01 ];\n\n x_vec = [ ...\n 0.0019531250E+00, ...\n -0.0078125000E+00, ...\n 0.0625000000E+00, ...\n -0.2500000000E+00, ...\n 1.0000000000E+00, ...\n 1.2500000000E+00, ...\n 2.0000000000E+00, ...\n -4.0000000000E+00, ...\n 7.5000000000E+00, ...\n 11.0000000000E+00, ...\n 11.5000000000E+00, ...\n -16.0000000000E+00, ...\n 20.0000000000E+00, ...\n 25.0000000000E+00, ...\n -30.0000000000E+00, ...\n 50.0000000000E+00, ...\n 75.0000000000E+00, ...\n -80.0000000000E+00, ...\n 100.0000000000E+00, ...\n -125.0000000000E+00 ]; \n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/struve_h0_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6497923145633903}} {"text": "function W = threshold_proportional(W, p)\n%THRESHOLD_PROPORTIONAL Proportional thresholding\n%\n% W_thr = threshold_proportional(W, p);\n%\n% This function \"thresholds\" the connectivity matrix by preserving a\n% proportion p (0 for details.\n\n% Flux function\n% ------------------\n% Description: Recharge to fulfil evaporation demand if the receiving \n% store is below a threshold\n% Constraints: f <= S/dt\n% S >= 0 prevents complex numbers\n% @(Inputs): p1 - time coefficient [d-1]\n% p2 - non-linear scaling [mm]\n% S - current storage [mm]\n% dt - time step size [d]\n\nout = min(max(S/dt,0),p1.*max(S,0).^p2);\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/recharge_6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6496659843846951}} {"text": "%% Analyzing Neural Time Series Data\n% Matlab code for Chapter 34\n% Mike X Cohen\n% \n% This code accompanies the book, titled \"Analyzing Neural Time Series Data\" \n% (MIT Press). Using the code without following the book may lead to confusion, \n% incorrect data analyses, and misinterpretations of results. \n% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code. \n\n%% load sample data\n\nload sampleEEGdata\n\n% note: Most of these figures take a while to generate. Have patience!\n\n%% extract TF power (create data that are used for the rest of this chapter)\n\n% definitions, selections...\nchan2use = 'fcz';\n\nmin_freq = 3;\nmax_freq = 30;\nnum_frex = 20;\n\n\n% define wavelet parameters\ntime = -1:1/EEG.srate:1;\nfrex = logspace(log10(min_freq),log10(max_freq),num_frex);\ns = logspace(log10(3),log10(10),num_frex)./(2*pi*frex);\n\n% definte convolution parameters\nn_wavelet = length(time);\nn_data = EEG.pnts*EEG.trials;\nn_convolution = n_wavelet+n_data-1;\nn_conv_pow2 = pow2(nextpow2(n_convolution));\nhalf_of_wavelet_size = (n_wavelet-1)/2;\n\n% note that you don't need the wavelet itself, you need the FFT of the wavelet\nwavelets = zeros(num_frex,n_conv_pow2);\nfor fi = 1:num_frex\n wavelets(fi,:) = fft( sqrt(1/(s(fi)*sqrt(pi))) * exp(2*1i*pi*frex(fi).*time) .* exp(-time.^2./(2*(s(fi)^2))) , n_conv_pow2 );\nend\n\n% get FFT of data\neegfft = fft(reshape(EEG.data(strcmpi(chan2use,{EEG.chanlocs.labels}),:,:),1,EEG.pnts*EEG.trials),n_conv_pow2);\n\n% initialize\neegpower = zeros(num_frex,EEG.pnts,EEG.trials); % frequencies X time X trials\neegphase = zeros(num_frex,EEG.pnts,EEG.trials); % frequencies X time X trials\n\n% loop through frequencies and compute synchronization\nfor fi=1:num_frex\n \n % convolution\n eegconv = ifft(wavelets(fi,:).*eegfft);\n eegconv = eegconv(1:n_convolution);\n eegconv = eegconv(half_of_wavelet_size+1:end-half_of_wavelet_size);\n \n % reshape to time X trials\n eegpower(fi,:,:) = abs(reshape(eegconv,EEG.pnts,EEG.trials)).^2;\n eegphase(fi,:,:) = exp(1i*angle(reshape(eegconv,EEG.pnts,EEG.trials)));\nend\n\n% remove edge artifacts\ntime_s = dsearchn(EEG.times',-500);\ntime_e = dsearchn(EEG.times',1200);\n\neegpower = eegpower(:,time_s:time_e,:);\ntftimes = EEG.times(time_s:time_e);\nnTimepoints = numel(tftimes);\n\n%% Figure 34.1\n\nvoxel_pval = 0.01;\ncluster_pval = 0.05;\n\n% note: try to use 1000 or more permutations for real data\nn_permutes = 1000;\n\nbaseidx(1) = dsearchn(tftimes',-500);\nbaseidx(2) = dsearchn(tftimes',-100);\n\n% compute actual t-test of difference\nrealbaselines = squeeze(mean(eegpower(:,baseidx(1):baseidx(2),:),2));\nrealmean = 10*log10(bsxfun(@rdivide, mean(eegpower,3), mean(realbaselines,2)));\n\n% initialize null hypothesis matrices\npermuted_maxvals = zeros(n_permutes,2,num_frex);\npermuted_vals = zeros(n_permutes,num_frex,numel(tftimes));\nmax_clust_info = zeros(n_permutes,1);\n\n\nfor permi=1:n_permutes\n cutpoint = randsample(2:nTimepoints-diff(baseidx)-2,1);\n permuted_vals(permi,:,:) = 10*log10(bsxfun(@rdivide,mean(eegpower(:,[cutpoint:end 1:cutpoint-1],:),3),mean(realbaselines,2)) );\n % btw, using bsxfun instead of repmat increases the speed \n % of this loop by a factor of ~5.\nend\n\nzmap = (realmean-squeeze(mean(permuted_vals))) ./ squeeze(std(permuted_vals));\nthreshmean = realmean;\nthreshmean(abs(zmap)lower_threshold & zmapthreshlower_threshold & realcorrs dist_12\n disp(['TODA delay (' num2str(doa_meters) ' meters) larger than RX distance (' num2str(1000* dist_12) ' meters) -> no solution possible ']);\n doa_meters = sign(doa_meters) * 0.995 * dist_12 * 1000;\n disp(['ATTENTION: Correcting TODA delay to 0.995 * RX distance (maximum possible value) = ' num2str(0.995*doa_meters) '']);\n end\n \n \n if abs(doa_meters/1000) <= dist_12\n\n %for r_1 = (exp(0:0.05:4)-1) / 5\n for r_1 = 0:0.05:10\n r_2 = r_1 - doa_meters/1000;\n %disp(['r_1 = ' num2str(r_1) ', r_2 = ' num2str(r_2)]);\n\n if ((r_2 + r_1) > dist_12) % checks if triangle can be created\n \n\t\t\t\tacos_argument = (r_2^2 - r_1^2 - dist_12^2) / (-2*r_1*dist_12);\n\t\t\t\t\n\t\t\t\tif (acos_argument >= -1) && (acos_argument <= +1) % checks if triangle can be created\n\t\t\t\t\n\t\t\t\t\thyp_point_counter = hyp_point_counter + 1;\n\n\t\t\t\t\thyp_angle = acos(acos_argument); % inner angle of triangle at RX1\n \n\t\t\t\t\tabs_angle1 = wrap2pi(angle_12 + hyp_angle); % 1st solution: hyperbola leg 1\n\t\t\t\t\thyp_x_leg1(hyp_point_counter) = rx1_x + r_1 * cos(abs_angle1);\n\t\t\t\t\thyp_y_leg1(hyp_point_counter) = rx1_y + r_1 * sin(abs_angle1);\n\n\t\t\t\t\tabs_angle2 = wrap2pi(angle_12 - hyp_angle); % 2nd solution: hyperbola leg 2 \n\t\t\t\t\thyp_x_leg2(hyp_point_counter) = rx1_x + r_1 * cos(abs_angle2);\n\t\t\t\t\thyp_y_leg2(hyp_point_counter) = rx1_y + r_1 * sin(abs_angle2);\n else\n %disp(['acos argument ' num2str(acos_argument)]);\n\t\t\t\tend\n end\n\n end\n else\n disp('TODA delay larger than RX distance -> no solution possible');\n end\n \n if (hyp_point_counter == 0)\n disp('Hyperbola could not be constructed');\n end\n\n hyp_x = [fliplr(hyp_x_leg1) hyp_x_leg2];\n hyp_y = [fliplr(hyp_y_leg1) hyp_y_leg2];\n hyp_points = 2* hyp_point_counter;\n \n points_lat = zeros(hyp_points,1);\n points_long = zeros(hyp_points,1);\n \n for ii=1:1:hyp_points\n [points_lat(ii), points_long(ii)] = xy2latlong(hyp_x(ii), hyp_y(ii), geo_ref_lat, geo_ref_long);\n end\n \n disp(['Hyperbola with totally ' num2str(hyp_points) ' points generated.']);\nend\n\n", "meta": {"author": "DC9ST", "repo": "tdoa-evaluation-rtlsdr", "sha": "3e7791adca1179b0a0be715b240caa0ad01d09c7", "save_path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr", "path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr/tdoa-evaluation-rtlsdr-3e7791adca1179b0a0be715b240caa0ad01d09c7/functions/gen_hyperbola.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6495392439184182}} {"text": "function lik = lik_qgp(varargin)\n%LIK_QGP Create a Quantile Gaussian Process likelihood (utility) structure\n%\n% Description\n% LIK = LIK_QGP('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a quantile gp likelihood structure in which the named\n% parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% LIK = LIK_QGP(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a likelihood function structure with the named\n% parameters altered with the specified values.\n%\n% Parameters for QGP likelihood function [default]\n% sigma2 - variance [0.1]\n% sigma2_prior - prior for sigma2 [prior_logunif]\n% quantile - Quantile of interest [0.5]\n%\n% Note! If the prior is 'prior_fixed' then the parameter in\n% question is considered fixed and it is not handled in\n% optimization, grid integration, MCMC etc. \n%\n% The likelihood is defined as follows:\n% __ n\n% p(y|f, sigma2, tau) = || i=1 tau*(1-tau)/sigma*exp(-(y-f)/sigma*\n% (tau - I(t <= f)))\n% \n% where tau is the quantile of interest, sigma is the standard deviation\n% of the distribution and I(t <= f) = 1 if t <= f, 0 otherwise.\n%\n% Note that because the form of the likelihood, second order derivatives\n% with respect to latent values are 0. Because this, EP should be used\n% instead of Laplace approximation. \n%\n% See also\n% GP_SET, PRIOR_*, LIK_*\n%\n% References\n% Boukouvalas et al. (2012). Direct Gaussian Process Quantile Regression\n% Using Expectation Propagation. Appearing in Proceedings of the 29th\n% International Conference on Machine Learning, Edinburg, Scotland, UK,\n% 2012.\n% \n \n% Copyright (c) 2012 Ville Tolvanen\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_QGP';\n ip.addOptional('lik', [], @isstruct);\n ip.addParamValue('sigma2',0.1, @(x) isscalar(x) && x>0);\n ip.addParamValue('sigma2_prior',prior_logunif(), @(x) isstruct(x) || isempty(x));\n ip.addParamValue('quantile',0.5, @(x) isscalar(x) && x>0 && x<1);\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'QGP';\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'QGP')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n \n % Initialize parameters\n if init || ~ismember('sigma2',ip.UsingDefaults)\n lik.sigma2 = ip.Results.sigma2;\n end\n if init || ~ismember('quantile',ip.UsingDefaults)\n lik.quantile = ip.Results.quantile;\n end\n % Initialize prior structure\n if init\n lik.p=[];\n end\n if init || ~ismember('sigma2_prior',ip.UsingDefaults)\n lik.p.sigma2=ip.Results.sigma2_prior;\n end\n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_qgp_pak;\n lik.fh.unpak = @lik_qgp_unpak;\n lik.fh.lp = @lik_qgp_lp;\n lik.fh.lpg = @lik_qgp_lpg;\n lik.fh.ll = @lik_qgp_ll;\n lik.fh.llg = @lik_qgp_llg; \n lik.fh.llg2 = @lik_qgp_llg2;\n lik.fh.llg3 = @lik_qgp_llg3;\n lik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n lik.fh.siteDeriv = @lik_qgp_siteDeriv;\n lik.fh.predy = @lik_qgp_predy;\n lik.fh.invlink = @lik_qgp_invlink;\n lik.fh.recappend = @lik_qgp_recappend;\n end\n\nend\n\nfunction [w s] = lik_qgp_pak(lik)\n%LIK_QGP_PAK Combine likelihood parameters into one vector.\n%\n% Description\n% W = LIK_QGP_PAK(LIK) takes a likelihood structure LIK\n% and combines the parameters into a single row vector W.\n% This is a mandatory subfunction used for example in \n% energy and gradient computations.\n%\n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.magnSigma2)]'\n% \n% See also\n% LIK_QGP_UNPAK\n\n w = []; s = {};\n if ~isempty(lik.p.sigma2)\n w = [w log(lik.sigma2)];\n s = [s; 'log(qgp.sigma2)'];\n % Hyperparameters of sigma2\n [wh sh] = lik.p.sigma2.fh.pak(lik.p.sigma2);\n w = [w wh];\n s = [s; sh];\n end \n\nend\n\nfunction [lik, w] = lik_qgp_unpak(lik, w)\n%LIK_QGP_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_QGP_UNPAK(W, LIK) takes a likelihood structure\n% LIK and extracts the parameters from the vector W to the LIK\n% structure. This is a mandatory subfunction used for example \n% in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = [ log(lik.sigma2)\n% (hyperparameters of lik.magnSigma2)]'\n%\n% See also\n% LIK_QGP_PAK\n \n if ~isempty(lik.p.sigma2)\n lik.sigma2 = exp(w(1));\n w = w(2:end);\n \n % Hyperparameters of sigma2\n [p, w] = lik.p.sigma2.fh.unpak(lik.p.sigma2, w);\n lik.p.sigma2 = p;\n end\nend\n\nfunction lp = lik_qgp_lp(lik)\n%LIK_QGP_LP Evaluate the log prior of likelihood parameters\n%\n% Description\n% LP = LIK_QGP_LP(LIK) takes a likelihood structure LIK and\n% returns log(p(th)), where th collects the parameters. This\n% subfunction is needed when there are likelihood parameters.\n%\n% See also\n% LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_G, GP_E\n\n lp = 0;\n\n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n lp = likp.sigma2.fh.lp(lik.sigma2, likp.sigma2) + log(lik.sigma2);\n end\nend\n\nfunction lpg = lik_qgp_lpg(lik)\n%LIK_QGP_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = LIK_QGP_LPG(LIK) takes a QGP likelihood\n% function structure LIK and returns LPG = d log (p(th))/dth,\n% where th is the vector of parameters. This subfunction is \n% needed when there are likelihood parameters.\n%\n% See also\n% LIK_QGP_PAK, LIK_QGP_UNPAK, LIK_QGP_E, GP_G\n\n lpg = [];\n\n if ~isempty(lik.p.sigma2)\n likp=lik.p;\n \n lpgs = likp.sigma2.fh.lpg(lik.sigma2, likp.sigma2);\n lpg = lpgs(1).*lik.sigma2 + 1;\n if length(lpgs) > 1\n lpg = [lpg lpgs(2:end)];\n end \n end\nend\n\nfunction ll = lik_qgp_ll(lik, y, f, z)\n%LIK_QGP_LL Log likelihood\n%\n% Description\n% LL = LIK_QGP_LL(LIK, Y, F, Z) takes a likelihood\n% structure LIK, observations Y and latent values F. \n% Returns the log likelihood, log p(y|f,z). This subfunction \n% is needed when using Laplace approximation or MCMC for \n% inference with non-Gaussian likelihoods. This subfunction \n% is also used in information criteria (DIC, WAIC) computations.\n%\n% See also\n% LIK_QGP_LLG, LIK_QGP_LLG3, LIK_QGP_LLG2, GPLA_E\n \n tau=lik.quantile;\n sigma=sqrt(lik.sigma2);\n ll = sum(log(tau*(1-tau)/sigma) - (y-f)./sigma.*(tau-(y<=f)));\nend\n\nfunction llg = lik_qgp_llg(lik, y, f, param, z)\n%LIK_QGP_LLG Gradient of the log likelihood\n%\n% Description \n% LLG = LIK_QGP_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F. Returns \n% the gradient of the log likelihood with respect to PARAM. \n% At the moment PARAM can be 'param' or 'latent'. This subfunction \n% is needed when using Laplace approximation or MCMC for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG2, LIK_QGP_LLG3, GPLA_E\n\n \n tau=lik.quantile;\n sigma2=sqrt(lik.sigma2);\n switch param\n case 'param' \n llg = sum(-1/(2.*sigma2) + (y-f)./(2.*sigma2^(3/2)).*(tau-(y<=f)));\n \n % correction for the log transformation\n llg = llg.*lik.sigma2;\n case 'latent'\n llg = (tau-(y<=f))/sqrt(sigma2);\n end\nend\n\nfunction llg2 = lik_qgp_llg2(lik, y, f, param, z)\n%LIK_QGP_LLG2 Second gradients of the log likelihood\n%\n% Description \n% LLG2 = LIK_QGP_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F. Returns \n% the Hessian of the log likelihood with respect to PARAM. \n% At the moment PARAM can be 'param' or 'latent'. LLG2 is \n% a vector with diagonal elements of the Hessian matrix \n% (off diagonals are zero). This subfunction is needed \n% when using Laplace approximation or EP for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG3, GPLA_E\n\n \n tau=lik.quantile;\n sigma2=lik.sigma2;\n switch param\n case 'param'\n llg2 = sum(1/(2*sigma2^2) - 3.*(tau-(y<=f)).*(y-f)./(4.*sigma2^(5/2)));\n \n % correction due to the log transformation\n llg2 = llg2.*lik.sigma2;\n case 'latent'\n llg2 = zeros(size(f));\n case 'latent+param'\n llg2 = -(tau-(y<=f))./(2*sigma2^(3/2));\n \n % correction due to the log transformation\n llg2 = llg2.*lik.disper;\n end\nend \n\nfunction llg3 = lik_qgp_llg3(lik, y, f, param, z)\n%LIK_QGP_LLG3 Third gradients of the log likelihood\n%\n% Description\n% LLG3 = LIK_QGP_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, observations Y and latent values F and \n% returns the third gradients of the log likelihood with \n% respect to PARAM. At the moment PARAM can be 'param' or \n% 'latent'. LLG3 is a vector with third gradients. This \n% subfunction is needed when using Laplace approximation for \n% inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_LLG, LIK_QGP_LLG2, GPLA_E, GPLA_G\n\n tau=lik.quantile;\n sigma2=lik.sigma2;\n switch param\n case 'param'\n llg3 = sum(-1/sigma2^3 + 15.*(tau-(y<=f)).*(y-f)./(8.*sigma2^(7/2)));\n case 'latent'\n llg3 = 0;\n case 'latent2+param'\n llg3 = 0;\n \n % correction due to the log transformation\n llg3 = llg3.*lik.sigma2;\n end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_qgp_tiltedMoments(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_QGP_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_QGP_TILTEDMOMENTS(LIK, Y, I, S2,\n% MYY, Z) takes a likelihood structure LIK, observations\n% Y, index I and cavity variance S2 and mean MYY. Returns \n% the zeroth moment M_0, mean M_1 and variance M_2 of the \n% posterior marginal (see Rasmussen and Williams (2006): \n% Gaussian processes for Machine Learning, page 55). This \n% subfunction is needed when using EP for inference with \n% non-Gaussian likelihoods.\n%\n% See also\n% GPEP_E\n \n yy = y(i1);\n sigma2 = lik.sigma2;\n tau=lik.quantile;\n logM_0=zeros(size(yy));\n m_1=zeros(size(yy));\n sigm2hati1=zeros(size(yy));\n \n for i=1:length(i1)\n % get a function handle of an unnormalized tilted distribution\n % (likelihood * cavity = Quantile-GP * Gaussian)\n % and useful integration limits\n [tf,minf,maxf]=init_qgp_norm(yy(i),myy_i(i),sigm2_i(i),sigma2,tau);\n \n % Integrate with quadrature\n RTOL = 1.e-6;\n ATOL = 1.e-10;\n [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n sigm2hati1(i) = m_2 - m_1(i).^2;\n \n % If the second central moment is less than cavity variance\n % integrate more precisely. Theoretically for log-concave\n % likelihood should be sigm2hati1 < sigm2_i.\n if sigm2hati1(i) >= sigm2_i(i)\n ATOL = ATOL.^2;\n RTOL = RTOL.^2;\n [m_0, m_1(i), m_2] = quad_moments(tf, minf, maxf, RTOL, ATOL);\n sigm2hati1(i) = m_2 - m_1(i).^2;\n if sigm2hati1(i) >= sigm2_i(i)\n error('lik_qgp_tilted_moments: sigm2hati1 >= sigm2_i');\n end\n end\n logM_0(i) = log(m_0);\n end\nend\n\nfunction [g_i] = lik_qgp_siteDeriv(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_QGP_SITEDERIV Evaluate the expectation of the gradient\n% of the log likelihood term with respect\n% to the likelihood parameters for EP \n%\n% Description [M_0, M_1, M2] =\n% LIK_QGP_SITEDERIV(LIK, Y, I, S2, MYY, Z) takes a\n% likelihood structure LIK, observations Y, index I \n% and cavity variance S2 and mean MYY. Returns E_f \n% [d log p(y_i|f_i) /d a], where a is the likelihood \n% parameter and the expectation is over the marginal posterior.\n% This term is needed when evaluating the gradients of \n% the marginal likelihood estimate Z_EP with respect to \n% the likelihood parameters (see Seeger (2008):\n% Expectation propagation for exponential families).This \n% subfunction is needed when using EP for inference with \n% non-Gaussian likelihoods and there are likelihood parameters.\n%\n% See also\n% GPEP_G\n\n\n yy = y(i1);\n sigma2=lik.sigma2;\n tau=lik.quantile;\n \n % get a function handle of an unnormalized tilted distribution \n % (likelihood * cavity = Quantile-GP * Gaussian)\n % and useful integration limits\n [tf,minf,maxf]=init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau);\n % additionally get function handle for the derivative\n td = @deriv;\n \n % Integrate with quadgk\n [m_0, fhncnt] = quadgk(tf, minf, maxf);\n [g_i, fhncnt] = quadgk(@(f) td(f).*tf(f)./m_0, minf, maxf);\n g_i = g_i.*sigma2;\n\n function g = deriv(f)\n\n g = -1/(2.*sigma2) + (yy-f)./(2.*sigma2^(3/2)).*(tau-(yy<=f));\n \n end\nend\n\nfunction [lpy, Ey, Vary] = lik_qgp_predy(lik, Ef, Varf, yt, zt)\n%LIK_QGP_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% LPY = LIK_QGP_PREDY(LIK, EF, VARF YT, ZT)\n% Returns logarithm of the predictive density PY of YT, that is \n% p(yt | zt) = \\int p(yt | f, zt) p(f|y) df.\n% This subfunction is needed when computing posterior predictive \n% distributions for future observations.\n%\n% [LPY, EY, VARY] = LIK_QGP_PREDY(LIK, EF, VARF) takes a\n% likelihood structure LIK, posterior mean EF and posterior\n% Variance VARF of the latent variable and returns the\n% posterior predictive mean EY and variance VARY of the\n% observations related to the latent variables. This \n% subfunction is needed when computing posterior predictive \n% distributions for future observations.\n% \n\n%\n% See also\n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n\n sigma2=lik.sigma2;\n tau=lik.quantile;\n \n Ey=[];\n Vary=[];\n \n % Evaluate the posterior predictive densities of the given observations\n lpy = zeros(length(yt),1);\n for i1=1:length(yt)\n % get a function handle of the likelihood times posterior\n % (likelihood * posterior = Quantile-GP * Gaussian)\n % and useful integration limits\n [pdf,minf,maxf]=init_qgp_norm(...\n yt(i1),Ef(i1),Varf(i1),sigma2, tau);\n % integrate over the f to get posterior predictive distribution\n lpy(i1) = log(quadgk(pdf, minf, maxf));\n end\nend\n\n\nfunction [df,minf,maxf] = init_qgp_norm(yy,myy_i,sigm2_i,sigma2,tau)\n%INIT_QGP_NORM\n%\n% Description\n% Return function handle to a function evaluating\n% Quantile-GP * Gaussian which is used for evaluating\n% (likelihood * cavity) or (likelihood * posterior) Return\n% also useful limits for integration. This is private function\n% for lik_qgp. This subfunction is needed by subfunctions\n% tiltedMoments, siteDeriv and predy.\n% \n% See also\n% LIK_QGP_TILTEDMOMENTS, LIK_QGP_SITEDERIV,\n% LIK_QGP_PREDY\n \n sigma=sqrt(sigma2);\n% avoid repetitive evaluation of constant part\n ldconst = log(tau*(1-tau)/sigma) ...\n - log(sigm2_i)/2 - log(2*pi)/2;\n % Create function handle for the function to be integrated\n df = @qgp_norm;\n % use log to avoid underflow, and derivates for faster search\n ld = @log_qgp_norm;\n ldg = @log_qgp_norm_g;\n% ldg2 = @log_qgp_norm_g2;\n\n % Set the limits for integration\n % Quantile-GP likelihood is log-concave so the qgp_norm\n % function is unimodal, which makes things easier\n if yy==0\n % with yy==0, the mode of the likelihood is not defined\n % use the mode of the Gaussian (cavity or posterior) as a first guess\n modef = myy_i;\n else\n % use precision weighted mean of the Gaussian approximation\n % of the Quantile-GP likelihood and Gaussian\n modef = (myy_i/sigm2_i + yy/sigma2)/(1/sigm2_i + 1/sigma2);\n end\n % find the mode of the integrand using Newton iterations\n % few iterations is enough, since the first guess in the right direction\n niter=8; % number of Newton iterations \n \n minf=modef-6*sigm2_i;\n while ldg(minf) < 0\n minf=minf-2*sigm2_i;\n end\n maxf=modef+6*sigm2_i;\n while ldg(maxf) > 0\n maxf=maxf+2*sigm2_i;\n end\n for ni=1:niter\n% h=ldg2(modef);\n modef=0.5*(minf+maxf);\n if ldg(modef) < 0\n maxf=modef;\n else\n minf=modef;\n end\n end\n % integrand limits based on Gaussian approximation at mode\n minf=modef-6*sqrt(sigm2_i);\n maxf=modef+6*sqrt(sigm2_i);\n modeld=ld(modef);\n iter=0;\n % check that density at end points is low enough\n lddiff=20; % min difference in log-density between mode and end-points\n minld=ld(minf);\n step=1;\n while minld>(modeld-lddiff)\n minf=minf-step*sqrt(sigm2_i);\n minld=ld(minf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_qgp -> init_qgp_norm: ' ...\n 'integration interval minimun not found ' ...\n 'even after looking hard!'])\n end\n end\n maxld=ld(maxf);\n step=1;\n while maxld>(modeld-lddiff)\n maxf=maxf+step*sqrt(sigm2_i);\n maxld=ld(maxf);\n iter=iter+1;\n step=step*2;\n if iter>100\n error(['lik_qgp -> init_qgp_norm: ' ...\n 'integration interval maximun not found ' ...\n 'even after looking hard!'])\n end\n end\n \n function integrand = qgp_norm(f)\n % Quantile-GP * Gaussian\n integrand = exp(ldconst ...\n -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n -0.5*(f-myy_i).^2./sigm2_i);\n end\n \n function log_int = log_qgp_norm(f)\n % log(Quantile-GP * Gaussian)\n % log_qgp_norm is used to avoid underflow when searching\n % integration interval\n log_int = ldconst...\n -(yy-f)./sqrt(sigma2).*(tau-(yy<=f)) ...\n -0.5*(f-myy_i).^2./sigm2_i;\n end\n \n function g = log_qgp_norm_g(f)\n % d/df log(Quantile-GP * Gaussian)\n % derivative of log_qgp_norm\n g = (tau-(yy<=f))/sqrt(sigma2) ...\n + (myy_i - f)./sigm2_i;\n end\n \n \nend\n\nfunction mu = lik_qgp_invlink(lik, f, z)\n%LIK_QGP_INVLINK Returns values of inverse link function\n% \n% Description \n% MU = LIK_QGP_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values MU of inverse link function.\n% This subfunction is needed when using function gp_predprctmu.\n%\n% See also\n% LIK_QGP_LL, LIK_QGP_PREDY\n \n mu = f;\nend\n\nfunction reclik = lik_qgp_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = LIK_QGP_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood record structure RECLIK, record index RI and\n% likelihood structure LIK with the current MCMC samples of\n% the parameters. Returns RECLIK which contains all the old\n% samples and the current samples from LIK. This subfunction\n% is needed when using MCMC sampling (gp_mc).\n% \n% See also\n% GP_MC\n\n if nargin == 2\n % Initialize the record\n reclik.type = 'Quantile-GP';\n\n % Initialize parameter\n reclik.sigma2 = [];\n\n % Set the function handles\n reclik.fh.pak = @lik_qgp_pak;\n reclik.fh.unpak = @lik_qgp_unpak;\n reclik.fh.lp = @lik_qgp_lp;\n reclik.fh.lpg = @lik_qgp_lpg;\n reclik.fh.ll = @lik_qgp_ll;\n reclik.fh.llg = @lik_qgp_llg; \n reclik.fh.llg2 = @lik_qgp_llg2;\n reclik.fh.llg3 = @lik_qgp_llg3;\n reclik.fh.tiltedMoments = @lik_qgp_tiltedMoments;\n reclik.fh.predy = @lik_qgp_predy;\n reclik.fh.invlink = @lik_qgp_invlink;\n reclik.fh.recappend = @lik_qgp_recappend;\n reclik.p=[];\n reclik.p.sigma2=[];\n if ~isempty(ri.p.sigma2)\n reclik.p.sigma2 = ri.p.sigma2;\n end\n else\n \n % Append to the record\n reclik.sigma2(ri,:)=lik.sigma2;\n if ~isempty(lik.p)\n reclik.p.sigma2 = lik.p.sigma2.fh.recappend(reclik.p.sigma2, ri, lik.p.sigma2);\n end\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/lik_qgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6495292872064116}} {"text": "function [C_pos,C_neg,Ctot_pos,Ctot_neg] = clustering_coef_wu_sign(W,coef_type)\n%CLUSTERING_COEF_WU_SIGN Multiple generalizations of the clustering coefficient \n%\n% [C_pos,C_neg,Ctot_pos,Ctot_neg] = clustering_coef_wu_sign(W,coef_type);\n%\n% The weighted clustering coefficient is the average weight or intensity\n% of all triangles associated with each node.\n%\n% Inputs:\n% W, \n% Weighted undirected connection matrix\n%\n% corr_type,\n% Desired type of clustering coefficient.\n% Options: \n% 1, (default) Onnela et al. formula, used in original\n% clustering_coef_wu.m. Computed separately for positive &\n% negative weights.\n% 2, Zhang & Horvath formula, similar to Onnela formula except\n% denominator of Onnela formula relies on binarizing the\n% network whereas this denominator is based on weight value,\n% which reduces the sensitivity of this measure to the\n% weights directly connected to the node of interest.\n% Computed separately for positive & negative weights.\n% 3, Constantini & Perugini's generalization of the Zhang &\n% Horvath formula. This formula takes both positive &\n% negative weights into account simultaneously, & is\n% particularly sensitive to non-redundancy in path\n% information based on sign (i.e., when two weights are\n% positive & one negative, or all three are negative, both of\n% which indicate that the weight of the third path is not\n% redundant information). Produces only one value.\n%\n%\n% Outputs: \n% C_pos/C_neg,\n% Clustering coefficient vector for positive/negative weights.\n% For the third option, only one vector is outputted (as C_pos). \n% Ctot_pos/Ctot_neg,\n% Mean clustering coefficient for positive and negative weights.\n%\n% References: \n% Onnela et al. (2005) Phys Rev E 71:065103\n% Zhang & Horvath (2005) Stat Appl Genet Mol Biol 41:1544-6115\n% Costantini & Perugini (2014) PLOS ONE 9:e88669\n%\n%\n% Contributor: Jeff Spielberg, Boston University, 2014-2015\n% (script based on clustering_coef_wu.m)\n\n%\n% Modification History:\n% May 2014: Added computation of pos & neg weights separately & \n% computation of mean coefficient (Jeff Spielberg)\n% May 2015: Added computation of Zhang & Horvath and Constantini & \n% Perugini formulas (Jeff Spielberg)\n% May 2016: Bugfix in computation of the denominator of the Costantini &\n% Perugini (flag 3) version (Chiara Pintossi)\n\nif ~exist('coef_type','var')\n coef_type = 1;\nend\n\nn = length(W); %number of nodes\nW(1:n+1:end) = 0;\n\nswitch coef_type\n case 1\n W_pos = W.*(W>0);\n K_pos = sum(W_pos~=0,2);\n cyc3_pos = diag((W_pos.^(1/3))^3);\n K_pos(cyc3_pos == 0) = inf; %if no 3-cycles exist, make C=0 (via K=inf)\n C_pos = cyc3_pos./(K_pos.*(K_pos-1)); %clustering coefficient\n Ctot_pos = mean(C_pos);\n \n W_neg = -W.*(W<0);\n K_neg = sum(W_neg~=0,2);\n cyc3_neg = diag((W_neg.^(1/3))^3);\n K_neg(cyc3_neg == 0) = inf; %if no 3-cycles exist, make C=0 (via K=inf)\n C_neg = cyc3_neg./(K_neg.*(K_neg-1)); %clustering coefficient\n Ctot_neg = mean(C_neg);\n case 2\n W_pos = W.*(W>0);\n cyc3_pos = zeros(n,1);\n cyc2_pos = zeros(n,1);\n for i = 1:n\n for j = 1:n\n for q = 1:n\n cyc3_pos(i) = cyc3_pos(i)+(W_pos(j,i)*W_pos(i,q)*W_pos(j,q));\n if j~=q\n cyc2_pos(i) = cyc2_pos(i)+(W_pos(j,i)*W_pos(i,q));\n end\n end\n end\n end\n cyc2_pos(cyc3_pos == 0) = inf; %if no 3-cycles exist, make C=0 (via K=inf)\n C_pos = cyc3_pos./cyc2_pos; %clustering coefficient\n Ctot_pos = mean(C_pos);\n \n W_neg = -W.*(W<0);\n cyc3_neg = zeros(n,1);\n cyc2_neg = zeros(n,1);\n for i = 1:n\n for j = 1:n\n for q = 1:n\n cyc3_neg(i) = cyc3_neg(i)+(W_neg(j,i)*W_neg(i,q)*W_neg(j,q));\n if j~=q\n cyc2_neg(i) = cyc2_neg(i)+(W_neg(j,i)*W_neg(i,q));\n end\n end\n end\n end\n cyc2_neg(cyc3_neg == 0) = inf; %if no 3-cycles exist, make C=0 (via K=inf)\n C_neg = cyc3_neg./cyc2_neg; %clustering coefficient\n Ctot_neg = mean(C_neg);\n case 3\n cyc3 = zeros(n,1);\n cyc2 = zeros(n,1);\n \n for i = 1:n\n for j = 1:n\n for q = 1:n\n cyc3(i) = cyc3(i)+(W(j,i)*W(i,q)*W(j,q));\n if j~=q\n cyc2(i) = cyc2(i)+abs(W(j,i)*W(i,q));\n end\n end\n end\n end\n \n cyc2(cyc3 == 0) = inf; %if no 3-cycles exist, make C=0 (via K=inf)\n C_pos = cyc3./cyc2; %clustering coefficient\n Ctot_pos = mean(C_pos);\n C_neg = nan(size(C_pos));\n Ctot_neg = nan(size(Ctot_pos));\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/clustering_coef_wu_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6494854061283761}} {"text": "function newFaces = minConvexHull(points, varargin)\n%MINCONVEXHULL Return the unique minimal convex hull of a set of 3D points.\n%\n% FACES = minConvexHull(PTS)\n% NODES is a set of 3D points (as a Nx3 array). The function computes\n% the convex hull, and merge contiguous coplanar faces. The result is a\n% set of polygonal faces, such that there are no coplanar faces.\n% FACES is a cell array, each cell containing the vector of indices of\n% nodes given in NODES for the corresponding face.\n%\n% FACES = minConvexHull(PTS, PRECISION)\n% Adjust the threshold for deciding if two faces are coplanar or\n% parallel. Default value is 1e-14.\n%\n% Example\n% % extract square faces from a cube\n% [n, e, f] = createCube;\n% f2 = minConvexHull(n);\n% drawMesh(n, f2);\n%\n% % Subdivides and smooths a mesh rpresenting a cube\n% [n, e, f] = createCube;\n% [n2, f2] = subdivideMesh(n, triangulateFaces(f), 4);\n% [n3, f3] = smoothMesh(n2, f2);\n% figure; drawMesh(n3, f3);\n% axis equal; view(3);\n% % merge coplanar faces, making apparent the faces of the original cube\n% f4 = minConvexHull(n3);\n% figure; drawMesh(n3, f4);\n% axis equal; view(3);\n%\n%\n% See also \n% meshes3d, mergeCoplanarFaces, drawMesh, convhull, convhulln\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2006-07-05\n% Copyright 2006-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\n% set up precision\nacc = 1e-14;\nif ~isempty(varargin)\n acc = varargin{1};\nend\n\n% triangulated convex hull. It is not uniquely defined.\nfaces = convhulln(points);\n\n% compute centroid of the nodes\npointsCentroid = centroid(points);\n\n% number of base triangular faces\nN = size(faces, 1);\n\n% compute normals of given faces\nnormals = planeNormal(createPlane(...\n points(faces(:,1),:), points(faces(:,2),:), points(faces(:,3),:)));\n\n% initialize empty faces\nnewFaces = {};\n\n\n% Processing flag for each triangle\n% 1 : triangle to process, 0 : already processed\n% in the beginning, every triangle face need to be processed\nflag = ones(N, 1);\n\n% iterate on each triangular face of the convex hull\nfor iFace = 1:N\n \n % check if face was already performed\n if ~flag(iFace)\n continue;\n end\n\n % indices of faces with same normal\n ind = find(abs(vectorNorm3d(cross(repmat(normals(iFace, :), [N 1]), normals)))\n end\n end\n \n \n % compute order of the vertices in current face\n faceVertices = unique(faces(ind2, :));\n [tmp, I] = angleSort3d(points(faceVertices, :)); %#ok\n \n % create the new face, ensuring it is a row vector\n face = faceVertices(I);\n face = face(:)';\n \n % ensure face has normal pointing outwards\n outerNormal = meshFaceCentroids(points, face) - pointsCentroid;\n if dot(meshFaceNormals(points, face), outerNormal, 2) < 0\n face = face([1 end:-1:2]);\n end\n \n % add a new face to the list\n newFaces = [newFaces {face}]; %#ok\n \n % mark processed faces\n flag(ind2) = 0;\nend\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/minConvexHull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6494854058377298}} {"text": "function [ o, x, w ] = en_r2_05_6 ( n )\n\n%*****************************************************************************80\n%\n%% EN_R2_05_6 implements the Stroud rule 5.6 for region EN_R2.\n%\n% Discussion:\n%\n% The rule has order O = ( N + 1 ) * 2^N.\n%\n% The rule has precision P = 5.\n%\n% EN_R2 is the entire N-dimensional space with weight function\n%\n% w(x) = exp ( - x1^2 - x2^2 ... - xn^2 ) \n%\n% The rule requires 5 <= N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n% 5 <= N.\n%\n% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( n < 5 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EN_R2_05_6 - Fatal error!\\n' );\n fprintf ( 1, ' 5 <= N is required.\\n' );\n error ( 'EN_R2_05_6 - Fatal error!' );\n end\n\n o = 2^n * ( n + 1 );\n volume = sqrt ( pi^n );\n\n a = volume / 2^n / ( n + 1 );\n\n r = sqrt ( ( n - sqrt ( 2 ) + ( n - 1 ) * sqrt ( 2 * ( n + 1 ) ) ) / 2 / n );\n s = sqrt ( ( n - sqrt ( 2 ) - sqrt ( 2 * ( n + 1 ) ) ) / 2 / n );\n t = sqrt ( ( 1 + sqrt ( 2 ) ) / 2 );\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n k = 0;\n%\n% N * 2^N points.\n%\n for i = 1 : n\n\n k = k + 1;\n x(1:n,k) = - s;\n x(i,k) = - r;\n w(k) = a;\n\n more = 1;\n\n while ( more )\n more = 0;\n for j = n : -1 : 1\n if ( x(j,k) < 0.0 )\n k = k + 1;\n x(1:n,k) = x(1:n,k-1);\n x(j,k) = abs ( x(j,k) );\n x(j+1:n,k) = - abs ( x(j+1:n,k) );\n w(k) = a;\n more = 1;\n break;\n end\n end\n end\n\n end\n%\n% 2^N points.\n%\n k = k + 1;\n x(1:n,k) = - t;\n w(k) = a;\n more = 1;\n while ( more )\n more = 0;\n for j = n : -1 : 1\n if ( x(j,k) < 0.0 )\n k = k + 1;\n x(1:n,k) = x(1:n,k-1);\n x(j,k) = abs ( x(j,k) );\n x(j+1:n,k) = - abs ( x(j+1:n,k) );\n w(k) = a;\n more = 1;\n break;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/en_r2_05_6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6494212417144379}} {"text": "%TROTX Rotation about X axis\n%\n% T = TROTX(THETA) is a homogeneous transformation (4x4) representing a rotation \n% of THETA radians about the x-axis.\n%\n% T = TROTX(THETA, 'deg') as above but THETA is in degrees.\n%\n% Notes::\n% - Translational component is zero.\n%\n% See also ROTX, TROTY, TROTZ, TROT2.\n\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 T = trotx(t, varargin)\n\tT = [rotx(t, varargin{:}) [0 0 0]'; 0 0 0 1];\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/trotx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6494212417144379}} {"text": "function x = VBA_spm_invFcdf(F,v,w)\n% Inverse Cumulative Distribution (CDF) of F (Fisher-Snedecor) distribution\n% FORMAT x = spm_invFpdf(F,df)\n% FORMAT x = spm_invFpdf(F,v,w)\n%\n% F - CDF (lower tail p-value)\n% df - Degrees of freedom, concatenated along last dimension\n% Eg. Scalar (or column vector) v & w. Then df=[v,w];\n% v - Shape parameter 1 / numerator degrees of freedom (v>0)\n% w - Shape parameter 2 / denominator degrees of freedom (w>0)\n% x - F-variate (F has range [0,Inf) )\n%__________________________________________________________________________\n%\n% spm_Fcdf implements the inverse Cumulative Distribution Function\n% for the F-distribution.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% The CDF F(x) of the F distribution with degrees of freedom v & w,\n% defined for positive integer degrees of freedom v & w, is the\n% probability that a realisation of an F random variable X has value\n% less than x F(x)=Pr{X0 & w>0, and for x in [0,Inf) (See Evans et al., Ch16).\n%\n% Variate relationships: (Evans et al., Ch16 & 37)\n%--------------------------------------------------------------------------\n% The square of a Student's t variate with w degrees of freedom is\n% distributed as an F-distribution with [1,w] degrees of freedom.\n%\n% For X an F-variate with v,w degrees of freedom, w/(w+v*X^2) has\n% distribution related to a Beta random variable with shape parameters\n% w/2 & v/2, as described below.\n%\n% Algorithm:\n%--------------------------------------------------------------------------\n% Using the routine spm_invBcdf for the Beta distribution, with\n% appropriate parameters: The CDF of the F-distribution with v,w\n% degrees of freedom is related to the incomplete beta function by:\n% Pr(X1;\nif sum(xa)>1 && any(any(diff(as(xa,:)),1))\n error('non-scalar args must match in size');\nend\n\n%-Computation\n%--------------------------------------------------------------------------\n%-Initialise result to zeros\nx = zeros(rs);\n\n%-Only defined for F in [0,1] & strictly positive v & w.\n% Return NaN if undefined.\nmd = ( F>=0 & F<=1 & v>0 & w>0 );\nif any(~md(:))\n x(~md) = NaN;\n warning('Returning NaN for out of range arguments');\nend\n\n%-Special cases: x=0 when F=0, x=Inf when F=1\nx(md & F==1) = Inf;\n\n%-Compute where defined & not special case\nQ = find( md & F>0 & F<1 );\nif isempty(Q), return, end\nif xa(1), QF=Q; else QF=1; end\nif xa(2), Qv=Q; else Qv=1; end\nif xa(3), Qw=Q; else Qw=1; end\n\n%-Compute\nbQ = VBA_spm_invBcdf(1-F(QF),w(Qw)/2,v(Qv)/2);\nx(Q) = (w(Qw)./bQ -w(Qw))./v(Qv);\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/thrid-party/spm/VBA_spm_invFcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6492867607369451}} {"text": "function [in3] = cc2in3(cc)\n% Convert volume from cubic centimeters to cubic inches. \n% Chad Greene 2012\nin3 = cc*0.061023744095;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/cc2in3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6492867505648329}} {"text": "function [tt] = tt_qtoepl(x, d)\n\n% returns the multilevel Toeplitz matrix tt generated by the multi-dimensional input vector x \n% in the QTT format\n%\n% The size of the input vector is 2^(d(1) + 1) x ... x 2^(d(D) + 1),\n% The output matrix is square of order 2^d(1) x ... x 2^d(D).\n% The (i_1,...i_D)-th component of x is not used if at least one of i_1,...,i_D is equal to 1\n% (e. g., in the one-dimensional case the first component of x is not used)\n%\n% April 20, 2011\n% Vladimir Kazeev\n% vladimir.kazeev@gmail.com\n% INM RAS\n% Moscow, Russia\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% For details please see the preprint\n% http://www.mis.mpg.de/publications/preprints/2011/prepr2011-36.html\n% Vladimir A. Kazeev, Boris N. Khoromskij and Eugene E. Tyrtyshnikov\n% Multilevel Toeplitz matrices generated by QTT tensor-structured vectors and convolution with logarithmic complexity\n% January 12, 2012\n% Vladimir Kazeev,\n% Seminar for Applied Mathematics, ETH Zurich\n% vladimir.kazeev@sam.math.ethz.ch\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nD = numel(d);\ntt = tt_qshiftstack(d);\n\nsz=[];\nfor K=1:D\n\tsz = [sz; 4*ones(d(K),1), 2*ones(d(K),1); 1, 2];\nend\n\ntt = tt_qreshape(tt, 3, sz);\ntt = tt_matrix(tt) * x;\n\n\ntt1 = cell(sum(d),1);\nind = 0;\nind1 = 0;\nfor K = 1:D\n\tfor k = 1:d(K)-1\n\t\ttt1{ind1 + k} = tt{ind + k};\n\tend\t\n\t\n\tp = size(tt{ind + d(K)}, 1);\n\tq = size(tt{ind + d(K)}, 3);\n\tr = size(tt{ind + d(K) + 1}, 3);\n\ttt1{ind1 + d(K)} = reshape(reshape(permute(tt{ind+d(K)},[2, 1, 3]),[4*p,q])*...\n reshape(permute(tt{ind+d(K)+1},[2, 1, 3]),[q,r]),[4,p,r]);\n tt1{ind1 + d(K)} = permute(tt1{ind1 + d(K)}, [2, 1, 3]);\n\tind=ind+d(K)+1;\n\tind1=ind1+d(K);\nend\ntt = tt1;\ntt1 = tt_tensor;\ntt = cell2core(tt1, tt);\ntt = tt_matrix(tt);\nreturn\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_qtoepl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6492813621511165}} {"text": "function score = DM(Population,optimum)\n% \n% Metric for diversity\n\n%------------------------------- Reference --------------------------------\n% K. Deb and S. Jain, Running performance metrics for evolutionary\n% multi-objective optimization, KanGAL Report 2002004, 2002.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n PopObj = Population.best.objs;\n if size(PopObj,2) ~= size(optimum,2)\n score = nan;\n else\n fmax = max(optimum,[],1);\n fmin = min(optimum,[],1);\n H = calGrid(optimum(:,1:end-1),fmax(1:end-1),fmin(1:end-1),size(PopObj,1));\n h = H & calGrid(PopObj(:,1:end-1),fmax(1:end-1),fmin(1:end-1),size(PopObj,1));\n score = calM(h,H)./calM(H,H);\n end\nend\n\nfunction h = calGrid(P,fmax,fmin,div)\n% Determine whether each grid has at least one point\n\n [N,M] = size(P);\n d = (fmax-fmin)./div;\n GLoc = ceil((P-repmat(fmin,N,1))./repmat(d,N,1));\n GLoc = max(1,GLoc);\n h = zeros(M,div);\n for i = 1 : M\n h(i,:) = ismember(1:div,GLoc(:,i));\n end\nend\n\nfunction m = calM(h,H)\n% Calculate the value function m()\n\n M = size(h,1);\n h = [ones(M,1),h,ones(M,1)];\n H = [ones(M,1),H,ones(M,1)];\n m = 0;\n for i = 1 : M\n for j = 2 : size(h,2)-1\n if H(i,j)\n if h(i,j)\n if h(i,j-1)\n if h(i,j+1)\n m = m + 1;\n else\n m = m + 0.67;\n end\n else\n if h(i,j+1)\n m = m + 0.67;\n else\n m = m + 0.75;\n end\n end\n else\n if h(i,j-1)\n if h(i,j+1)\n m = m + 0.75;\n else\n m = m + 0.5;\n end\n else\n if h(i,j+1)\n m = m + 0.5;\n else\n m = m + 0;\n end\n end\n end\n end\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Metrics/DM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6492813573525371}} {"text": "function [varargout] = likGumbel(sign, hyp, y, mu, s2, inf, i)\n\n% likGumbel - Gumbel likelihood function for extremal value regression. \n% The expression for the likelihood is\n% likGumbel(t) = exp(-z-exp(-z))/be, z = ga+s*(y-t)/be, be = sn*sqrt(6)/pi\n% where s={+1,-1} is a sign switching between left and right skewed, ga is the\n% Euler-Mascheroni constant, y is the mean, sn^2 is the variance.\n% The skewness and kurtosis of likGumbel are 1.14*s and 2.4, respectively. \n%\n% The hyperparameters are:\n%\n% hyp = [ log(sn) ]\n%\n% Several modes are provided, for computing likelihoods, derivatives and moments\n% respectively, see likFunctions.m for the details. In general, care is taken\n% to avoid numerical issues when the arguments are extreme.\n%\n% Copyright (c) by Hannes Nickisch, 2013-11-01.\n%\n% See also LIKFUNCTIONS.M.\n\nif nargin<4, varargout = {'1'}; return; end % report number of hyperparameters\nif sign=='-', s = -1; else s = 1; end % extract sign of skewness\n\nsn2 = exp(2*hyp); % extract hyperparameters\nga = 0.5772156649; % Euler-Mascheroni constant\nbe = sqrt(6*sn2)/pi;\nlZ = -log(be);\n\nif nargin<6 % prediction mode if inf is not present\n if numel(y)==0, y = zeros(size(mu)); end\n s2zero = 1; if nargin>4, if norm(s2)>0, s2zero = 0; end, end % s2==0 ?\n if s2zero % log probability evaluation\n lp = likGumbel(sign, hyp, y, mu, [], 'infLaplace'); s2 = 0;\n else % prediction\n lp = likGumbel(sign, hyp, y, mu, s2, 'infEP');\n end\n ymu = {}; ys2 = {};\n if nargout>1\n ymu = mu; % first y moment\n if nargout>2\n ys2 = s2 + sn2; % second y moment\n end\n end\n varargout = {lp,ymu,ys2};\nelse\n switch inf \n case 'infLaplace'\n z = ga+s*(y-mu)/be; emz = exp(-z);\n if nargin<7 % no derivative mode\n dlp = {}; d2lp = {}; d3lp = {};\n lp = lZ -z -emz;\n if nargout>1\n dz = -s/be; % dz/dmu\n dlp = dz*(emz-1); % dlp, derivative of log likelihood\n if nargout>2 % d2lp, 2nd derivative of log likelihood\n d2lp = -dz^2*emz;\n if nargout>3 % d3lp, 3rd derivative of log likelihood\n d3lp = dz^3*emz;\n end\n end\n end\n varargout = {lp,dlp,d2lp,d3lp};\n else % derivative w.r.t. log(sn)\n dz = -s/be; % dz/dmu\n dzs = -s*(y-mu)/be; % dz/dlog(sn)\n lp_dhyp = dzs.*(emz-1) -1;\n dlp_dhyp = dz*(1-emz.*(1+dzs));\n d2lp_dhyp = dz^2*emz.*(2+dzs);\n varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};\n end\n\n case 'infEP'\n if nargout>1\n error('infEP not supported since likT is not log-concave')\n end\n n = max([length(y),length(mu),length(s2)]); on = ones(n,1);\n y = y(:).*on; mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only\n % since we are not aware of an analytical expression of the integral, \n % we use Gaussian-Hermite quadrature\n N = 20; [t,w] = gauher(N); oN = ones(1,N);\n lZ = likGumbel(sign, hyp, y*oN, sig*t'+mu*oN, []);\n lZ = log_expA_x(lZ,w); % log( exp(lZ)*w )\n varargout = {lZ};\n\n case 'infVB'\n error('infVB not supported')\n end\nend\n\n% computes y = log( exp(A)*x ) in a numerically safe way by subtracting the\n% maximal value in each row to avoid cancelation after taking the exp\nfunction y = log_expA_x(A,x)\n N = size(A,2); maxA = max(A,[],2); % number of columns, max over columns\n y = log(exp(A-maxA*ones(1,N))*x) + maxA; % exp(A) = exp(A-max(A))*exp(max(A))", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/lik/likGumbel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6492813314068783}} {"text": "function dz = dynamics_6_link(~,z,P) \n%DZ = DYNAMICS_6_LINK(T,Z,P)\n% \n%FUNCTION: This function computes the dynamics of a 6\n% link pendulum, and is designed to be called from ode45.\n% The model allows for arbitrary mass and inertia for each\n% link, but no friction or actuation\n% \n%INPUTS: \n% t = time. Dummy input for ode45. Not used.\n% z = [12 X nTime] matrix of states\n% P = struct of parameters\n%OUTPUTS: \n% dz = [12 X nTime] matrix of state derivatives\n% \n%NOTES:\n% This file was automatically generated by writeDynamics.m\n\ng = P.g ; %gravity\nm1 = P.m(1); % Link 1 mass\nm2 = P.m(2); % Link 2 mass\nm3 = P.m(3); % Link 3 mass\nm4 = P.m(4); % Link 4 mass\nm5 = P.m(5); % Link 5 mass\nm6 = P.m(6); % Link 6 mass\nl1 = P.l(1); % Link 1 length\nl2 = P.l(2); % Link 2 length\nl3 = P.l(3); % Link 3 length\nl4 = P.l(4); % Link 4 length\nl5 = P.l(5); % Link 5 length\nl6 = P.l(6); % Link 6 length\nI1 = P.I(1); % Link 1 moment of inertia about its center of mass\nI2 = P.I(2); % Link 2 moment of inertia about its center of mass\nI3 = P.I(3); % Link 3 moment of inertia about its center of mass\nI4 = P.I(4); % Link 4 moment of inertia about its center of mass\nI5 = P.I(5); % Link 5 moment of inertia about its center of mass\nI6 = P.I(6); % Link 6 moment of inertia about its center of mass\nd1 = P.d(1); % Link 1 distance between center of mass and parent joint\nd2 = P.d(2); % Link 2 distance between center of mass and parent joint\nd3 = P.d(3); % Link 3 distance between center of mass and parent joint\nd4 = P.d(4); % Link 4 distance between center of mass and parent joint\nd5 = P.d(5); % Link 5 distance between center of mass and parent joint\nd6 = P.d(6); % Link 6 distance between center of mass and parent joint\n\nnTime = size(z,2);\ndz = zeros(size(z)); \nM = zeros(6,6,nTime);\nf = zeros(6,nTime);\n\nth1 = z(1,:); \nth2 = z(2,:); \nth3 = z(3,:); \nth4 = z(4,:); \nth5 = z(5,:); \nth6 = z(6,:); \n\ndth1 = z(7,:); \ndth2 = z(8,:); \ndth3 = z(9,:); \ndth4 = z(10,:); \ndth5 = z(11,:); \ndth6 = z(12,:); \n\ndz(1,:) = dth1; \ndz(2,:) = dth2; \ndz(3,:) = dth3; \ndz(4,:) = dth4; \ndz(5,:) = dth5; \ndz(6,:) = dth6; \n\nM(1,1,:) = - I1 - d1.^2.*m1 - l1.^2.*m2 - l1.^2.*m3 - l1.^2.*m4 - l1.^2.*m5 - l1.^2.*m6;\nM(1,2,:) = -l1.*cos(th1 - th2).*(d2.*m2 + l2.*m3 + l2.*m4 + l2.*m5 + l2.*m6);\nM(1,3,:) = -l1.*cos(th1 - th3).*(d3.*m3 + l3.*m4 + l3.*m5 + l3.*m6);\nM(1,4,:) = -l1.*cos(th1 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(1,5,:) = -l1.*cos(th1 - th5).*(d5.*m5 + l5.*m6);\nM(1,6,:) = -d6.*l1.*m6.*cos(th1 - th6);\nM(2,1,:) = -l1.*cos(th1 - th2).*(d2.*m2 + l2.*m3 + l2.*m4 + l2.*m5 + l2.*m6);\nM(2,2,:) = - I2 - d2.^2.*m2 - l2.^2.*m3 - l2.^2.*m4 - l2.^2.*m5 - l2.^2.*m6;\nM(2,3,:) = -l2.*cos(th2 - th3).*(d3.*m3 + l3.*m4 + l3.*m5 + l3.*m6);\nM(2,4,:) = -l2.*cos(th2 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(2,5,:) = -l2.*cos(th2 - th5).*(d5.*m5 + l5.*m6);\nM(2,6,:) = -d6.*l2.*m6.*cos(th2 - th6);\nM(3,1,:) = -l1.*cos(th1 - th3).*(d3.*m3 + l3.*m4 + l3.*m5 + l3.*m6);\nM(3,2,:) = -l2.*cos(th2 - th3).*(d3.*m3 + l3.*m4 + l3.*m5 + l3.*m6);\nM(3,3,:) = - I3 - d3.^2.*m3 - l3.^2.*m4 - l3.^2.*m5 - l3.^2.*m6;\nM(3,4,:) = -l3.*cos(th3 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(3,5,:) = -l3.*cos(th3 - th5).*(d5.*m5 + l5.*m6);\nM(3,6,:) = -d6.*l3.*m6.*cos(th3 - th6);\nM(4,1,:) = -l1.*cos(th1 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(4,2,:) = -l2.*cos(th2 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(4,3,:) = -l3.*cos(th3 - th4).*(d4.*m4 + l4.*m5 + l4.*m6);\nM(4,4,:) = - I4 - d4.^2.*m4 - l4.^2.*m5 - l4.^2.*m6;\nM(4,5,:) = -l4.*cos(th4 - th5).*(d5.*m5 + l5.*m6);\nM(4,6,:) = -d6.*l4.*m6.*cos(th4 - th6);\nM(5,1,:) = -l1.*cos(th1 - th5).*(d5.*m5 + l5.*m6);\nM(5,2,:) = -l2.*cos(th2 - th5).*(d5.*m5 + l5.*m6);\nM(5,3,:) = -l3.*cos(th3 - th5).*(d5.*m5 + l5.*m6);\nM(5,4,:) = -l4.*cos(th4 - th5).*(d5.*m5 + l5.*m6);\nM(5,5,:) = - I5 - d5.^2.*m5 - l5.^2.*m6;\nM(5,6,:) = -d6.*l5.*m6.*cos(th5 - th6);\nM(6,1,:) = -d6.*l1.*m6.*cos(th1 - th6);\nM(6,2,:) = -d6.*l2.*m6.*cos(th2 - th6);\nM(6,3,:) = -d6.*l3.*m6.*cos(th3 - th6);\nM(6,4,:) = -d6.*l4.*m6.*cos(th4 - th6);\nM(6,5,:) = -d6.*l5.*m6.*cos(th5 - th6);\nM(6,6,:) = - I6 - d6.^2.*m6;\n\nf(1,:) = - d1.*g.*m1.*cos(th1) - g.*l1.*m2.*cos(th1) - g.*l1.*m3.*cos(th1) - g.*l1.*m4.*cos(th1) - g.*l1.*m5.*cos(th1) - g.*l1.*m6.*cos(th1) - d2.*dth2.^2.*l1.*m2.*sin(th1 - th2) - d3.*dth3.^2.*l1.*m3.*sin(th1 - th3) - d4.*dth4.^2.*l1.*m4.*sin(th1 - th4) - d5.*dth5.^2.*l1.*m5.*sin(th1 - th5) - d6.*dth6.^2.*l1.*m6.*sin(th1 - th6) - dth2.^2.*l1.*l2.*m3.*sin(th1 - th2) - dth2.^2.*l1.*l2.*m4.*sin(th1 - th2) - dth2.^2.*l1.*l2.*m5.*sin(th1 - th2) - dth2.^2.*l1.*l2.*m6.*sin(th1 - th2) - dth3.^2.*l1.*l3.*m4.*sin(th1 - th3) - dth3.^2.*l1.*l3.*m5.*sin(th1 - th3) - dth3.^2.*l1.*l3.*m6.*sin(th1 - th3) - dth4.^2.*l1.*l4.*m5.*sin(th1 - th4) - dth4.^2.*l1.*l4.*m6.*sin(th1 - th4) - dth5.^2.*l1.*l5.*m6.*sin(th1 - th5);\nf(2,:) = d2.*dth1.^2.*l1.*m2.*sin(th1 - th2) - g.*l2.*m3.*cos(th2) - g.*l2.*m4.*cos(th2) - g.*l2.*m5.*cos(th2) - g.*l2.*m6.*cos(th2) - d2.*g.*m2.*cos(th2) - d3.*dth3.^2.*l2.*m3.*sin(th2 - th3) - d4.*dth4.^2.*l2.*m4.*sin(th2 - th4) - d5.*dth5.^2.*l2.*m5.*sin(th2 - th5) - d6.*dth6.^2.*l2.*m6.*sin(th2 - th6) + dth1.^2.*l1.*l2.*m3.*sin(th1 - th2) + dth1.^2.*l1.*l2.*m4.*sin(th1 - th2) + dth1.^2.*l1.*l2.*m5.*sin(th1 - th2) + dth1.^2.*l1.*l2.*m6.*sin(th1 - th2) - dth3.^2.*l2.*l3.*m4.*sin(th2 - th3) - dth3.^2.*l2.*l3.*m5.*sin(th2 - th3) - dth3.^2.*l2.*l3.*m6.*sin(th2 - th3) - dth4.^2.*l2.*l4.*m5.*sin(th2 - th4) - dth4.^2.*l2.*l4.*m6.*sin(th2 - th4) - dth5.^2.*l2.*l5.*m6.*sin(th2 - th5);\nf(3,:) = d3.*dth1.^2.*l1.*m3.*sin(th1 - th3) - g.*l3.*m4.*cos(th3) - g.*l3.*m5.*cos(th3) - g.*l3.*m6.*cos(th3) - d3.*g.*m3.*cos(th3) + d3.*dth2.^2.*l2.*m3.*sin(th2 - th3) - d4.*dth4.^2.*l3.*m4.*sin(th3 - th4) - d5.*dth5.^2.*l3.*m5.*sin(th3 - th5) - d6.*dth6.^2.*l3.*m6.*sin(th3 - th6) + dth1.^2.*l1.*l3.*m4.*sin(th1 - th3) + dth1.^2.*l1.*l3.*m5.*sin(th1 - th3) + dth1.^2.*l1.*l3.*m6.*sin(th1 - th3) + dth2.^2.*l2.*l3.*m4.*sin(th2 - th3) + dth2.^2.*l2.*l3.*m5.*sin(th2 - th3) + dth2.^2.*l2.*l3.*m6.*sin(th2 - th3) - dth4.^2.*l3.*l4.*m5.*sin(th3 - th4) - dth4.^2.*l3.*l4.*m6.*sin(th3 - th4) - dth5.^2.*l3.*l5.*m6.*sin(th3 - th5);\nf(4,:) = d4.*dth1.^2.*l1.*m4.*sin(th1 - th4) - g.*l4.*m5.*cos(th4) - g.*l4.*m6.*cos(th4) - d4.*g.*m4.*cos(th4) + d4.*dth2.^2.*l2.*m4.*sin(th2 - th4) + d4.*dth3.^2.*l3.*m4.*sin(th3 - th4) - d5.*dth5.^2.*l4.*m5.*sin(th4 - th5) - d6.*dth6.^2.*l4.*m6.*sin(th4 - th6) + dth1.^2.*l1.*l4.*m5.*sin(th1 - th4) + dth1.^2.*l1.*l4.*m6.*sin(th1 - th4) + dth2.^2.*l2.*l4.*m5.*sin(th2 - th4) + dth2.^2.*l2.*l4.*m6.*sin(th2 - th4) + dth3.^2.*l3.*l4.*m5.*sin(th3 - th4) + dth3.^2.*l3.*l4.*m6.*sin(th3 - th4) - dth5.^2.*l4.*l5.*m6.*sin(th4 - th5);\nf(5,:) = d5.*dth1.^2.*l1.*m5.*sin(th1 - th5) - g.*l5.*m6.*cos(th5) - d5.*g.*m5.*cos(th5) + d5.*dth2.^2.*l2.*m5.*sin(th2 - th5) + d5.*dth3.^2.*l3.*m5.*sin(th3 - th5) + d5.*dth4.^2.*l4.*m5.*sin(th4 - th5) - d6.*dth6.^2.*l5.*m6.*sin(th5 - th6) + dth1.^2.*l1.*l5.*m6.*sin(th1 - th5) + dth2.^2.*l2.*l5.*m6.*sin(th2 - th5) + dth3.^2.*l3.*l5.*m6.*sin(th3 - th5) + dth4.^2.*l4.*l5.*m6.*sin(th4 - th5);\nf(6,:) = d6.*m6.*(dth1.^2.*l1.*sin(th1 - th6) - g.*cos(th6) + dth2.^2.*l2.*sin(th2 - th6) + dth3.^2.*l3.*sin(th3 - th6) + dth4.^2.*l4.*sin(th4 - th6) + dth5.^2.*l5.*sin(th5 - th6));\n\nfor i=1:nTime \n MM = M(:,:,i); ff = f(:,i); \n dz(7:12,i) = -MM \\ ff;\nend \n\nend \n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/nLinkPendulum/dynamics_6_link.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6492374145221932}} {"text": "function digit = r8_digit ( x, idigit )\n\n%*****************************************************************************80\n%\n%% R8_DIGIT returns a particular decimal digit of an R8.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 20 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose NDIG-th decimal digit\n% is desired. If X is zero, all digits will be returned as 0.\n%\n% Input, integer IDIGIT, the position of the desired decimal digit.\n% A value of 1 means the leading digit, a value of 2 the second digit\n% and so on.\n%\n% Output, integer DIGIT, the value of the IDIGIT-th decimal digit of X.\n%\n if ( x == 0.0 )\n digit = 0;\n return\n end\n\n if ( idigit <= 0 )\n digit = 0;\n return\n end\n%\n% Force X to lie between 1 and 10.\n%\n x = abs ( x );\n\n while ( x < 1.0 )\n x = x * 10.0;\n end\n\n while ( 10.0 <= x )\n x = x / 10.0;\n end\n\n for i = 1 : idigit\n ival = floor ( x );\n x = ( x - ival ) * 10.0;\n end\n\n digit = ival;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_digit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6492238724362518}} {"text": "function srad = solarradiation(dem,lat,cs,r)\n% PUPROSE: Calculate solar radiation for a digital elevation model (DEM)\n% over one year for clear sky conditions in W/m2\n% -------------------------------------------------------------------\n% USAGE: srad = solarradiation(dem,lat,cs)\n% where: dem is the DEM to calculate hillshade for\n% lat is the latitude vector for the DEM - same size as size(dem,2)\n% cs is the cellsize in meters\n% r is the ground reflectance (global value or map, default is 0.2)\n%\n% srad is the solar radiation in W/m2 over one year per grid cell\n%\n% EXAMPLE:\n% srad = solarradiation(peaks(50)*100,54.9:-0.1:50,1000,0.2);\n% - calculates the solar radiation for an example 50x50 peak surface.\n%\n% See also: GRADIENT, CART2POL\n%\n% Note: Follows the approach of Kumar et al 1997. Calculates clear sky\n% radiation corrected for the incident angle (selfshading) plus\n% diffuse and reflected radiation. Insolation is depending on time of year (and day), \n% latitude, elevation, slope and aspect. \n% Relief shading is not considered.\n% Script uses simple unweighed gradient of 4 nearest neighbours for slope\n% calculation.\n%\n% Reference: Kumar, L, Skidmore AK and Knowles E 1997: Modelling topographic variation in solar radiation in \n% a GIS environment. Int.J.Geogr.Info.Sys. 11(5), 475-497\n%\n%\n% Felix Hebeler, Dept. of Geography, University Zurich, May 2008.\n\n\n%% parameters\n%It ; % total hours of daily sunshine (calculated inline)\n%M ; % air mass ratio parameter (calculated inline)\n%r = 0.20; % ground reflectance coefficient (more sensible to give as input)\n%L=lat; %latitude\nn = 1; % timestep of calculation over sunshine hours: 1=hourly, 0.5=30min, 2=2hours etc\ntau_a = 365; %length of the year in days\nS0 = 1367; % solar constant W m^-2 default 1367\n\ndr= 0.0174532925; % degree to radians conversion factor\n\n%% convert factors\n[slop,asp]=get_ders(dem,cs); % calculate slope and aspect in radians using given cellsize cs\n[dummy,L]=meshgrid(1:size(dem,2),lat); % grid latitude\nclear dummy;\nL=L*dr; % convert to radians\nfcirc = 360*dr; % 360 degrees in radians\n\n%% some setup calculations\nsrad=0;\nsinL=sin(L);\ncosL=cos(L);\ntanL=tan(L);\nsinSlop=sin(slop);\ncosSlop=cos(slop);\ncosSlop2=cosSlop.*cosSlop;\nsinSlop2=sinSlop.*sinSlop;\nsinAsp=sin(asp);\ncosAsp=cos(asp);\nterm1 = ( sinL.*cosSlop - cosL.*sinSlop.*cosAsp);\nterm2 = ( cosL.*cosSlop + sinL.*sinSlop.*cosAsp);\nterm3 = sinSlop.*sinAsp;\n%% loop over year\nfor d = 1:tau_a; \n %display(['Calculating melt for day ',num2str(d)]) \n % clear sky solar radiation\n I0 = S0 * (1 + 0.0344*cos(fcirc*d/tau_a)); % extraterr rad per day \n % sun declination dS\n dS = 23.45 * dr* sin(fcirc * ( (284+d)/tau_a ) ); %in radians, correct/verified\n % angle at sunrise/sunset\n % t = 1:It; % sun hour \n hsr = real(acos(-tanL*tan(dS))); % angle at sunrise\n % this only works for latitudes up to 66.5 deg N! Workaround:\n % hsr(hsr<-1)=acos(-1);\n % hsr(hsr>1)=acos(1);\n It=round(12*(1+mean(hsr(:))/pi)-12*(1-mean(hsr(:))/pi)); % calc daylength\n%% daily loop\n I=0;\n for t=1:n:It % loop over sunshine hours\n % if accounting for shading should be included, calc hillshade here\n % hourangle of sun hs \n hs=hsr-(pi*t/It); % hs(t)\n %solar angle and azimuth\n %alpha = asin(sinL*sin(dS)+cosL*cos(dS)*cos(hs));% solar altitude angle\n sinAlpha = sinL.*sin(dS)+cosL.*cos(dS).*cos(hs);\n %alpha_s = asin(cos(dS)*sin(hs)/cos(alpha)); % solar azimuth angle\n % correction using atmospheric transmissivity taub_b\n M=sqrt(1229+((614.*sinAlpha)).^2)-614.*sinAlpha; % Air mass ratio\n tau_b = 0.56 * (exp(-0.65*M) + exp(-0.095*M));\n tau_d = 0.271-0.294*tau_b; % radiation diffusion coefficient for diffuse insolation\n tau_r = 0.271+0.706*tau_b; % reflectance transmitivity\n % correct for local incident angle\n cos_i = (sin(dS).*term1) + (cos(dS).*cos(hs).*term2) + (cos(dS).*term3.*sin(hs));\n Is = I0 * tau_b; % potential incoming shortwave radiation at surface normal (equator)\n % R = potential clear sky solar radiation W m2\n R = Is .* cos_i;\n R(R<0)=0; % kick out negative values\n Id = I0 .* tau_d .* cosSlop2./ 2.*sinAlpha; %diffuse radiation;\n Ir = I0 .* r .* tau_r .* sinSlop2./ 2.* sinAlpha; % reflectance\n R= R + Id + Ir;\n R(R<0)=0; \n I=I+R;% solar radiation per day (sunshine hours) \n end % end of sun hours in day loop\n%% add up radiation part melt for every day\n srad = srad + I;\nend % end of days in year loop\n\n\n%%\nfunction [grad,asp] = get_ders(dem,cs)\n% calculate slope and aspect (deg) using GRADIENT function\n[fx,fy] = gradient(dem,cs,cs); % uses simple, unweighted gradient of immediate neighbours\n[asp,grad]=cart2pol(fy,fx); % convert to carthesian coordinates\ngrad=atan(grad); %steepest slope\nasp=asp.*-1+pi; % convert asp 0 facing south\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/19791-solar-radiation/solarradiation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6491515400853329}} {"text": "function J = evalObjectiveFCN(u,x,xref,Q,R,Ru)\n% [J,Js,Ju]\n%% Cost function of nonlinear MPC for Lotka-Volterra system\n%\n% Inputs:\n% u: optimization variable, from time k to time k+N-1 \n% x: current state at time k\n% Ts: controller sample time\n% N: prediction horizon\n% xref: state references, constant from time k+1 to k+N\n% u0: previous controller output at time k-1\n%\n% Output:\n% J: objective function cost\n%\n\n%% Nonlinear MPC design parameters\n\n%% Cost Calculation\n% Set initial cost and input\nN = size(x,2);\nJ = zeros(N,1);\nu0 = 0;\n\n% Loop through each time step\nfor ct=1:N\n \n % Accumulate state tracking cost from x(k+1) to x(k+N)\n J(ct) = (x(:,ct)-xref(:,ct))'*Q*(x(:,ct)-xref(:,ct));\n \n % Accumulate MV rate of change cost from u(k) to u(k+N-1)\n if ct==1\n J(ct) = J(ct) + (u(:,ct)-u0)'*R*(u(:,ct)-u0) + u(:,ct)'*Ru*u(:,ct);\n else\n J(ct) = J(ct) + (u(:,ct)-u(:,ct-1))'*R*(u(:,ct)-u(:,ct-1)) + u(:,ct)'*Ru*u(:,ct);\n end\nend\n\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LOTKA_VOLTERRA/evalObjectiveFCN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6491021497398698}} {"text": "function desired_state = desiredState(traj_obj, t)\n%desiredState computes desired position (x,y,z), yaw and its derivatives \n% INPUT\n% \n\ntau_vec = traj_obj.tau_vec';\nP = traj_obj.P;\npath = traj_obj.path;\n\n% Check dimensions\nif size(path,2) ~= size(P,2)\n path = path';\nend\n\ncumsum_tau_vec = cumsum(tau_vec);\nts = [0; cumsum_tau_vec(:)];\nD = size(P,2);\n\n% Declare variables\npos = zeros(1,D);\nvel = zeros(1,D);\nacc = zeros(1,D);\njerk = zeros(1,D);\nsnap = zeros(1,D);\n\n\n% If time is out of range, return the end point of the path\nif t < 0\n error('time has to be greater than zero.')\nelseif t >= sum(tau_vec)\n pos = path(end,:);\nelse\n k = find(ts<=t);\n k = k(end);\n for m = 1:D\n tau = t-ts(k);\n pos(m) = [tau^9,tau^8,tau^7,tau^6,tau^5,tau^4,tau^3,tau^2,tau,1] * P(10*k:-1:10*(k-1)+1,m);\n vel(m) = [9*tau^8,8*tau^7,7*tau^6,6*tau^5,5*tau^4,4*tau^3,3*tau^2,2*tau,1,0] * P(10*k:-1:10*(k-1)+1,m);\n acc(m) = [72*tau^7,56*tau^6,42*tau^5,30*tau^4,20*tau^3,12*tau^2,6*tau,2,0,0] * P(10*k:-1:10*(k-1)+1,m);\n jerk(m) = [504*tau^6,336*tau^5,210*tau^4,120*tau^3,60*tau^2,24*tau,6,0,0,0] * P(10*k:-1:10*(k-1)+1,m);\n snap(m) = [3024*tau^5,1680*tau^4,840*tau^3,360*tau^2,120*tau,24,0,0,0,0] * P(10*k:-1:10*(k-1)+1,m);\n% pos(m) = polyval(P(10*k:-1:10*(k-1)+1,m),t-ts(k));\n% vel(m) = polyval(polyder(P(10*k:-1:10*(k-1)+1,m)),t-ts(k));\n% acc(m) = polyval(polyder(polyder(P(10*k:-1:10*(k-1)+1,m))),t-ts(k));\n% jerk(m) = polyval(polyder(polyder(polyder(P(10*k:-1:10*(k-1)+1,m)))),t-ts(k));\n% snap(m) = polyval(polyder(polyder(polyder(polyder(P(10*k:-1:10*(k-1)+1,m))))),t-ts(k));\n end\nend\n\n% Desired yaw and its derivatives are all zero.\nyaw = 0;\nyawdot = 0;\nyawddot = 0;\n\ndesired_state.pos = pos(:);\ndesired_state.vel = vel(:);\ndesired_state.acc = acc(:);\ndesired_state.jerk = jerk(:);\ndesired_state.snap = snap(:);\ndesired_state.yaw = yaw;\ndesired_state.yawdot = yawdot;\ndesired_state.yawddot = yawddot;", "meta": {"author": "yorgoon", "repo": "minimum-snap-geometric-control", "sha": "efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac", "save_path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control", "path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control/minimum-snap-geometric-control-efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac/poly_optimization/desiredState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.649069929993857}} {"text": "function p = eval_pdf_clg(X,Y,mu,Sigma,W)\n% function p = eval_pdf_clg(X,Y,mu,Sigma,W)\n%\n% p(c,t) = N(Y(:,t); mu(:,c) + W(:,:,c)*X(:,t), Sigma(:,:,c))\n\n[d T] = size(Y);\n[d nc] = size(mu);\np = zeros(nc,T);\nfor c=1:nc\n denom = (2*pi)^(d/2)*sqrt(abs(det(Sigma(:,:,c))));\n M = repmat(mu(:,c), 1, T) + W(:,:,c)*X;\n mahal = sum(((Y-M)'*inv(Sigma(:,:,c))).*(Y-M)',2); \n p(c,:) = (exp(-0.5*mahal) / denom)';\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/murphy/KPMstats/clg_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6490699118672791}} {"text": "function [ t, w ] = u_quadrature_rule ( n )\n\n%*****************************************************************************80\n%\n%% U_QUADRATURE_RULE: quadrature rule for U(n,x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real T(N,1), W(N,1), the points and weights of the rule.\n%\n aj = zeros ( n, 1 );\n\n bj = 0.5 * ones ( n, 1 );\n\n w = zeros ( n, 1 );\n w(1,1) = sqrt ( pi / 2.0 );\n\n [ t, w ] = imtqlx ( n, aj, bj, w );\n\n w(1:n,1) = w(1:n,1).^2;\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/chebyshev_polynomial/u_quadrature_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6490432389613516}} {"text": "function value = box_contains_segment_nd ( dim_num, p1, p2, pa, pb )\n\n%*****************************************************************************80\n%\n%% BOX_CONTAINS_SEGMENT_ND reports if a box contains a line segment in ND.\n%\n% Discussion:\n%\n% A box is assumed to be a rectangle with sides aligned on coordinate\n% axes. It can be described by its low and high corner, P1 and P2:\n%\n% points P so that P1(1:DIM_NUM) <= P(1:DIM_NUM) <= P2(1:DIM_NUM).\n%\n% A line segment is the finite portion of a line that lies between\n% two points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real P1(DIM_NUM), P2(DIM_NUM), the low and high corners of the box.\n%\n% Input, real PA(DIM_NUM), PB(DIM_NUM), the endpoints of the line segment.\n%\n% Output, logical VALUE, is TRUE if the box contains\n% the line segment.\n%\n value = 0;\n\n if ( ~box_contains_point_nd ( dim_num, p1, p2, pa ) )\n return\n end\n\n if ( ~box_contains_point_nd ( dim_num, p1, p2, pb ) )\n return\n end\n\n value = 1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/box_contains_segment_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.649043235201696}} {"text": "%% Canny Edge Detection\n% This sample demonstrates Canny edge detection.\n%\n% In this demo, we show how to use the OpenCV function |cv.Canny| to implement\n% the Canny Edge Detector.\n%\n% Sources:\n%\n% * \n% * \n% * \n% * \n% * \n%\n\n%% Theory\n%\n% The _Canny Edge detector_ was developed by John F. Canny in 1986. Also known\n% to many as the _optimal detector_, the Canny algorithm aims to satisfy three\n% main criteria:\n%\n% * *Low error rate:* Meaning a good detection of only existent edges.\n% * *Good localization:* The distance between edge pixels detected and real\n% edge pixels have to be minimized.\n% * *Minimal response:* Only one detector response per edge.\n%\n%% Steps\n%\n% 1) Filter out any noise. The Gaussian filter is used for this purpose. An\n% example of a Gaussian kernel of $size = 5$ that might be used is shown\n% below:\n%\n% $$K = \\frac{1}{159}\n% \\left[{\\matrix{\n% 2 & 4 & 5 & 4 & 2 \\cr\n% 4 & 9 & 12 & 9 & 4 \\cr\n% 5 & 12 & 15 & 12 & 5 \\cr\n% 4 & 9 & 12 & 9 & 4 \\cr\n% 2 & 4 & 5 & 4 & 2\n% }}\\right]$$\n%\n% 2) Find the intensity gradient of the image. For this, we follow a procedure\n% analogous to Sobel:\n%\n% * Apply a pair of convolution masks (in $x$ and $y$ directions):\n%\n% $$G_{x} = \\left[{\\matrix{\n% -1 & 0 & +1 \\cr\n% -2 & 0 & +2 \\cr\n% -1 & 0 & +1\n% }}\\right]$$\n%\n% $$G_{y} = \\left[{\\matrix{\n% -1 & -2 & -1 \\cr\n% 0 & 0 & 0 \\cr\n% +1 & +2 & +1\n% }}\\right]$$\n%\n% * Find the gradient strength and direction. The direction is rounded to\n% one of four possible angles (namely 0, 45, 90 or 135)\n%\n% $$G = \\sqrt{ G_{x}^{2} + G_{y}^{2} }$$\n%\n% $$\\theta = \\arctan(\\frac{ G_{y} }{ G_{x} })$$\n%\n% 3) _Non-maximum suppression_ is applied. This removes pixels that are not\n% considered to be part of an edge. Hence, only thin lines (candidate edges)\n% will remain.\n%\n% 4) _Hysteresis_: The final step. Canny does use two thresholds\n% (_upper_ and _lower_). Canny recommended a |upper:lower| ratio between\n% 2:1 and 3:1.\n%\n% * If a pixel gradient is higher than the _upper_ threshold, the pixel is\n% accepted as an edge\n% * If a pixel gradient value is below the _lower_ threshold, then it is\n% rejected.\n% * If the pixel gradient is between the two thresholds, then it will be\n% accepted only if it is connected to a pixel that is above the _upper_\n% threshold.\n%\n% For more details, you can always consult your favorite Computer Vision book.\n%\n\n%% Code\n%\n% This program:\n%\n% * Asks the user to enter a numerical value to set the lower threshold for\n% our _Canny Edge Detector_ (by means of a slider)\n% * Applies the _Canny Detector_ and generates a *mask* (bright lines\n% representing the edges on a black background)\n% * Applies the mask obtained on the original image and display it in a window\n%\n\nfunction varargout = edge_demo_gui(im)\n % load source image\n if nargin < 1\n im = fullfile(mexopencv.root(),'test','fruits.jpg');\n src = cv.imread(im, 'Color',true);\n elseif ischar(im)\n src = cv.imread(im, 'Color',true);\n else\n src = im;\n end\n\n % create the UI\n h = buildGUI(src);\n if nargout > 0, varargout{1} = h; end\nend\n\nfunction onChange(~,~,h)\n %ONCHANGE Event handler for UI controls\n\n % retrieve current values from UI controls\n apertures = [3, 5, 7];\n aIdx = get(h.pop, 'Value');\n thresh = round(get(h.slid, 'Value'));\n set(h.txt, 'String',sprintf('Threshold: %3d',thresh));\n\n % convert image to grayscale, and blur to reduce the noise\n gray = cv.cvtColor(h.src, 'RGB2GRAY');\n gray = cv.blur(gray, 'KSize',[3 3]);\n\n % detect edges, with 3:1 as threshold ratio\n if true\n % default canny (Sobel gradient)\n edges = cv.Canny(gray, thresh*[1 3], 'ApertureSize',apertures(aIdx));\n else\n % canny with custom gradient (Scharr)\n dx = cv.Scharr(gray, 'DDepth','int16', 'XOrder',1, 'YOrder',0);\n dy = cv.Scharr(gray, 'DDepth','int16', 'XOrder',0, 'YOrder',1);\n edges = cv.Canny2(dx, dy, thresh*[1 3]);\n end\n\n % apply edges mask on original image\n if true\n out = cv.copyTo(h.src, 'Mask',edges);\n else\n out = bsxfun(@times, h.src, uint8(edges~=0));\n end\n\n % show result\n set(h.img, 'CData',out);\n drawnow;\nend\n\nfunction h = buildGUI(img)\n %BUILDGUI Creates the UI\n\n % parameters\n thresh = 10;\n max_thresh = 150;\n sz = size(img);\n sz(2) = max(sz(2), 300); % minimum figure width\n\n % build the user interface (no resizing to keep it simple)\n h = struct();\n h.src = img;\n h.fig = figure('Name','Edge map', ...\n 'NumberTitle','off', 'Menubar','none', 'Resize','off', ...\n 'Position',[200 200 sz(2) sz(1)+29]);\n if ~mexopencv.isOctave()\n %HACK: not implemented in Octave\n movegui(h.fig, 'center');\n end\n h.ax = axes('Parent',h.fig, ...\n 'Units','pixels', 'Position',[1 30 sz(2) sz(1)]);\n if ~mexopencv.isOctave()\n h.img = imshow(img, 'Parent',h.ax);\n else\n %HACK: https://savannah.gnu.org/bugs/index.php?45473\n axes(h.ax);\n h.img = imshow(img);\n end\n uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n 'Position',[5 5 65 20], 'String','Aperture');\n h.pop = uicontrol('Parent',h.fig, 'Style','popupmenu', 'Value',1, ...\n 'Position',[70 5 40 20], 'String',{'3','5','7'});\n h.txt = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n 'Position',[110 5 120 20], 'String',sprintf('Threshold: %3d',thresh));\n h.slid = uicontrol('Parent',h.fig, 'Style','slider', 'Value',thresh, ...\n 'Min',0, 'Max',max_thresh, 'SliderStep',[1 10]./(max_thresh-0), ...\n 'Position',[230 5 sz(2)-230-5 20]);\n\n % hook event handlers, and trigger default start\n set([h.pop, h.slid], 'Callback',{@onChange,h}, ...\n 'Interruptible','off', 'BusyAction','cancel');\n onChange([],[],h);\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/edge_demo_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.649023035030048}} {"text": "classdef TP5 < PROBLEM\n% \n% Test problem for robust multi-objective optimization\n% delta --- 0.05 --- Maximum disturbance degree\n% H --- 50 --- Number of disturbances\n\n%------------------------------- Reference --------------------------------\n% A. Gaspar-Cunha, J. Ferreira, and G. Recio, Evolutionary robustness\n% analysis for multi-objective optimization: benchmark problems, Structural\n% and Multidisciplinary Optimization, 2014, 49: 771-793.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n delta; % Maximum disturbance degree\n H; % Number of disturbances\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n [obj.delta,obj.H] = obj.ParameterSet(0.05,50);\n obj.M = 2;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n PopObj(:,1) = PopDec(:,1);\n g = 1 + 10*mean(PopDec(:,2:end),2);\n h = sin(4*pi*PopDec(:,1))/15 - PopDec(:,1) + 1;\n PopObj(:,2) = h.*g;\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(~,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = sin(4*pi*R(:,1))/15 - R(:,1) + 1;\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n %% Calculate the metric value\n function score = CalMetric(obj,metName,Population)\n switch metName\n case {'Mean_IGD','Mean_HV','Worst_IGD','Worst_HV'}\n score = feval(metName,Population,obj);\n otherwise\n score = feval(metName,Population,obj.optimum);\n end\n end\n %% Perturb solutions multiple times\n function PopX = Perturb(obj,PopDec,N)\n if nargin < 3; N = obj.H; end\n Delta = repmat(obj.delta.*(obj.upper-obj.lower),N*size(PopDec,1),1);\n w = UniformPoint(N,obj.D,'Latin');\n Dec = 2*Delta.*w(reshape(repmat(1:end,size(PopDec,1),1),1,[]),:) + repmat(PopDec,N,1) - Delta;\n Dec = obj.CalDec(Dec);\n PopX = SOLUTION(Dec,obj.CalObj(Dec),obj.CalCon(Dec));\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/TP/TP5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6489905037622664}} {"text": "% Fig. 5.38 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\nclf\nnumG = 160*conv ([1 2.5],[1 0.7]);\ndenG = conv([1 5 40],[1 .03 .06]);\nsysG = tf(numG,denG);\nsysD=tf([1 3],[1 20]);\nsysDG=sysD*sysG;\nK = 0.3;\nsysH=tf(1,1);\nsysT = feedback (K*sysG,sysH);\nsysTD=feedback(sysDG,sysH);\nstep(sysT)\nhold on\nstep(sysTD)\ngrid on\ntitle('Step responses of auto-pilot with P and lead control')\nhold off\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig5_38.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6489904889915615}} {"text": "clear; clc; close all;\ndataset = 'grid';\nimg = imread(strcat('../noncvx-lowrank(ICDM 2015)/data/images/', dataset, '.jpg'));\n\nif(size(img, 2) > size(img, 1))\n img = permute(img, [2,1,3]);\nend\n\nimgSize = size(img);\n\nimg = double(img)/255;\nimgMean = mean(img(:));\nimg = img - imgMean;\nimg = img/std(img(:));\n\nimg = reshape(img, imgSize(1), prod(imgSize)/imgSize(1));\n\nmissRatio = 0.95;\nnoisRatio = 0.05;\n\nmask = (rand(size(img)) > missRatio);\nG = randn(size(img))*noisRatio;\ntraD = img + G;\ntraD = traD.*mask;\ntraD = sparse(traD);\n\nclear maxk missRatio noisRatio mask G;\n\npara.maxIter = 5000;\npara.tol = 1e-6;\npara.maxR = 50 ;\n\n%% ---------------------------------------------------------------\nmask = (rand(size(img)) > 0.9);\ntstD = img.*mask;\ntstD = sparse(tstD);\n\n[tstRow, tstCol, tstVal] = find(tstD);\n\npara.test.row = tstRow;\npara.test.col = tstCol;\npara.test.data = tstVal;\npara.test.m = size(tstD, 1);\npara.test.n = size(tstD, 2);\n\nclear tstRow tstCol tstVal tstD;\n\n%% ---------------------------------------------------------------\nlambdaMax = 4;\ngridLambda = lambdaMax*(0.8).^(0:9);\n\ngridNMSE = zeros(2, size(gridLambda,2 ));\ngridRank = zeros(1, size(gridLambda,2 ));\nfor g = 1:length(gridLambda) \n lambda = gridLambda(g);\n \n % [U, S, V] = SoftImpute(traD, lambda, para );\n [U, S, V] = AISImpute(traD, lambda, para );\n gridRank(g) = nnz(S);\n \n X = U*S*V';\n gridNMSE(1, g) = sqrt(norm(X - img, 'fro')^2/numel(img));\n \n [ U, S, V ] = PostProcess(traD, U, V, S);\n X = U*S*V';\n \n gridNMSE(2, g) = sqrt(norm(X - img, 'fro')^2/numel(img)); \n \n if(g > 1 && gridNMSE(2, g) > gridNMSE(2, g - 1))\n break;\n end\nend\n\ngridNMSE = gridNMSE(2,1:g);\n[~, lambda] = min(gridNMSE);\ngndRank = gridRank(lambda);\npara.maxR = ceil(gndRank*1.2);\n\nlambda = gridLambda(lambda);\n\nclear gridNMSE gridRank g X U S V gridLambda;\n\n%% active --------------------------------------------------------\nmethod = 1;\nt = tic;\n[U, S, V, out{method}] = ActiveSubspace(traD, lambda, para );\n% [U, S, V, out{1}]=mc_alt(traData', lambda, para);\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nhold on;\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nhold on;\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('active');\n\n%% boost ---------------------------------------------------------\nmethod = 2;\nt = tic;\n[U, S, V, out{method}] = Boost( traD, lambda, para);\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nhold on;\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nhold on;\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('boost');\n\n%% TR ------------------------------------------------------------\nmethod = 3;\nt = tic;\n[U, S, V, out{method}] = MMBS( traD, lambda, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('TR');\n\n%% ALT-Impute ----------------------------------------------------\nmethod = 4;\nt = tic;\n[U, S, V, out{method}] = SoftImputeALS( traD, lambda, para.maxR, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('ALT-Impute');\n\n%% SSGD ----------------------------------------------------------\nmethod = 5;\nt = tic;\n[U, S, V, out{method}] = SSGD( traD, lambda, gndRank, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('SSGD');\n\n%% LMaFit --------------------------------------------------------\n\ngridNMSE = zeros(1, 10);\nfor g = 1:10 \n [U, S, V] = FixedRank( traD, g, para );\n \n X = U*S*V';\n gridNMSE(g) = sqrt(norm(X - img, 'fro')^2/numel(img));\n \n if(g > 1 && gridNMSE(g) > gridNMSE(g - 1))\n break;\n end\nend\n\ngridNMSE = gridNMSE(1:g);\n[~, rnk] = min(gridNMSE);\n\nclear gridNMSE X g U S V;\n\nmethod = 6;\nt = tic;\n[U, S, V, out{method}] = FixedRank( traD, rnk, para );\nTime(method) = toc(t);\n\nX = U*S*V';\nRMSE(method) = out{method}.RMSE(end);\nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('LMaFit');\n\n%% APG -----------------------------------------------------------\nmethod = 7;\nt = tic;\n[U, S, V, out{method}] = APGMatComp( traD, lambda, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('APG');\n\n%% Soft-Impute ---------------------------------------------------\nmethod = 8;\nt = tic;\n[U, S, V, out{method}] = SoftImpute( traD, lambda, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('Soft-Impute');\n\n%% AIS-Impute ----------------------------------------------------\nmethod = 9;\nt = tic;\n[U, S, V, out{method}] = AISImpute( traD, lambda, para );\nTime(method) = toc(t);\n\n[ U, S, V ] = PostProcess(traD, U, V, S);\nX = U*S*V';\nRMSE(method) = sqrt(norm(X - img, 'fro')^2/numel(img)); \nclear U S V t;\n\nfigure(1);\nplot(out{method}.Time, out{method}.RMSE);\nfigure(2);\nsemilogy(out{method}.Time, out{method}.obj - min(out{method}.obj));\nfigure;\nX = X + imgMean;\nX = reshape(X, imgSize);\nimshow(X, []);\ntitle('AIS-Impute');\n\n% clear gndRank img imgMean lambda lambdaMax method rnk traD X mask;\n", "meta": {"author": "HKUST-KnowComp", "repo": "FMG", "sha": "97944182356df7840c4e915f672f5b1d50953139", "save_path": "github-repos/MATLAB/HKUST-KnowComp-FMG", "path": "github-repos/MATLAB/HKUST-KnowComp-FMG/FMG-97944182356df7840c4e915f672f5b1d50953139/matlab/AIS-Impute/TestImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6489904851626865}} {"text": "function [rs, rs2, rs3] = dimensions(s, bins)\n\n%tstoolbox/@signal/dimensions\n% Syntax:\n% * [bc,in,co] = dimensions(s, bins)\n%\n% Input arguments:\n% * s - data points (row vectors)\n% * bins - maximal number of partition per axis, default is 100\n%\n% Output arguments:\n% * bc - scaling of boxes with partititon sizes (log[2]-log[2])\n% * in - scaling of information with partititon sizes (log[2]-log[2])\n% * co - scaling of correlation with partititon sizes (log[2]-log[2])\n%\n% Compute boxcounting, information and correlation dimension of a\n% time-delay reconstructed timeseries s for dimensions from 1 to D,\n% where D is the dimension of the input vectors using boxcounting\n% approach.\n%\n% Scale data to be within 0 and 1. Give a sortiment of (integer)\n% partitionsizes with almost exponential behaviour.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,2);\n\nif ndim(s) ~= 2\n error('Signal must contain vector data'); \nend\n\nif nargin<2\n bins = 100; \nend\n\npoints = data(s);\n[N,dim] = size(points);\n\n% scale data to be within 0 and 1\npoints = points - min(min(points));\npoints = points / max(max(points));\n\n% give a sortiment of (integer) partitionsizes with almost exponential behaviour \npar = [2 3 4 5 6 7 8 10 12 14 16 20 23 27 32 39 46 54 64 77 91 108 128 153 182 216 256 ...\n 305 363 431 512 609 725 862 1024 1218 1449 1723 2048 2436 2897 3445 4096 4871 ...\n\t 5793 6889 8192 9742 11586 13778 16384 19484 23171 27555 32768 38968 46341 55109 65536];\n\npartitions = par(find(par<=bins));\t% use no sizes greater than bins\n\n[c,d,e] = boxcount(points, partitions);\n\nc = [zeros(1,dim) ; c]; % add zeros for partition size 1\nd = [zeros(1,dim) ; d]; % add zeros for partition size 1\ne = [zeros(1,dim) ; e]; % add zeros for partition size 1\npartitions = [1 ; partitions(:)];\n\na1 = achse(-log2(partitions)); \t\t% create axis with arbitrary spacing\na1 = setname(a1, 'ld r');\n\na2 = setname(achse(unit, 1, 1), 'Embedding dimension');\n\nrs = signal(core(c), s);\t\nrs = setaxis(rs, 1, a1);\nrs = setaxis(rs, 2, a2);\nrs = setplothint(rs, 'multigraph');\nrs = addhistory(rs, ['Computed boxcounting dimension']);\nrs = addcommandlines(rs, 's = boxdim(s', bins);\nrs = setyname(rs, 'ld N(r)');\nrs = setlabel(rs, 'Scaling of D0');\n\nrs2 = signal(core(d), s);\t\nrs2 = setaxis(rs2, 1, a1);\nrs2 = setaxis(rs2, 2, a2);\nrs2 = setplothint(rs2, 'multigraph');\nrs2 = addhistory(rs2, ['Computed information dimension']);\nrs2 = addcommandlines(rs2, 's = infodim(s', bins);\nrs2 = setyname(rs2, 'I(r)');\nrs2 = setlabel(rs2, 'Scaling of D1');\n\nrs3 = signal(core(e), s);\t\nrs3 = setaxis(rs3, 1, a1);\nrs3 = setaxis(rs3, 2, a2);\nrs3 = setplothint(rs3, 'multigraph');\nrs3 = addhistory(rs3, ['Computed correlation dimension']);\nrs3 = addcommandlines(rs3, 's = corrdim(s', bins);\nrs3 = setyname(rs3, 'ld C(r)');\nrs3 = setlabel(rs3, 'Scaling of D2');\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@signal/dimensions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6489730590953954}} {"text": "% plot_UWB_channel.m\nclear, clf\nno_output_files = 0; % non-zero: avoids writing output files of continuous-time responses\nTs = 0.167; % sampling time (nsec)\nnum_ch=100; % number of channel impulse responses to generate\nrandn('state',12); % initialize state of function for repeatability\nrand('state',12); % initialize state of function for repeatability\ncm = 1; % channel model number from 1 to 4\n% get channel model params based on this channel model number\n[Lam,lam,Gam,gam,nlos,sdi,sdc,sdr] = UWB_parameters(cm);\nfprintf(1,['Model Parameters\\n' ' Lam= %.4f, lam= %.4f, Gam= %.4f, gam= %.4f\\n NLOS flag= %d, std_shdw= %.4f, std_ln_1= %.4f, std_ln_2= %.4f\\n'],...\n Lam,lam,Gam,gam,nlos,sdi,sdc,sdr);\n% get a bunch of realizations (impulse responses)\n[h_ct,t_ct,t0,np] = UWB_model_ct(Lam,lam,Gam,gam,num_ch,nlos,sdi,sdc,sdr);\n% now reduce continuous-time result to a discrete-time result\n[hN,N] = convert_UWB_ct(h_ct,t_ct,np,num_ch,Ts);\n% if we wanted complex baseband model or to impose some filtering function,\n% this would be a good place to do it\nh = resample(hN,1,N); % decimate the columns of hN by factor N\nh = h*N; % correct for 1/N scaling imposed by decimation\nchannel_energy = sum(abs(h).^2); % channel energy\nh_len = size(h,1);\nt = [0:(h_len-1)]*Ts; % for use in computing excess & RMS delays\n \nfor k=1:num_ch\n % determine excess delay and RMS delay\n sq_h = abs(h(:,k)).^2/channel_energy(k);\n t_norm = t - t0(k); % remove the randomized arrival time of first cluster\n excess_delay(k) = t_norm*sq_h;\n rms_delay(k) = sqrt((t_norm-excess_delay(k)).^2*sq_h);\n % determine # of significant paths (paths within 10 dB from peak)\n threshold_dB = -10; % dB\n temp_h = abs(h(:,k));\n temp_thresh = 10^(threshold_dB/20)*max(temp_h);\n num_sig_paths(k) = sum(temp_h>temp_thresh);\n % determine number of sig. paths (captures x % of energy in channel)\n x = 0.85;\n temp_sort = sort(temp_h.^2); % sorted in ascending order of energy\n cum_energy = cumsum(temp_sort(end:-1:1)); % cumulative energy\n index_e = min(find(cum_energy >= x*cum_energy(end)));\n num_sig_e_paths(k) = index_e;\nend\nenergy_mean = mean(10*log10(channel_energy));\nenergy_stddev = std(10*log10(channel_energy));\nmean_excess_delay = mean(excess_delay);\nmean_rms_delay = mean(rms_delay);\nmean_sig_paths = mean(num_sig_paths);\nmean_sig_e_paths = mean(num_sig_e_paths);\n \nfprintf(1,'Model Characteristics\\n');\nfprintf(1,' Mean delays: excess (tau_m) = %.1f ns, RMS (tau_rms) = %1.f\\n', ...\n mean_excess_delay, mean_rms_delay);\nfprintf(1,' # paths: NP_10dB = %.1f, NP_85%% = %.1f\\n', ...\n mean_sig_paths, mean_sig_e_paths);\nfprintf(1,' Channel energy: mean = %.1f dB, std deviation = %.1f dB\\n', ...\n energy_mean, energy_stddev);\n \nsubplot(421), plot(t,h), grid on\ntitle('Impulse response realizations'), xlabel('Time (nS)')\n \nsubplot(422), plot([1:num_ch], excess_delay, 'b-', ...\n [1 num_ch], mean_excess_delay*[1 1], 'r--' );\ngrid on, title('Excess delay (nS)'), xlabel('Channel number')\n \nsubplot(423), plot([1:num_ch], rms_delay, 'b-', ...\n [1 num_ch], mean_rms_delay*[1 1], 'r--' );\ngrid on, title('RMS delay (nS)'), xlabel('Channel number')\n \nsubplot(424), plot([1:num_ch], num_sig_paths, 'b-', ...\n [1 num_ch], mean_sig_paths*[1 1], 'r--');\ngrid on, title('Number of significant paths within 10 dB of peak')\nxlabel('Channel number')\n \nsubplot(427), plot([1:num_ch], num_sig_e_paths, 'b-', ...\n [1 num_ch], mean_sig_e_paths*[1 1], 'r--');\ngrid on, title('Number of significant paths capturing > 85% energy')\nxlabel('Channel number')\n \ntemp_average_power = sum(h'.*(h)')/num_ch;\ntemp_average_power = temp_average_power/max(temp_average_power);\naverage_decay_profile_dB = 10*log10(temp_average_power);\nsubplot(425), plot(t,average_decay_profile_dB); grid on\naxis([0 t(end) -60 0]), title('Average Power Decay Profile')\nxlabel('Delay (nsec)'), ylabel('Average power (dB)')\n \nsubplot(426)\nfigh = plot([1:num_ch],10*log10(channel_energy),'b-', ...\n [1 num_ch], energy_mean*[1 1], 'g--', ...\n [1 num_ch], energy_mean+energy_stddev*[1 1], 'r:', ...\n [1 num_ch], energy_mean-energy_stddev*[1 1], 'r:');\nxlabel('Channel number'), ylabel('dB'), title('Channel Energy');\nlegend(figh, 'Per-channel energy', 'Mean', '\\pm Std. deviation', 0)\n \nif no_output_files, return; end\n%%% save continuous-time (time,value) pairs to files\nsave_fn = sprintf('cm%d_imr', cm);\n% A complete self-contained file for Matlab users\nsave([save_fn '.mat'], 't_ct', 'h_ct', 't0', 'np', 'num_ch', 'cm');\n% Two comma-delimited text files for non-Matlab users:\n% File #1: cmX_imr_np.csv lisTs the number of paths in each realization\ndlmwrite([save_fn '_np.csv'], np, ','); % number of paths\n% File #2: cmX_imr.csv can open with Excel\n% n'th pair of columns contains the (time,value) pairs for the n'th realization\nth_ct = zeros(size(t_ct,1),2*size(t_ct,2));\nth_ct(:,1:2:end) = t_ct; % odd columns are time\nth_ct(:,2:2:end) = h_ct; % even columns are values\nfid = fopen([save_fn '.csv'], 'w');\nif fid < 0,\n error('unable to write .csv file for impulse response, file may be open in another application');\nend\nfor k = 1:size(th_ct,1)\n fprintf(fid,'%.4f,%.6f,', th_ct(k,1:end));\n fprintf(fid,'\\r\\n'); % \\r\\n for Windoze end-of-line\nend\nfclose(fid); ", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/第2章 SISO信道模型/UWB信道模型/plot_UWB_channel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6489730333296841}} {"text": "% POLARCONT Polar contour plot\n%\n% Richard Rieber\n% rrieber@gmail.com\n% April 4, 2007\n% Updated June 15, 2007\n% \n% function [C,h] = polarcont(r,theta,z,N,s)\n%\n% Purpose: This function creates polar contour plots on the current active\n% figure\n% \n% Inputs: o r - Radius vector of length m\n% o theta - Angle vector in radians of length n\n% o z - Magnitude at the points specified in r and theta of\n% size m x n\n% o N - The number of contours to plot [OPTIONAL]\n% o s - Linespec as described in PLOT [OPTIONAL]\n%\n% Outputs: o C - returns contour matrix C as described in CONTOURC\n% o h - Column vector H of handles to LINE or PATCH objects,\n% one handle per line. \n%\n% OTHER NOTES:\n% - Both C and h can be used as inputs to CLABEL\n% - Colors are defined in colormap\n% - Treat this function as a standard contour plot\n\nfunction [C,h] = polarcont(r,theta,z,N,s)\n\n[a,b] = size(z);\n\nif a ~= length(r)\n error('r is not the same length as the first dimension of z')\nend\n\nif b ~= length(theta)\n error('theta is not the same length as the second dimension of z')\nend\n\nx = zeros(a,b);\ny = zeros(a,b);\n\nfor j = 1:a\n for k = 1:b\n x(j,k) = r(j)*cos(theta(k));\n y(j,k) = r(j)*sin(theta(k));\n end\nend\n\nif nargin == 3\n [C,h] = contour(x,y,z);\nelseif nargin == 4\n [C,h] = contour(x,y,z,N);\nelseif nargin == 5\n [C,h] = contour(x,y,z,N,s);\nelse\n error('Incorrect number of inputs')\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/14826-polar-contour-plot/polarcont.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.6489439723305361}} {"text": "function X = tendiag(v,sz)\n%TENDIAG Creates a tensor with v on the diagonal.\n%\n% TENDIAG(V) creates a tensor with N dimensions, each of size N, where N\n% is the number of elements of V. The elements of V are placed on the\n% superdiagonal.\n%\n% TENDIAG(V,SZ) is the same as above but creates a tensor of size SZ. If\n% SZ is not big enough, the tensor will be enlarged to accommodate the\n% elements of V on the superdiagonal.\n%\n% Examples\n% X = tendiag([0.1 0.22 0.333]) %<-- creates a 3x3x3 tensor\n%\n% See also TENSOR, SPTENDIAG.\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\n% Make sure v is a column vector\nv = reshape(v,[numel(v) 1]);\n\nN = numel(v);\nif ~exist('sz','var')\n sz = repmat(N,1,N);\nend\n\nX = tenzeros(sz);\nsubs = repmat((1:N)', 1, length(sz));\nX(subs) = v;\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/tendiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6489439664539598}} {"text": "function [L,S,obj,err,iter] = rmsc(X,lambda,opts)\n\n% Solve the Robust Multi-view Spectral Clustering (RMSC) problem by M-ADMM\n%\n% min_{L,S_i} ||L||_*+lambda*\\sum_i ||S_i||_1,\n% s.t. X_i=L+S_i, i=1,...,m, L>=0, L1=1.\n% ---------------------------------------------\n% Input:\n% X - d*n*m tensor\n% lambda - >0, parameter\n% opts - Structure value in Matlab. The fields are\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% L - d*n matrix\n% S - d*n*m tensor\n% obj - objective function value\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 19/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'tol'); tol = opts.tol; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\n[d,n,m] = size(X);\nL = zeros(d,n);\nS = zeros(d,n,m);\nZ = L;\nY = S;\ndY = S;\nY2 = L;\niter = 0;\nfor iter = 1 : max_iter\n Lk = L;\n Sk = S;\n Zk = Z;\n % first super block {Z,S_i}\n [Z,nuclearnormZ] = prox_nuclear(L+Y2/mu,1/mu);\n for i = 1 : m\n S(:,:,i) = prox_l1(-L+X(:,:,i)-Y(:,:,i)/mu,lambda/mu);\n end\n % second super block {L}\n temp = (sum(X-S-Y/mu,3)+Z-Y2/mu)/(m+1);\n L = project_simplex(temp);\n\n for i = 1 : m\n dY(:,:,i) = L+S(:,:,i)-X(:,:,i);\n end\n dY2 = L-Z;\n chgL = max(abs(Lk(:)-L(:)));\n chgZ = max(abs(Zk(:)-Z(:)));\n chgS = max(abs(Sk(:)-S(:)));\n chg = max([chgL chgS chgZ max(abs(dY(:))) max(abs(dY2(:)))]);\n if DEBUG\n if iter == 1 || mod(iter, 10) == 0\n obj = nuclearnormZ+lambda*norm(S(:),1);\n err = sqrt(norm(dY(:))^2+norm(dY2,'fro')^2);\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', obj=' num2str(obj) ', err=' num2str(err)]); \n end\n end\n \n if chg < tol\n break;\n end \n Y = Y + mu*dY;\n Y2 = Y2 + mu*dY2;\n mu = min(rho*mu,max_mu); \nend\nobj = nuclearnormZ+lambda*norm(S(:),1);\nerr = sqrt(norm(dY(:))^2+norm(dY2,'fro')^2);\n\n", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/rmsc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6489391850717435}} {"text": "function [ prob, ier ] = mdbeta ( x, p, q )\n\n%*****************************************************************************80\n%\n%% MDBETA evaluates the incomplete beta function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Oliver Ludwig;\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Oliver Ludwig,\n% Algorithm 179:\n% Incomplete Beta Ratio,\n% Communications of the ACM,\n% Volume 6, Number 6, June 1963, page 314.\n%\n% Parameters:\n%\n% Input, real X, the value to which function is to be\n% integrated. X must be in the range [0,1] inclusive.\n%\n% Input, real P, the first parameter. P must be greater\n% than 0.0.\n%\n% Input, real Q, the second parameter. Q must be greater\n% than 0.0.\n%\n% Output, real PROB. The probability that a random variable\n% from a Beta distribution having parameters P and Q will be less than\n% or equal to X.\n%\n% Output, integer IER, error parameter.\n% 0, normal exit.\n% 1, X is not in the range [0,1] inclusive.\n% 2, P or Q is less than or equal to 0.\n%\n% Local parameters:\n%\n% Local, real ALEPS, the logarithm of EPS1.\n%\n% Local, real EPS, the machine precision.\n%\n% Local, real EPS1, the smallest representable number.\n%\n aleps = - 179.6016;\n eps = 2.2E-16;\n eps1 = 1.0E-78;\n%\n% Check ranges of the arguments.\n%\n prob = 0.0;\n y = x;\n\n if ( x < 0.0 || 1.0 < x )\n ier = 1;\n return\n end\n\n if ( p <= 0.0 || q <= 0.0 )\n ier = 2;\n return\n end\n\n ier = 0;\n\n if ( x <= 0.5 )\n interval = 0;\n else\n interval = 1;\n temp = p;\n p = q;\n q = temp;\n y = 1.0 - y;\n end\n\n if ( x == 0.0 || x == 1.0 )\n\n prob = 0.0;\n\n if ( interval ~= 0 )\n prob = 1.0 - prob;\n temp = p;\n p = q;\n q = temp;\n end\n\n return\n end\n\n ib = q;\n temp = ib;\n ps = q - ib;\n\n if ( q == temp )\n ps = 1.0;\n end\n\n dp = p;\n dq = q;\n px = dp * log ( y );\n pq = alogam ( dp + dq );\n p1 = alogam ( dp );\n c = alogam ( dq );\n d4 = log ( dp );\n xb = px + alogam ( ps + dp ) - alogam ( ps ) - d4 - p1;\n%\n% Scaling\n%\n ib = floor ( xb / aleps );\n infsum = 0.0;\n%\n% First term of a decreasing series will underflow.\n%\n if ( ib == 0 )\n\n infsum = exp ( xb );\n cnt = infsum * dp;\n%\n% CNT will equal dexp ( temp ) * ( 1.d0 - ps ) * i * p * y**i / factorial ( i ).\n%\n wh = 0.0;\n\n while ( 1 )\n\n wh = wh + 1.0;\n cnt = cnt * ( wh - ps ) * y / wh;\n xb = cnt / ( dp + wh );\n infsum = infsum + xb;\n\n if ( xb / eps < infsum )\n break\n end\n\n end\n\n end\n\n finsum = 0.0;\n\n if ( dq <= 1.0 )\n\n prob = finsum + infsum;\n\n if ( interval ~= 0 )\n prob = 1.0 - prob;\n temp = p;\n p = q;\n q = temp;\n end\n\n return\n end\n\n xb = px + dq * log ( 1.0 - y ) + pq - p1 - log ( dq ) - c;\n%\n% Scaling.\n%\n ib = floor ( xb / aleps );\n\n if ( ib < 0 )\n ib = 0;\n end\n\n c = 1.0 / ( 1.0 - y );\n cnt = exp ( xb - ib * aleps );\n ps = dq;\n wh = dq;\n\n while ( 1 )\n\n wh = wh - 1.0;\n\n if ( wh <= 0.0 )\n\n prob = finsum + infsum;\n\n if ( interval ~= 0 )\n prob = 1.0 - prob;\n temp = p;\n p = q;\n q = temp;\n end\n\n break\n\n end\n\n px = ( ps * c ) / ( dp + wh );\n\n if ( px <= 1.0 )\n\n if ( cnt / eps <= finsum || cnt <= eps1 / px )\n\n prob = finsum + infsum;\n\n if ( interval ~= 0 )\n prob = 1.0 - prob;\n temp = p;\n p = q;\n q = temp;\n end\n\n break\n\n end\n\n end\n\n cnt = cnt * px;\n%\n% Rescale.\n%\n if ( 1.0 < cnt )\n ib = ib - 1;\n cnt = cnt * eps1;\n end\n\n ps = wh;\n\n if ( ib == 0 )\n finsum = finsum + cnt;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms179/mdbeta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6489391817264292}} {"text": "function z = proj_sdp(z,n)\nif n==0\n return;\nelseif n==1\n z = max(z,0);\n return;\nend\n\n% expand to full size matrix\nb = tril(ones(n));\nb(b == 1) = z;\nz = b;\nz = (z + z');\nz = z - diag(diag(z)) / 2;\n\n% rescale so projection works, and matrix norm preserved\n% see http://www.seas.ucla.edu/~vandenbe/publications/mlbook.pdf pg 3\n% scale diags by sqrt(2)\nz(eye(n) == 1) = z(eye(n) == 1) .* sqrt(2);\n\n[V,S] = eig(z);\nS = diag(S);\n\nidx = find(S>0);\nV = V(:,idx);\nS = S(idx);\nz = V*diag(S)*V';\n\n% scale diags by 1/sqrt(2)\nz(eye(n) == 1) = z(eye(n) == 1) ./ sqrt(2);\n\nz = z(tril(ones(n)) == 1);\nend", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/3rd_Party_Libraries/scs-matlab-master/examples/scs_matlab/proj_sdp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.6489347388206174}} {"text": "function u=rotrack(u0,x,y,nu,T) \n%\n% Solves the linear equation u_t + y u_x - x u_y = 0 by \"front tracking\" +\n% dimensional splitting, using a time step dictated by dt/dx=nu for each\n% substep. \n% Neumann boundary condition are implicit. \n% \ndx=x(2)-x(1);\ndt=nu*dx;\nnstep=ceil(T/dt);\ndt=T/nstep;\nnu=dt/dx;\nu=u0;\nfor i=1:nstep,\n\tu=transp(u,nu*y,1);\n\tu=transp(u,-nu*x,2);\nend;\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/OperatorSplitting/Chapter5/Rotationtrack/rotrack.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6489347344471948}} {"text": "%% Demo of gaimc - 'Graph Algorithms In Matlab Code'\n% Matlab includes great algorithms to work with sparse matrices but does\n% provide a reasonable set of algorithms to work with sparse matrices as\n% graph data structures. My other project -- MatlabBGL -- provides a\n% high-performance solution to this problem by directly interfacing the\n% Matlab sparse matrix data structure with the Boost Graph Library. \n% That library, however, suffers from enormous complication because \n% it must be compiled for each platform. The Boost Graph Library \n% heavily uses advanced C++ features that impair easy portability\n% between platforms. In contrast, the gaimc library is implemented in\n% pure Matlab code, making it completely portable.\n%\n% The cost of the portability for this library is a 2-4x slowdown in \n% the runtime of the algorithms as well as significantly fewer \n% algorithms to choose from.\n\n%% Sparse matrices as graphs\n% To store the connectivity structure of the graph, gaimc uses the\n% adjacency matrix of a graph. \n%\n% A graph is represented by a set of vertices and a set of\n% edges between the vertices. Often, we write $G = (V,E)$ to denote the\n% graph, the set of vertices, and the set of edges, respectively. In\n% gaimc, like in my other package MatlabBGL, we represent graphs with their\n% adjacency matrices. This representation is handy in Matlab because\n% Matlab is rather efficient at working with the large sparse matrices that\n% typically arise as adjacency matrices.\n%\n% To convert from $G=(V,E)$ to an adjacency matrix, we identify each vertex\n% with a row of the matrix via a bijective map. The adjacency matrix is\n% then a $|V| \\times |V|$ matrix called A. The entry A(i,j) = 1 for\n% any edge between in $E$ and 0 otherwise. Let's look at an example.\n\nload_gaimc_graph('bfs_example');\ngraph_draw(A,xy,'labels',labels)\nfull(A)\nlabels'\n\n%%\n% This output means that vertex 'r' is row 1, vertex 's' is row 2 and\n% because A(1,2) = 1, then there is an edge between them, just like in the\n% picture.\n%\n% One funny property is that A(2,1) = 1 too! So we actually have to store\n% each edge twice in the adjacency matrix. This might seem wasteful, but\n% its hard to avoid as I've learned while working on graph algorithms. So\n% don't worry about it! It also makes the generalization to directed\n% graphs (below) easy.\n%\n% For more information about the adjacency matrix representation of a\n% graph, see a standard book on graph algorithms.\n%\n\n%% Weighted and directed graphs\n% Our previous case handled the situation for undirected graphs only. To\n% encode weighted and directed graphs, we use weighted and non-symmetric\n% adjacency matrices.\n%\n% For a weighted matrix, A(i,j) = distance between i and j for most of the\n% algorithms in gaimc. But A(i,j) = 0 means there is no edge, and so\n% sometimes things can get a little tricky to get what you want.\n%\n% For a directed graph, just set A(i,j) ~= A(j,i). The adjacency matrix\n% won't be symmetric, but that's what you want!\n%\n% To understand more, explore the examples or read up on adjacency matrices\n% in graph theory books.\n\n%% Loading helper\n% To make loading our sample graphs easy, gaimc defines it's own function\n% to load graphs.\n\nload_gaimc_graph('dfs_example'); % loads one of our example graphs\nwhos\n\n%%\n% This helps make our examples work regardless of where the current\n% directory lies. \n\n%% Search algorithms\n% The two standard graph search algorithms are depth first search and \n% breadth first search. This library implements both.\n\n%%\n% Load the example matrix from the Boost Graph Library \nload_gaimc_graph('dfs_example');\nfigure(1); graph_draw(A,xy,'labels',labels);\n\n%%\n% Run a depth first search. The output records the distance to the other\n% vertices, except where the vertices are not reachable starting from the\n% first node A.\nd=dfs(A,1)\n\n%%\n% From this example, we see that vertices a-f are reachable from vertex a,\n% but that verice g-i are not reachable. Given the of the edges, this\n% makes sense.\n\n%%\n% Let's look at breadth first search too, using a different example.\nload_gaimc_graph('bfs_example');\nfigure(1); clf; graph_draw(A,xy,'labels',labels);\n\n%%\n% The breadth first search algorithm records the distance from the starting\n% vertex to each vertex it visits in breadth first order. This means it\n% visits all the vertices in order of their distance from the starting\n% vertex. The d output records the distance, and the dt output records the\n% step of the algorithm when the breadth first search saw the node.\n[d dt] = bfs(A,2);\n% draw the graph where the label is the \"discovery time\" of the vertex.\nfigure(1); clf; graph_draw(A,xy,'labels',num2str(dt));\n\n%%\n% Notice how the algorithm visits all vertices one edge away from the start\n% vertex (0) before visiting those two edges away.\n\n\n%% Shortest paths\n% In the previous two examples, the distance between vertices was\n% equivalent to the number of edges. Some graphs, however, have specific\n% weights, such as the graph of flights between airports. We can use this\n% information to build information about the _shortest path_ between two\n% nodes in a network. \n\n% Find the minimum travel time between Los Angeles (LAX) and\n% Rochester Minnesota (RST).\nload_gaimc_graph('airports')\nA = -A; % fix funny encoding of airport data\nlax=247; rst=355;\n\n[d pred] = dijkstra(A,lax); % find all the shorest paths from Los Angeles.\n\nfprintf('Minimum time: %g\\n',d(rst));\n% Print the path\nfprintf('Path:\\n');\npath =[]; u = rst; while (u ~= lax) path=[u path]; u=pred(u); end\nfprintf('%s',labels{lax}); \nfor i=path; fprintf(' --> %s', labels{i}); end, fprintf('\\n');\n\n%% Minimum spanning trees\n% A minimum spanning tree is a set of edges from a graph that ...\n%\n% This demo requires the mapping toolbox for maximum effect, but we'll do\n% okay without it.\n\n%%\n% Our data comes from a graph Brendan Frey prepared for his affinity\n% propagation clustering tool. For 456 cities in the US, we have the mean\n% travel time between airports in those cities, along with their latitude\n% and longitude.\nload_gaimc_graph('airports')\n\n%%\n% For some reason, the data is stored with the negative travel time between\n% cities. (I believe this is so that closer cities have larger edges\n% between them.) But for a minimum spanning tree, we want the actual\n% travel time between cities.\nA = -A;\n\n%%\n% Now, we just call MST and look at the result.\n% T = mst_prim(A);\n% This command means we can't run the demo, so it's commented out.\n\n%%\n% Oops, travel time isn't symmetric! Let's just pick the longest possible\n% time.\nA = max(A,A');\nT = mst_prim(A);\nsum(sum(T))/2 % total travel time in tree\n\n%% \n% Well, the total weight isn't that helpful, let's _look_ at the data\n% instead.\nclf;\ngplot(T,xy);\n\n%%\n% Hey! That looks like the US! You can see regional airports and get some\n% sense of the overall connectivity. \n\n%% Connected components\n% The connected components of a network determine which parts of the\n% network are reachable from other parts. One of your first questions\n% about any network should generally be: is it connected?\n%\n% There are two types of connected components: components and strongly\n% connected components. gaimc only implements an algorithm for the latter\n% case, but that's okay! It turns out it computes exactly the right thing\n% for connected components as well. The difference only occurs when the\n% graph is undirected vs. directed.\n\nload_gaimc_graph('dfs_example')\ngraph_draw(A,xy)\n\n%%\n% This picture shows there are 3 strongly connected components and 2 \n% connected components\n\n% get the number of strongly connected components\nmax(scomponents(A)) \n\n%%\n\n% get the number of connected components\nmax(scomponents(A|A')) % we make the graph symmetric first by \"or\"ing each entry\n\n%%\n% Let's look at the vertices in the strongly connected components\ncc = scomponents(A)\n%%\n% The output tells us that vertices 1,2,3,5,6 are in one strong component,\n% vertex 4 is it's own strong component, and vertices 7,8,9 are in another\n% one. Remember that a strong component is all the vertices mutually\n% reachable from a given vertex. If you start at vertex 4, you can't get\n% anywhere else! That's why it is in a different component than vertices \n% 1,2,3,5,6.\n\n%%\n% We also have a largest_component function that makes it easy to just get\n% the largest connected component.\nclf;\n[Acc,f] = largest_component(A);\ngraph_draw(Acc,xy(f,:)) \n%%\n% The filter variable f, tells us which vertices in the original graph made\n% it into the largest strong component. We can just apply that filter to\n% the coordinates xy and reuse them for drawing the graph!\n\n%% Statistics\n% Graph statistics are just measures that indicate a property of the graph\n% at every vertex, or at every edges. Arguably the simplest graph\n% statistic would be the average vertex degree. Because such statistics\n% are easy to compute with the adjaceny matrix in Matlab, they do not have\n% special functions in gaimc. \n\n%%\n% Load a road network to use for statistical computations\nload_gaimc_graph('minnesota');\ngplot(A,xy);\n\n%%\n% Average vertex degree\nd = sum(A,2);\nmean(d)\n\n%% \n% So the average number of roads at any intersection is 2.5. My guess is\n% that many roads have artificial intersections in the graph structure that\n% do not correspond to real intersections. Try validating that hypothesis\n% using the library!\n\n%%\n% Average clustering coefficients\nccfs = clustercoeffs(A);\nmean(ccfs)\n% The average clustering coefficient is a measure of the edge density\n% throughout the graph. A small value indicates that the network has few\n% edges and they are well distributed throughout the graph.\n\n%%\n% Average core numbers\ncn = corenums(A);\nmean(cn)\n\n\n\n%% Efficient repetition\n% Every time a gaimc function runs, it converts the adjacency matrix into a\n% set of compressed sparse row arrays. These arrays yield efficient access\n% to the edges of the graph starting at a particular vertex. For many\n% function calls on the same graph, this conversion process slows the\n% algorithms. Hence, gaimc also accepts pre-converted input, in which case\n% it skips it's conversion. \n%\n% Let's demonstrate how this works by calling Dijkstra's algorithm to\n% compute the shortest paths between all vertices in the graph. The \n% Floyd Warshall algorithm computes these same quantities more efficiently,\n% but that would just be one more algorithm to implement and maintain.\n\n%%\n% Load and convert the graph. \nload_gaimc_graph('all_shortest_paths_example');\nA = spfun(@(x) x-min(min(A))+1,A); % remove the negative edges\nAs = convert_sparse(A);\n%%\n% Now, we'll run Dijkstra's algorithm for every vertex and save the result\n% On my 2GHz laptop, this takes 0.000485 seconds.\nn = size(A,1);\nD = zeros(n,n);\ntic\nfor i=1:n\n D(i,:) = dijkstra(As,i);\nend\ntoc\n%%\n% Let's try it without the conversion to see if we can notice the\n% difference in speed.\n% On my 2GHz laptop, this takes 0.001392 seconds.\nD2 = zeros(n,n);\ntic\nfor i=1:n\n D2(i,:) = dijkstra(A,i);\nend\ntoc\n%%\n% And just to check, let's make sure the output is the same.\nisequal(D,D2)\n", "meta": {"author": "ckczzj", "repo": "CHAN", "sha": "9b051c6ccf4d2a2bd2f06d37d590718e238593e6", "save_path": "github-repos/MATLAB/ckczzj-CHAN", "path": "github-repos/MATLAB/ckczzj-CHAN/CHAN-9b051c6ccf4d2a2bd2f06d37d590718e238593e6/evaluation_code/demo/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6488199510081152}} {"text": "function cvt_movie ( )\n\n%*****************************************************************************80\n%\n%% CVT_MOVIE generates and animates a CVT dataset.\n%\n% Discussion:\n%\n% This program is meant to be used interactively. It's also\n% possible to prepare a simple input file beforehand and use it\n% in batch mode.\n%\n% The program requests input values from the user:\n%\n% * NDIM, the spatial dimension,\n% * N, the number of points to generate,\n% * SEED, a seed to use for random number generation;\n% * INIT, initialize the points:\n% ** file, by reading data from file;\n% ** 'GRID', picking points from a grid;\n% ** 'HALTON', from a Halton sequence;\n% ** 'RAND', using MATLAB's RAND function;\n% ** 'UNIFORM', using a simple uniform RNG;\n% * IT_MAX, the maximum number of iterations;\n% * IT_FIXED, the number of iterative steps to take\n% using a fixed set of sampling points.\n% * SAMPLE, how to conduct the sampling:\n% ** 'GRID', picking points from a grid;\n% ** 'HALTON', from a Halton sequence;\n% ** 'RAND', using MATLAB's RAND function;\n% ** 'UNIFORM', using a simple uniform RNG;\n% * SAMPLE_NUM, the number of sampling points;\n% * BATCH, the number of sampling points to create at one time;\n% * MOVIE_NAME is the name of the file in which the movie is stored;\\n' );\n% * OUTPUT, a file into which the data can be stored.\n%\n% To indicate that no further computations are desired, it is \n% enough to input a nonsensical value, such as -1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 December 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Qiang Du, Vance Faber, and Max Gunzburger,\n% Centroidal Voronoi Tessellations: Applications and Algorithms,\n% SIAM Review, Volume 41, 1999, pages 637-676.\n%\n DEBUG = 1;\n\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Generate and animate a CVT dataset.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This program is meant to be used interactively.\\n' );\n fprintf ( 1, ' It is also possible to prepare a simple input \\n' );\n fprintf ( 1, ' file beforehand and use it in batch mode.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program requests input values from the user:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * NDIM, the spatial dimension,\\n' );\n fprintf ( 1, ' * N, the number of points to generate,\\n' );\n fprintf ( 1, ' * SEED, a seed to use for random number generation,\\n' );\n fprintf ( 1, ' * INIT, initialize the points:\\n' );\n fprintf ( 1, ' ** file, read data from a file;\\n' );\n fprintf ( 1, ' ** ''GRID'', by picking points from a grid;\\n' );\n fprintf ( 1, ' ** ''HALTON'', from a Halton sequence;\\n' );\n fprintf ( 1, ' ** ''RAND'', using MATLAB''s RAND function;\\n' );\n fprintf ( 1, ' ** ''UNIFORM'', using a simple uniform RNG;\\n' );\n fprintf ( 1, ' * IT_MAX, the maximum number of iterations.\\n' );\n fprintf ( 1, ' * IT_FIXED, the number of iterative steps to take\\n' );\n fprintf ( 1, ' using a fixed set of sampling points.\\n' );\n fprintf ( 1, ' * SAMPLE, how to conduct the sampling.\\n' );\n fprintf ( 1, ' ** ''GRID'', by picking points from a grid;\\n' );\n fprintf ( 1, ' ** ''HALTON'', from a Halton sequence;\\n' );\n fprintf ( 1, ' ** ''RAND'', using MATLAB''s RAND function;\\n' );\n fprintf ( 1, ' ** ''UNIFORM'', using a simple uniform RNG;\\n' );\n fprintf ( 1, ' * SAMPLE_NUM, the number of sample points;\\n' );\n fprintf ( 1, ' * BATCH, the number of sampling points to create at one time;\\n' );\n fprintf ( 1, ' * OUTPUT, a file into which the data is stored.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' To indicate that no further computations are \\n' );\n fprintf ( 1, ' desired, it is enough to input a nonsensical value, \\n' );\n fprintf ( 1, ' such as -1.\\n' );\n\n while ( 1 )\n\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '* Ready to generate a new dataset:\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NDIM is the spatial dimension.\\n' );\n fprintf ( 1, ' (Try ''2'' if you have no preference.)\\n' );\n fprintf ( 1, ' (Any value less than 1 terminates execution.)\\n' );\n ndim = [];\n ndim = input ( ' Enter NDIM: ' );\n\n fprintf ( 1, ' Default NDIM = %12d\\n', ndim );\n\n if ( ndim < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of NDIM = %12d\\n', ndim );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N is the number of points to generate.\\n' );\n fprintf ( 1, ' (Try ''25'' if you have no preference.)\\n' );\n fprintf ( 1, ' (Any value less than 1 terminates execution.)\\n' );\n n = [];\n n = input ( ' Enter N: ' );\n\n fprintf ( 1, ' User input N = %12d\\n', n );\n\n if ( n < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of N = %12d\\n', n );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' SEED is a seed for the random number generation.\\n' );\n% fprintf ( 1, ' (Try ''123456789'' if you have no preference.)\\n' );\n% fprintf ( 1, ' (Any value less than 0 terminates execution.)\\n' );\n% seed = [];\n% seed = input ( ' Enter SEED: ' );\n seed = 123456789;\n fprintf ( 1, ' Default SEED = %d\\n', seed );\n\n if ( seed < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of SEED = %12d\\n', seed );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' INIT is the method of initializing the data:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' file read data from a file;\\n' );\n fprintf ( 1, ' ''GRID'' by picking points from a grid;\\n' );\n fprintf ( 1, ' ''HALTON'' from a Halton sequence;\\n' );\n fprintf ( 1, ' ''RAND'' using MATLAB''s RAND function;\\n' );\n fprintf ( 1, ' ''UNIFORM'' using a simple uniform RNG;\\n' );\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' (Try ''RAND'' if you have no preference.)\\n' );\n fprintf ( 1, ' (A blank value terminates execution).\\n' );\n fprintf ( 1, ' (Be sure to INCLUDE QUOTES around the string!\\n' );\n fprintf ( 1, ' \\n' );\n\n init_string = [];\n init_string = input ( ' Enter INIT: ' );\n\n fprintf ( 1, ' User input INIT = \"%s\".\\n', init_string );\n\n if ( s_len_trim ( init_string ) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of INIT \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n if ( s_eqi ( init_string, 'RAND' ) )\n init = -1;\n elseif ( s_eqi ( init_string, 'RANDOM' ) )\n init_string = 'RAND';\n init = -1;\n elseif ( s_eqi ( init_string, 'UNIFORM' ) )\n init = 0;\n elseif ( s_eqi ( init_string, 'HALTON' ) )\n init = 1;\n elseif ( s_eqi ( init_string, 'GRID' ) )\n init = 2;\n elseif ( 0 < s_len_trim ( init_string ) )\n init = 3;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of INIT \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' IT_MAX is the maximum number of iterations.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' An iteration carries out the following steps:\\n' );\n fprintf ( 1, ' * the Voronoi region associated with each\\n' );\n fprintf ( 1, ' generator is estimated by sampling;\\n' );\n fprintf ( 1, ' * the centroid of each Voronoi region is estimated.\\n' );\n fprintf ( 1, ' * the generator is replaced by the centroid.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' If \"enough\" sampling points are used,\\n' );\n fprintf ( 1, ' and \"enough\" iterations are taken, this process\\n' );\n fprintf ( 1, ' will converge.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (Try ''50'' if you have no preference.)\\n' );\n fprintf ( 1, ' (A negative value terminates execution).\\n' );\n fprintf ( 1, '\\n' );\n it_max = [];\n it_max = input ( ' Enter IT_MAX: ' );\n\n fprintf ( 1, ' User input IT_MAX = %12d\\n', it_max );\n\n if ( it_max < 0 )\n fprintf ( 1, ' \\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of IT_MAX = %12d\\n', it_max );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' IT_FIXED is the number of consecutive iterations\\n' );\n fprintf ( 1, ' to take with a fixed set of sample points.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Setting IT_FIXED to 1 means a new set of sample\\n' );\n fprintf ( 1, ' points is generated on every iterative step;\\n' );\n fprintf ( 1, ' Setting IT_FIXED equal to IT_MAX means a single set\\n' );\n fprintf ( 1, ' of sample points is used for the entire iteration.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Any value between 1 and IT_MAX is reasonable.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (Try \"%d\" if you do not have a preference).\\n', it_max );\n fprintf ( 1, ' (A 0 or negative value terminates execution).\\n' );\n fprintf ( 1, '\\n' );\n it_fixed = [];\n it_fixed = input ( ' Enter IT_FIXED: ' );\n\n fprintf ( 1, ' User input IT_FIXED = %12d\\n', it_fixed );\n\n if ( it_max < 0 )\n fprintf ( 1, ' \\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of IT_FIXED = %12d\\n', it_fixed );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SAMPLE is the method of sampling the region:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ''GRID'' by picking points from a grid;\\n' );\n fprintf ( 1, ' ''HALTON'' from a Halton sequence;\\n' );\n fprintf ( 1, ' ''RAND'' using MATLAB''s RAND function;\\n' );\n fprintf ( 1, ' ''UNIFORM'' using a simple uniform RNG;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (Try ''RAND'' if you have no preference.)\\n' );\n fprintf ( 1, ' (A blank value terminates execution).\\n' );\n fprintf ( 1, ' (Be sure to INCLUDE QUOTES around the string!\\n' );\n fprintf ( 1, '\\n' );\n\n sample_string = [];\n sample_string = input ( ' Enter SAMPLE: ' );\n\n fprintf ( 1, ' User input SAMPLE = \"%s\".\\n', sample_string );\n\n if ( s_len_trim ( sample_string ) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of SAMPLE \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n if ( s_eqi ( sample_string, 'RAND' ) )\n sample = -1;\n elseif ( s_eqi ( sample_string, 'RANDOM' ) )\n sample = -1;\n sample_string = 'RAND';\n elseif ( s_eqi ( sample_string, 'UNIFORM' ) )\n sample = 0;\n elseif ( s_eqi ( sample_string, 'HALTON' ) )\n sample = 1;\n elseif ( s_eqi ( sample_string, 'GRID' ) )\n sample = 2; \n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of SAMPLE \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SAMPLE_NUM is the number of sample points.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The Voronoi regions will be explored by generating\\n' );\n fprintf ( 1, ' SAMPLE_NUM points. For each sample point, the\\n' );\n fprintf ( 1, ' nearest generator is found. Using more points\\n' );\n fprintf ( 1, ' gives a better estimate of these regions.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SAMPLE_NUM should be much larger than N, the\\n' );\n fprintf ( 1, ' number of generators.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (Try ''10000'' if you have no preference.)\\n' );\n fprintf ( 1, ' (A zero or negative value terminates execution.)\\n' );\n fprintf ( 1, '\\n' );\n\n sample_num = [];\n sample_num = input ( ' Enter SAMPLE_NUM: ' );\n\n fprintf ( 1, ' User input SAMPLE_NUM = %12d\\n', sample_num );\n\n if ( sample_num <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of SAMPLE_NUM = %12d\\n', sample_num );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' BATCH is the number of sample points to create\\n' );\n% fprintf ( 1, ' at one time\\n' );\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' BATCH should be between 1 and SAMPLE_NUM.\\n' );\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' It is FASTER to set BATCH to SAMPLE_NUM;\\n' );\n% fprintf ( 1, ' setting BATCH to 1 requires the least memory.\\n' );\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' (Try ''%d'' if you have no preference.)\\n', ...\n% min ( 1000, sample_num ) );\n% fprintf ( 1, ' (A zero or negative value terminates execution.)\\n' );\n% fprintf ( 1, '\\n' );\n\n% batch = [];\n% batch = input ( ' Enter BATCH: ' );\n batch = 1000;\n\n fprintf ( 1, ' Default BATCH = %12d\\n', batch );\n\n if ( batch <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of BATCH = %12d\\n', batch );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' MOVIE_NAME is the name of the file in which the movie is stored;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (Try ''movie.avi'' if you have no preference.)\\n' );\n fprintf ( 1, ' (A blank value terminates execution).\\n' );\n fprintf ( 1, ' (Be sure to INCLUDE QUOTES around the string!\\n' );\n fprintf ( 1, ' \\n' );\n\n movie_name = [];\n movie_name = input ( ' Enter MOVIE_NAME: ' );\n\n fprintf ( 1, ' User input MOVIE_NAME = %s\\n', movie_name );\n\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' OUTPUT is a file into which the data is stored;\\n' );\n% fprintf ( 1, '\\n' );\n% fprintf ( 1, ' (Try ''cvt.txt'' if you have no preference.)\\n' );\n% fprintf ( 1, ' (A blank value terminates execution).\\n' );\n% fprintf ( 1, ' (Be sure to INCLUDE QUOTES around the string!\\n' );\n% fprintf ( 1, ' \\n' );\n\n% file_out_name = [];\n% file_out_name = input ( ' Enter OUTPUT: ' );\n\n file_out_name = 'cvt.txt';\n\n fprintf ( 1, ' Default OUTPUT = \"%s\".\\n', file_out_name );\n\n if ( s_len_trim ( file_out_name ) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of OUTPUT \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n if ( s_len_trim ( file_out_name ) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_MOVIE\\n' );\n fprintf ( 1, ' The input value of OUTPUT \\n' );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n%\n% Initialize the data.\n%\n if ( init == 3 )\n r = data_read ( sample_string, ndim, n );\n else\n r = [];\n end\n\n seed_init = seed;\n%\n% Initialize the data unless the user has already done that.\n%\n if ( init ~= 3 )\n\n initialize = 1;\n\n [ r, seed ] = cvt_sample ( ndim, n, n, init, initialize, seed );\n\n end\n%\n% If the initialization and sampling steps use the same random number\n% scheme, then the sampling scheme does not have to be initialized.\n%\n if ( init == sample )\n initialize = 0;\n else\n initialize = 1;\n end\n\n if ( file_exist ( movie_name ) )\n file_delete ( movie_name )\n end\n\n if ( DEBUG )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step SEED L2-Change Energy\\n' );\n fprintf ( 1, '\\n' );\n end\n\n num_frames_per_second = 10;\n aviobj = avifile ( movie_name, 'fps', num_frames_per_second ); \n box = [ 0.0, 0.0; 1.0, 0.0; 1.0, 1.0; 0.0, 1.0 ]';\n\n it_num = 0;\n it_diff = 0.0;\n seed_base = seed_init;\n seed = seed_init;\n\n while ( it_num < it_max )\n%\n% Once every IT_FIXED steps, update the base value of SEED,\n% either to SEED_INIT before the first call to CVT_ITERATE, or to the \n% output value of SEED from the previous call to CVT_ITERATE.\n%\n% Otherwise, reset the value of SEED to SEED_BASE.\n%\n if ( mod ( it_num, it_fixed ) == 0 )\n seed_base = seed;\n else\n seed = seed_base;\n end\n\n it_num = it_num + 1;\n\n seed_init2 = seed;\n\n [ r, seed, it_diff, energy ] = cvt_iterate ( ndim, n, batch, sample, ...\n initialize, sample_num, seed, r );\n\n scatter ( r(1,1:n), r(2,1:n), [], 'r', 'filled' );\n line ( [ 0.0, 1.0, 1.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 1.0, 0.0 ] );\n axis ( [ -0.05, 1.05, -0.05, 1.05 ] );\n axis equal\n%\n% Label the axes and the plot.\n%\n xlabel ( 'X', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16 );\n\n ylabel ( 'Y', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16, 'Rotation', 0 );\n\n it_string = sprintf ( 'Step %4d', it_num );\n\n title ( it_string, 'FontName', 'Helvetica', 'FontWeight', ...\n 'bold', 'FontSize', 16 );\n\n frame = getframe ( gca );\n aviobj = addframe ( aviobj, frame );\n\n initialize = 0;\n\n if ( DEBUG )\n fprintf ( 1, ' %4d %12d %14e %14e\\n', ...\n it_num, seed_init2, it_diff, energy );\n end\n\n end \n\n aviobj = close ( aviobj );\n%\n% Write the final data to a file.\n%\n cvt_write ( ndim, n, batch, seed_init, seed, init_string, it_max, ...\n it_fixed, it_num, it_diff, energy, sample_string, sample_num, ...\n r, file_out_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data was written to the file \"%s\".\\n', ...\n file_out_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press RETURN to proceed.\\n' );\n \n pause\n \n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Final value of SEED = %d\\n', seed );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cvt_movie/cvt_movie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6488199409684238}} {"text": "function [X p ei ej] = chrobak_payne_straight_line_drawing(A,varargin)\n% CHROBAK_PAYNE_STRAIGHT_LINE_DRAWING Draw planar graphs with straight lines\n%\n% X = chrobak_payne_straight_line_drawing(A) generates coordinates for each\n% vertex such that a planar graph A can be drawn without any edge\n% crossings. This function reports an error if A is not planar.\n%\n% [X,p,ei,ej] = ... returns additional information. p is a\n% canonical planar ordering of the vertices, and [ei ej] are additional\n% edges required to make A a maximal_planar graph.\n%\n% ... = chrobak_payne_straight_line_drawing(A,...) takes a set of\n% key-value pairs or an options structure. See set_matlab_bgl_options\n% for the standard options. \n% options.is_maximal: is A already a maximal planar graph [{0} | 1]\n%\n% Note: Be careful with is_maximal=1 and nocheck=1. If the graph is not\n% maximal, then the call will crash Matlab.\n%\n% Example:\n% [A,xy] = grid_graph(6,5);\n% X = chrobak_payne_straight_line_drawing(A);\n% gplot(A,X,'.-'); hold on; gplot(A,xy*20,'r.-'); hold off\n% % it's still planar, but not obviously a grid!\n\n% David Gleich\n% Copyright, Stanford University, 2008\n\n%% History\n% 2007-10-06: Initial coding\n%%\n\n[trans check full2sparse] = get_matlab_bgl_options(varargin{:});\nif full2sparse && ~issparse(A), A = sparse(A); end\n\noptions = struct('is_maximal',0);\noptions = merge_options(options,varargin{:});\nif check\n check_matlab_bgl(A,struct('sym',1)); \n if options.is_maximal,\n [i j] = make_maximal_planar(A);\n if ~isempty(i), error('matlab_bgl:checkFailed',...\n 'The graph was not a maximal planar but is_maximal was set.'); end\n end\nend\n\n[ei ej p X] = planar_drawing_mex(A,options.is_maximal,0);\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/chrobak_payne_straight_line_drawing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6488065164809818}} {"text": "function f = f08_f0 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% F08_F0 returns the value of function 8.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real X(N,1), Y(N,1), the evalution points.\n%\n% Output, real F(N,1), the function values.\n%\n t1(1:n,1) = 5.0 - 10.0 * x(1:n,1);\n t2(1:n,1) = 5.0 - 10.0 * y(1:n,1);\n t3(1:n,1) = exp ( - 0.5 * t1(1:n,1) .* t1(1:n,1) );\n t4(1:n,1) = exp ( - 0.5 * t2(1:n,1) .* t2(1:n,1) );\n f(1:n,1) = t3(1:n,1) + 0.75 * t4(1:n,1) .* ( 1.0 + t3(1:n,1) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp_2d/f08_f0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.648806507763697}} {"text": "function [vert,econ,tria] = cfmtri2(vert,econ)\n%CFMTRI2 compute a conforming 2-simplex Delaunay triangulat-\n%ion in the two-dimensional plane.\n% [VERT,CONN,TRIA]=CFMTRI2(VERT,CONN) computes the confor-\n% ming Delaunay trianguation, given the points VERT, and\n% edge constraints CONN. New points are inserted to bisect\n% edge constraints until all are recovered. VERT is a\n% V-by-2 array of XY coordinates to be triangulated, TRIA\n% is a T-by-3 array of vertex indexing, with each row\n% defining a triangle, such that VERT(TRIA(II,1),:),\n% VERT(TRIA(II,2),:) and VERT(TRIA(II,3),:) are the coord-\n% inates of the II-TH triangle. CONN is a C-by-2 array of\n% constraining edges, where each row defines an edge, as\n% per the TRIA array.\n%\n% See also DELTRI2, DELAUNAYN\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 07/07/2017\n\n%---------------------------------------------- basic checks\n if ( ~isnumeric(vert) || ...\n ~isnumeric(econ) )\n error('cfmtri2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n%---------------------------------------------- basic checks\n if (ndims(vert) ~= +2 || ndims(econ) ~= +2)\n error('cfmtri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n if (size(vert,2)~= +2 || size(econ,2)~= +2)\n error('cfmtri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n%-- the DELAUNAYN routine is *not* well-behaved numerically,\n%-- so explicitly re-scale the problem about [-1,-1; +1,+1].\n vmax = max(vert,[],1) ;\n vmin = min(vert,[],1) ;\n\n vdel = vmax - vmin;\n vdel = mean(vdel) ;\n vdel = vdel * +.5 ;\n\n vmid = vmax + vmin;\n vmid = vmid * +.5 ;\n\n vert = vert - vmid;\n vert = vert / vdel;\n\n%-- keep bisecting edge constraints until they are all reco-\n%-- vered!\n while (true)\n\n %----------------- un-constrained delaunay triangulation\n tria = delaunay2(vert) ;\n\n nv = size(vert,+1);\n nt = size(tria,+1);\n\n %----------------------------- build non-unique edge-set\n ee = zeros(nt*3,2);\n ee((1:nt)+nt*0,:) = tria(:,[1,2]);\n ee((1:nt)+nt*1,:) = tria(:,[2,3]);\n ee((1:nt)+nt*2,:) = tria(:,[3,1]);\n\n %----------------- find constraints within tria-edge set\n [in] = setset2(econ,ee) ;\n\n %----------------------------- done when have contraints\n if (all(in)), break; end\n\n %----------------------------- un-recovered edge centres\n vm = vert(econ(~in,1),:) ...\n + vert(econ(~in,2),:) ;\n vm = vm * +.5 ;\n\n %----------------------------- un-recovered edge indexes\n ev = nv+(1:size(vm,1))';\n en = [econ(~in,+1), ev;\n econ(~in,+2), ev];\n\n %----------------------------- push new vert/edge arrays\n vert = [vert( :,:); vm];\n econ = [econ(in,:); en];\n\n end\n\n%--------------------------------- undo geomertic re-scaling\n vert = vert * vdel ;\n vert = vert + vmid ;\n\nend\n\nfunction [tria] = delaunay2(vert)\n%DELAUNAY2 thin wrapper for DELAUNAYN, so that we can have a\n% more efficient version in OCTAVE...\n\n isoctave = exist( ...\n 'OCTAVE_VERSION','builtin')>+0;\n\n if (isoctave)\n\n %-- call QHULL and then filter zero-volume simplexes via\n %-- vectorised area comparisons.\n\n %-- note silliness re. EVAL, so that MATLAB doesn't com-\n %-- plain re. OCTAVE '__' names.\n\n tria = eval( ...\n '__delaunayn__(vert)') ;\n\n ab = vert(tria(:,2),:) ...\n - vert(tria(:,1),:) ;\n ac = vert(tria(:,3),:) ...\n - vert(tria(:,1),:) ;\n\n aa = ab(:,1).* ac(:,2) ...\n - ab(:,2).* ac(:,1) ;\n\n lb = sumsq(ab,2) ;\n lc = sumsq(ac,2) ;\n\n ll = max (lb,lc) ;\n\n keep = abs(aa) >= ll * eps^.8 ;\n\n tria = tria(keep,:);\n\n else\n\n %-- the default call in MATLAB seems to be fast enough!!\n\n tria = ...\n delaunay (vert(:,1),vert(:,2));\n\n end\n\nend\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-util/cfmtri2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6487793044106503}} {"text": "function [p, npix] = histroi(f, c, r)\n%HISTROI Computes the histogram of an ROI in an image.\n% [P, NPIX] = HISTROI(F, C, R) computes the histogram, P, of a\n% polygonal region of interest (ROI) in image F. The polygonal\n% region is defined by the column and row coordinates of its\n% vertices, which are specified (sequentially) in vectors C and R,\n% respectively. All pixels of F must be >= 0. Parameter NPIX is the\n% number of pixels in the polygonal region. \n\n% Copyright 2002-2004 R. C. Gonzalez, R. E. Woods, & S. L. Eddins\n% Digital Image Processing Using MATLAB, Prentice-Hall, 2004\n% $Revision: 1.5 $ $Date: 2003/09/05 16:14:35 $\n\n% Generate the binary mask image.\nB = roipoly(f, c, r);\n\n% Compute the histogram of the pixels in the ROI.\np = imhist(f(B));\n\n% Obtain the number of pixels in the ROI if requested in the output.\nif nargout > 1\n npix = sum(B(:)); \nend\n\n\n", "meta": {"author": "61--", "repo": "weiyanmin", "sha": "e15a7789602ec65c7ce1972bd905826ff4851435", "save_path": "github-repos/MATLAB/61---weiyanmin", "path": "github-repos/MATLAB/61---weiyanmin/weiyanmin-e15a7789602ec65c7ce1972bd905826ff4851435/Matlab/histroi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.6487792942166346}} {"text": "function [deltaTNew,xNew,tNew,k,dxdtCur,exitCode]=performOneAdaptiveRKStep(xCur,tCur,f,deltaT,deltaTMinMag,deltaTMaxMag,dxdtCur,order,solutionChoice,AbsTol,RelTol)\n%%PERFORMONEADAPTIVERKSTEP Perform a single adaptive Runge-Kutta step,\n% returning the new adjusted stepsize. This function is a\n% subroutine of the function RKAdaptiveOverRange. Though\n% most folks will just directly use the function\n% RKAdaptiveOverRange to perform adaptive Runge-Kutta\n% integration over a particular timespan, this subroutine\n% has been broken out separately as one might want to\n% program Runge-Kutta integration routines that\n% adaptively integrate until a certain criterion is\n% satisfied. As this function is meant as an efficient\n% subroutine, none of the inputs provide default\n% parameters if omitted.\n%\n%INPUTS: xCur The NX1 state vector at time tCur.\n% tCur The scalar current time of integration.\n% f The function handle for f(x,t)=dxdt over which integration is\n% to be performed. The output is NX1-dimensional.\n% deltaT The current stepsize to be taken in t. This can be positive\n% or negative.\n% deltaTMinMag The minimum allowable magnitude of the step size.\n% deltaTMaxMag The maximum allowable magnitude of the step size.\n% dxdtCur The value f(xCur,tCur). This is requested so that methods\n% that are FSAL (See comments to the function RungeKStep) can\n% avoid additional computations.\n% order,solutionChoice A pair of optional parameters that specify the\n% highest order of the embedded Runge-Kutta pair to use as\n% well as the specific algorithm to use. Details are given in\n% the comments to the RungeKStep function. If omitted or empty\n% matrices are passed, the default order of 5 is used and the\n% default solutionChoice of 0 is used.\n% RelTol The maximum relative error tolerance allowed, a positive\n% scalar (its use is explained in more detail below).\n% AbsTol The absolute error tolerance allowed, a positive scalar, of\n% the same for all components of x, or a positive NX1 vector.\n%\n%OUTPUTS: deltaTNew The value of deltaT that can be used for the next\n% adaptive step (i.e. pass it to this function). If the\n% function fails (exitCode~=0), then this will be set to the\n% last step size used.\n% xNew The updated NX1 state vector.\n% tNew The time of the updated state vector.\n% k The values of the derivatives f evaluated at various\n% points as determined by the algorithm used for the\n% step. This can be passed to functions like RKInterpPolys to\n% perform interpolation.\n% exitCode A code indicating whether the step could be successfully\n% performed. Possible values are\n% 0: Integration was successful.\n% 1: Unable to get a small enough step size.\n% 3: Non-finite number encountered.\n%\n%The algorithm used for the step is described in the comments to the\n%function RKAdaptiveOverRange.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %Determine the orders of the main and subsidiary embedded Runge-Kutta\n %formulae that were chosen. The order of convergence for the step size\n %testing is the smallest order taken. The isFSAL flag indicates whether\n %k(:,end) is the value of f evaluated at the next step.\n [orders,isFSAL]=RungeKStep(order,solutionChoice);\n RKOrder=min(orders);\n\n deltaTMag=abs(deltaT);\n deltaTSign=sign(deltaT);\n \n %The first time the choice in step size fails, it is adjusted the\n %\"optimal\" way in the Runge-Kutta-Fehlberg method. Additional times,\n %the step size is just halved in the hope that it will reach an\n %accepted value more quickly.\n failedReducingStepSize=false;\n moveOnToNextStep=false;\n while(moveOnToNextStep==false)\n %The returned value dxValdt in k(:,1) is for xCur and tCur, which\n %is curStep-1.\n [xPredMain,xPredSubsid,k]=RungeKStep(xCur,tCur,f,deltaT,dxdtCur,order,solutionChoice);\n\n %Integration can only be over finite functions.\n if(any(~isfinite(xPredMain))||any(~isfinite(xPredSubsid)))\n xNew=[];\n tNew=[];\n exitCode=3;\n deltaTNew=deltaTMag;\n return;\n end\n \n %The local error estimate. This must be transformed into a \n %combination relative/ absolute error term to determine whether\n %the step should be rejected.\n normFactor=max(max(abs(xPredMain),abs(xCur)),AbsTol/RelTol);\n theError=max(abs((xPredMain-xPredSubsid)./normFactor));\n\n if(theError>RelTol)\n if(deltaTMag=1);\n Al = numel(A);\n A(end+1:m) = 0;\n % Upper half list (initialize with this index because above includes \"equal\")\n J = (1:m)';\n\n % While below and above still have elements\n while Bl>0 && Al>0\n % pop below\n b = B(Bl);\n Bl = Bl - 1;\n % Look above\n a = A(Al);\n % a going to be b's upper half\n J(b) = a;\n % lob off enough to fit D(b) to 1\n %D(a) = D(a) - (1.0 - D(b));\n % Reduce rounding error (see comments above)\n D(a) = (D(a) + D(b)) - 1.0;\n if D(a) < 1\n % pop off above\n Al = Al - 1;\n % push onto below\n Bl = Bl+1;\n B(Bl) = a;\n % else still on above\n end\n end\n\n R1 = floor(rand(n,1)*m)+1;\n R2 = rand(n,1);\n I = (1:m)';\n % select those that are in upper half\n upper = R2>=D(R1);\n S = I(R1);\n S(upper) = J(R1(upper));\n \nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/sample_discrete.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6487792893911712}} {"text": "function UNew = fluidDirichlet2D(varargin);\n% fluidDirichlet2D: solve fluid registraion in 2D with Dirichlet\n% boundary conditions\n%\n%\n% author: Nathan D. Cahill\n% email: nathan.cahill@rit.edu\n% affiliation: Rochester Institute of Technology\n% date: January 2014\n% licence: GNU GPL v3\n%\n% Copyright Nathan D. Cahill\n% Code available from https://github.com/tomdoel/npReg\n%\n%\n\n% parse input arguments\n[DU,F,mu,lambda,PixSize,NumPix,HX,HY] = parse_inputs(varargin{:});\n\n% construct filters that implement discretized Navier-Lame equations\nd1 = [1;-2;1]/(PixSize(1)^2);\nd2 = [1 -2 1]/(PixSize(2)^2);\nd12 = [1 0 -1;0 0 0;-1 0 1]/(4*PixSize(1)*PixSize(2));\n\n[A11,A22] = deal(zeros(3,3));\nA11(:,2) = A11(:,2) + (lambda+2*mu)*d1;\nA11(2,:) = A11(2,:) + mu*d2;\nA22(:,2) = A22(:,2) + mu*d1;\nA22(2,:) = A22(2,:) + (lambda+2*mu)*d2;\n\nA12 = d12*(lambda+mu)/4;\nA21 = A12;\n\n% multiply force field by adjoint of Navier-Lame equations\nFnew = zeros(NumPix(1),NumPix(2),2);\nFnew(:,:,1) = imfilter(F(:,:,1),A22,'replicate') - imfilter(F(:,:,2),A12,'replicate');\nFnew(:,:,2) = imfilter(F(:,:,2),A11,'replicate') - imfilter(F(:,:,1),A21,'replicate');\n\n% compute sine transform of new force field\nFnewF1 = imag(fft(imag(fft(Fnew(:,:,1),2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nFnewF2 = imag(fft(imag(fft(Fnew(:,:,2),2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nFnewF1 = FnewF1(1:NumPix(1),1:NumPix(2));\nFnewF2 = FnewF2(1:NumPix(1),1:NumPix(2));\n\n% construct images of coordinates scaled by pi/(N or M)\n[alpha,beta] = ndgrid(pi*(0:(NumPix(1)-1))/(NumPix(1)-1),pi*(0:(NumPix(2)-1))/(NumPix(2)-1));\n\n% construct LHS factor\nLHSfactor = mu.*(lambda+2*mu).*(2*cos(alpha) + 2*cos(beta) - 4).^2;\n\n% set origin term to 1, as DC term does not matter\nLHSfactor(1,1) = 1;\n\n% solve for FFT of V\nVF1 = FnewF1./LHSfactor;\nVF2 = FnewF2./LHSfactor;\n\n% perform inverse DST\nV1 = imag(ifft(imag(ifft(VF1,2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nV2 = imag(ifft(imag(ifft(VF2,2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\n\n% crop and concatenate\nV = cat(3,V1(1:NumPix(1),1:NumPix(2)),V2(1:NumPix(1),1:NumPix(2)));\n\n% construct estimate of transformation Jacobian\nJ = zeros(NumPix(1),NumPix(2),2,2);\nJ(:,:,1,1) = 1 - imfilter(V(:,:,1),HX,'replicate','same');\nJ(:,:,2,1) = -imfilter(V(:,:,1),HY,'replicate','same');\nJ(:,:,1,2) = -imfilter(V(:,:,2),HX,'replicate','same');\nJ(:,:,2,2) = 1 - imfilter(V(:,:,2),HY,'replicate','same');\n\n% now perform Euler integration to construct new displacements\nUNew = zeros(NumPix(1),NumPix(2),2);\nUNew(:,:,1) = J(:,:,1,1).*V(:,:,1) + J(:,:,1,2).*V(:,:,2);\nUNew(:,:,2) = J(:,:,2,1).*V(:,:,1) + J(:,:,2,2).*V(:,:,2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [DU,F,mu,lambda,PixSize,NumPix,HX,HY] = parse_inputs(varargin);\n\n% get arguments\nF = varargin{2};\nPixSize = varargin{4}(1:2);\nNumPix = [varargin{5} varargin{6}];\nmu = varargin{8};\nlambda = varargin{9};\nDU = varargin{11};\nHX = varargin{12};\nHY = varargin{13};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/npReg/npRegLib/fluidDirichlet2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6486822865884335}} {"text": "% Performs fast detrended fluctuation analysis on a nonstationary input signal to\n% obtain an estimate for the scaling exponent.\n%\n% Useage:\n% [alpha, intervals, flucts] = fastdfa(x)\n% [alpha, intervals, flucts] = fastdfa(x, intervals)\n% Inputs\n% x - input signal: must be a column vector\n% Optional inputs\n% intervals - List of sample interval widths at each scale\n% (If not specified, then a binary subdivision is constructed)\n%\n% Outputs:\n% alpha - Estimated scaling exponent\n% intervals - List of sample interval widths at each scale\n% flucts - List of fluctuation amplitudes at each scale\n%\n% (c) 2006 Max Little. If you use this code, please cite:\n% M. Little, P. McSharry, I. Moroz, S. Roberts (2006),\n% Nonlinear, biophysically-informed speech pathology detection\n% in Proceedings of ICASSP 2006, IEEE Publishers: Toulouse, France.\n% \n\nfunction [alpha, intervals, flucts] = ML_fastdfa(x, varargin)\n\n[xpts, ypts] = ML_fastdfa_core(x, varargin{:});\n\n% Sort the intervals, and produce a log-log straight line fit\ndatapts = sortrows([xpts, ypts],1);\nintervals = datapts(:,1);\nflucts = datapts(:,2);\n\ncoeffs = polyfit(log10(xpts), log10(ypts), 1);\nalpha = coeffs(1);\n\nend", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/Max_Little/fastdfa/ML_fastdfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6486822842534321}} {"text": "%% Set up paths\n\npath(path,'mesh_functions/');\npath(path,'../data');\n\n%% Read shape\n\n[X,T] = readOff('../data/meshes/moomoo_s0.off');\nM = getMeshData(X,T,10); % compute 10 LB eigenfunctions for fun\n\n%% Set up Gaussian blur function\n\nblurTime = .001; % if this gets too small, distances get noisy\nblurSteps = 3;\n\n% h = blurTime/blurSteps;\n\nblur = @(x) blurOnMesh(x,M,blurTime,blurSteps); % faster than pre-factored?\nblurTranspose = @(x) blurOnMesh(x,M,blurTime,blurSteps,1);\n\n%% Design a few functions to average\n\ncenterVerts = [300 100 600];\nnFunctions = length(centerVerts);\n\ndistributions = zeros(M.numVertices,nFunctions);\n\nfor i=1:nFunctions\n distributions(centerVerts(i),i) = 1./M.areaWeights(centerVerts(i));\nend\n\ndistributions = blur(distributions);\n\nclose all\nfor i=1:nFunctions\n f = subplot(1,nFunctions,i);\n showDescriptor(M,distributions(:,i),[],[],[],f);\n colorbar off;\n title(sprintf('Distribution %d',i));\nend\n\n%% Take the barycenter\n\neuclideanBarycenter = sum(distributions,2)/nFunctions;\n\nf = subplot(1,2,1);\nshowDescriptor(M,euclideanBarycenter,[],[],[],f);\ntitle('Euclidean barycenter');\ncolorbar off;\n\nalpha = [1 1 1];\nbarycenter = convolutionalBarycenter(distributions,alpha,M.areaWeights,blur,blurTranspose);\n\nf = subplot(1,2,2);\nshowDescriptor(M,barycenter,[],[],[],f);\ntitle('Wasserstein barycenter');\ncolorbar off;\n\n%% Test different entropy limits\n\naverageEntropy = -mean(sum(bsxfun(@times,distributions.*log(distributions),M.areaWeights),1));\n\nentropyChanges = [-1.5 -1 -.5 0 .5 1 1.5];\n\neuclideanBarycenter = sum(distributions,2)/nFunctions;\n\nf = subplot(1,length(entropyChanges)+1,1);\nshowDescriptor(M,euclideanBarycenter,[],[],[],f);\ntitle('Euclidean barycenter');\ncolorbar off;\n\nfor i=1:length(entropyChanges)\n targetEntropy = averageEntropy + entropyChanges(i);\n \n alpha = [1 1 1];\n barycenter = convolutionalBarycenter(distributions,alpha,M.areaWeights,blur,blurTranspose,targetEntropy);\n\n f = subplot(1,length(entropyChanges)+1,i+1);\n showDescriptor(M,barycenter,[],[],[],f);\n title(sprintf('entropy < average+(%g)',entropyChanges(i)));\n colorbar off;\n \n drawnow;\nend\n \n%% Try displacement interpolation\n\nnTimeSteps = 100;\n\np1 = distributions(:,1);\np2 = distributions(:,2);\n\ninterp = zeros(M.numVertices,nTimeSteps);\nfor i=1:nTimeSteps\n fprintf('i = %d/%d\\n',i,nTimeSteps);\n t = (i-1)/(nTimeSteps-1);\n alpha = [t 1-t]; % is this right?\n interp(:,i) = convolutionalBarycenter([p1 p2],alpha,M.areaWeights,blur,blurTranspose,averageEntropy);\nend\n\n%% Animate the result\n\nf = figure;\nfor i=1:nTimeSteps\n clf;\n showDescriptor(M,interp(:,i),[],[],[],f);\n colorbar off;\n drawnow;\nend", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/tests/testConvolutionalBarycenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6486062894475805}} {"text": "function subRoPS = subRoPSFunc(projNeighbor,binSize)\n%get the distribution matrix\nneighbNum = length(projNeighbor);\ndistrMatrix = zeros(binSize,binSize);\nminX = min(projNeighbor(:,1));\nstepX = (max(projNeighbor(:,1))-minX)/binSize;\nminY = min(projNeighbor(:,2));\nstepY = (max(projNeighbor(:,2))-minY)/binSize;\n\nif stepX==0 || stepY==0\n subRoPS = [0,0,0,0,0];\n return;\nend\n\nfor k=1:neighbNum\n idxX = ceil((projNeighbor(k,1) - minX)/stepX);\n idxY = ceil((projNeighbor(k,2) - minY)/stepY);\n if idxX>binSize idxX = binSize; end\n if idxX<1 idxX = 1; end\n if idxY>binSize idxY = binSize; end\n if idxY<1 idxY = 1; end\n distrMatrix(idxX,idxY) = distrMatrix(idxX,idxY)+1;\nend\ndistrMatrix = distrMatrix/neighbNum;%normalization\n%calculate the moment of this distribution matrix\nmeanX = 0;\nmeanY = 0;\npde = 0;\nfor idxX = 1:binSize\n for idxY = 1:binSize\n meanX = meanX+idxX*distrMatrix(idxX,idxY);\n meanY = meanY+idxY*distrMatrix(idxX,idxY);\n if distrMatrix(idxX,idxY)>0\n pde = pde - distrMatrix(idxX,idxY)*log2(distrMatrix(idxX,idxY));\n end\n end\nend\nu11 = 0;\nu21 = 0;\nu12 = 0;\nu22 = 0;\n\nfor idxX = 1:binSize\n for idxY = 1:binSize\n u11 = u11+(idxX-meanX)*(idxY-meanY)*distrMatrix(idxX,idxY);\n u21 = u21+(idxX-meanX)^2*(idxY-meanY)*distrMatrix(idxX,idxY);\n u12 = u12+(idxX-meanX)*(idxY-meanY)^2*distrMatrix(idxX,idxY);\n u22 = u22+(idxX-meanX)^2*(idxY-meanY)^2*distrMatrix(idxX,idxY);\n end\nend \n subRoPS = [u11,u21,u12,u22,pde];", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/RoPSMatcher/RoPS Toolbox2/subRoPSFunc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6486062719270284}} {"text": "% This library is coded for the double pendulum example\n% Last Updated: 2019/07/30\n% Coded By: K.Kahirman\n\nfunction [Data,Sym_Struct]=SINDyLib(X,dX,iter,u,Highest_Poly_Order,Highest_Trig_Order,Highest_U_Order,Highest_dPoly_Order)\n%% First get the size of the X matrix, determin the data length and the number of variables we have.\n[Data_Length,Variable_Number]=size(X);\n[~,Variable_Number_dX]=size(dX);\n[~,Variable_Number_u]=size(u);\n%Also create the symbolic variable\nSymbol=sym('z',[Variable_Number,1]);\nSymbol_dX=sym('dz',[Variable_Number,1]);\nSymbol_u=sym('u',[Variable_Number_u,1]);\n\n%Now according the Highest Polynomial Order entered, we will calculate the data matrix.\nData=[];\nIndex=1;\n\n%% First calculate the polynomial term\n\n% Form basis vector\nBasis=[X(:,1) X(:,2) X(:,1)-X(:,2) X(:,1)-2*X(:,2) 2*X(:,1)-X(:,2) 2*X(:,1)-2*X(:,2)];\nBasis_Sym=[Symbol(1) Symbol(2) Symbol(1)-Symbol(2) Symbol(1)-2*Symbol(2) 2*Symbol(1)-Symbol(2) 2*Symbol(1)-2*Symbol(2)];\n\n% Add the trigonometric form\nfor i=1:size(Basis,2)\n Data(:,Index)=sin(Basis(:,i));\n Sym_Struct{1,Index}=sin(Basis_Sym(1,i));\n Index=Index+1;\nend\n\nfor i=1:size(Basis,2)\n Data(:,Index)=cos(Basis(:,i));\n Sym_Struct{1,Index}=cos(Basis_Sym(1,i));\n Index=Index+1;\nend\n\nfor i=3:size(Basis,2)\n Data(:,Index)=cos(Basis(:,i)).^2;\n Sym_Struct{1,Index}=cos(Basis_Sym(1,i))^2;\n Index=Index+1;\nend\n\n% Adding following terms will reduce the noise robustness\n% for i=3:size(Basis,2)\n% Data(:,Index)=sin(Basis(:,1)).*cos(Basis(:,i));\n% Sym_Struct{1,Index}=sin(Basis_Sym(1,1))*cos(Basis_Sym(1,i));\n% Index=Index+1;\n% end\n% \n% for i=3:size(Basis,2)\n% Data(:,Index)=cos(Basis(:,1)).*cos(Basis(:,i));\n% Sym_Struct{1,Index}=cos(Basis_Sym(1,1))*cos(Basis_Sym(1,i));\n% Index=Index+1;\n% end\n% \n% for i=3:size(Basis,2)\n% Data(:,Index)=sin(Basis(:,2)).*cos(Basis(:,i));\n% Sym_Struct{1,Index}=sin(Basis_Sym(1,2))*cos(Basis_Sym(1,i));\n% Index=Index+1;\n% end\n% \n% for i=3:size(Basis,2)\n% Data(:,Index)=cos(Basis(:,2)).*cos(Basis(:,i));\n% Sym_Struct{1,Index}=cos(Basis_Sym(1,2))*cos(Basis_Sym(1,i));\n% Index=Index+1;\n% end\n\n% Add polynomial term\nData(:,Index)=X(:,3);\nSym_Struct{1,Index}=Symbol(3);\nIndex=Index+1;\n\nData(:,Index)=X(:,4);\nSym_Struct{1,Index}=Symbol(4);\nIndex=Index+1;\n\nfor i=3:size(Basis,2)\n Data(:,Index)=X(:,3).*sin(Basis(:,i));\n Sym_Struct{1,Index}=Symbol(3)*sin(Basis_Sym(1,i));\n Index=Index+1;\nend\n\nfor i=3:size(Basis,2)\n Data(:,Index)=X(:,4).*sin(Basis(:,i));\n Sym_Struct{1,Index}=Symbol(4)*sin(Basis_Sym(1,i));\n Index=Index+1;\nend\n\nfor i=3:size(Basis,2)\n Data(:,Index)=X(:,3).^2.*sin(Basis(:,i));\n Sym_Struct{1,Index}=Symbol(3)^2*sin(Basis_Sym(1,i));\n Index=Index+1;\nend\n\nfor i=3:size(Basis,2)\n Data(:,Index)=X(:,4).^2.*sin(Basis(:,i));\n Sym_Struct{1,Index}=Symbol(4)^2*sin(Basis_Sym(1,i));\n Index=Index+1;\nend\n\n% Add dx term\nData(:,Index)=dX(:,1);\nSym_Struct{1,Index}=Symbol_dX(iter);\nIndex=Index+1;\n\nfor i=3:size(Basis,2)\n Data(:,Index)=dX(:,1).*cos(Basis(:,i)).^2;\n Sym_Struct{1,Index}=Symbol_dX(iter)*cos(Basis_Sym(1,i)).^2;\n Index=Index+1;\nend\n\n% Add constant\n%Order zero:\nData(:,Index)=ones(Data_Length,1);\nSym_Struct{1,Index}=1;\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/DoublePendulum/Functions/SINDyLib.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.648598529236839}} {"text": "% =========================================================================\n% NCSR for image denoising, Version 1.0\n% Copyright(c) 2013 Weisheng Dong, Lei Zhang, Guangming Shi, and Xin Li\n% All Rights Reserved.\n%\n% ----------------------------------------------------------------------\n% Permission to use, copy, or modify this software and its documentation\n% for educational and research purposes only and without fee is here\n% granted, provided that this copyright notice and the original authors'\n% names appear on all copies and supporting documentation. This program\n% shall not be used, rewritten, or adapted as the basis of a commercial\n% software or hardware product without first obtaining permission of the\n% authors. The authors make no representations about the suitability of\n% this software for any purpose. It is provided \"as is\" without express\n% or implied warranty.\n%----------------------------------------------------------------------\n%\n% This is an implementation of the algorithm for image interpolation\n% \n% Please cite the following paper if you use this code:\n%\n% Weisheng Dong, Lei Zhang, Guangming Shi, and Xin Li.,\"Nonlocally \n% centralized sparse representation for image restoration\", IEEE Trans. on\n% Image Processing, vol. 22, no. 4, pp. 1620-1630, Apr. 2013.\n% \n%--------------------------------------------------------------------------\nfunction [pos_arr, wei_arr] = Block_matching(im, par)\nS = 30; \nf = par.win;\nf2 = f^2;\nnv = par.nblk;\ns = par.step;\nhp = max(12*par.nSig, par.hp);\n\nN = size(im,1)-f+1;\nM = size(im,2)-f+1;\nr = [1:s:N];\nr = [r r(end)+1:N];\nc = [1:s:M];\nc = [c c(end)+1:M];\nL = N*M;\nX = zeros(f*f, L, 'single');\n\nk = 0;\nfor i = 1:f\n for j = 1:f\n k = k+1;\n blk = im(i:end-f+i,j:end-f+j);\n X(k,:) = blk(:)';\n end\nend\n\nI = (1:L);\nI = reshape(I, N, M);\nN1 = length(r);\nM1 = length(c);\npos_arr = zeros(nv, N1*M1 );\nwei_arr = zeros(nv, N1*M1 ); \nX = X';\n\nfor i = 1 : N1\n for j = 1 : M1\n \n row = r(i);\n col = c(j);\n off = (col-1)*N + row;\n off1 = (j-1)*N1 + i;\n \n rmin = max( row-S, 1 );\n rmax = min( row+S, N );\n cmin = max( col-S, 1 );\n cmax = min( col+S, M );\n \n idx = I(rmin:rmax, cmin:cmax);\n idx = idx(:);\n B = X(idx, :); \n v = X(off, :);\n \n \n dis = (B(:,1) - v(1)).^2;\n for k = 2:f2\n dis = dis + (B(:,k) - v(k)).^2;\n end\n dis = dis./f2;\n [val,ind] = sort(dis); \n dis(ind(1)) = dis(ind(2));\n \n wei = exp( -dis(ind(1:nv))./hp );\n wei = wei./(sum(wei)+eps);\n indc = idx( ind(1:nv) );\n pos_arr(:,off1) = indc;\n wei_arr(:,off1) = wei;\n end\nend\npos_arr = pos_arr';\nwei_arr = wei_arr';\n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/NCSR/Utilities/Block_matching.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6485985218579644}} {"text": "%% FUNCTION bsa_ihb\n% Singular Projection \n%\n%% OBJECTIVE\n% min 1/2*||x - a||_2^2\n% s.t. b'*x = r, 0<= x <= u, b > 0\n%\n%% LICENSE\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Copyright (C) 2011 - 2012 Jiayu Zhou, Pinghua Gong and Jieping Ye \n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on June 3, 2012.\n%\n%% Related papers\n%\n% [1] KC. Kiwiel. On linear-time algorithms for the continuous \n% quadratic knapsack problem, Journal of Optimization Theory \n% and Applications, 2007\n%\n\n\nfunction [x_star,t_star,iter] = bsa_ihb(a,b,r,u)\n\n% initilization\nbreak_flag = 0;\nt_l = a./b; t_u = (a - u)./b;\nT = [t_l;t_u];\nt_L = -inf; t_U = inf;\ng_tL = 0; g_tU = 0;\n\niter = 0;\nwhile ~isempty(T)\n iter = iter + 1;\n g_t = 0;\n t_hat = median(T); \n \n U = t_hat < t_u;\n M = (t_u <= t_hat) & (t_hat <= t_l); \n\n if sum(U)\n g_t = g_t + b(U)'*u(U); \n end\n if sum(M)\n g_t = g_t + sum(b(M).*(a(M) - t_hat*b(M)));\n end\n \n if g_t > r\n t_L = t_hat;\n T = T(T > t_hat);\n g_tL = g_t;\n elseif g_t < r\n t_U = t_hat;\n T = T(T < t_hat);\n g_tU = g_t;\n else\n t_star = t_hat;\n break_flag = 1;\n break; \n end\nend\nif ~break_flag\n t_star = t_L - (g_tL -r)*(t_U - t_L)/(g_tU - g_tL); \nend\nx_star = min(max(0,a - t_star*b),u);\nend", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/cASO/bsa_ihb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6485591809298402}} {"text": "function MS = createMesh2D(varargin)\n% MeshStructure = createMesh2D(Nx, Ny, Lx, Ly)\n% MeshStructure = createMesh2D(facelocationX, facelocationY)\n% creates a uniform 2D mesh:\n% Nx is the number of cells in x (horizontal) direction\n% Ny is the number of cells in y (vertical) direction\n% Lx is the domain length in x direction\n% Ly is the domain length in y direction\n%\n% SYNOPSIS:\n% MeshStructure = createMesh2D(Nx, Ny, Lx, Ly)\n%\n% PARAMETERS:\n% Nx: number of cells in the x direction\n% Lx: domain length in x direction\n% Ny: number of cells in the y direction\n% Ly: domain length in y direction\n%\n% RETURNS:\n% MeshStructure.\n% dimensions=2 (2D problem)\n% numbering: shows the indexes of cellsn from left to right\n% and top to bottom\n% cellsize: x and y elements of the cell size =[Lx/Nx,\n% Ly/Ny]\n% cellcenters.x: location of each cell in the x direction\n% cellcenters.y: location of each cell in the y direction\n% facecenters.x: location of interface between cells in the\n% x direction\n% facecenters.y: location of interface between cells in the\n% y direction\n% numberofcells: [Nx, Ny]\n%\n%\n% EXAMPLE:\n% Nx = 5;\n% Ny = 7;\n% Lx = 10;\n% Ly = 20;\n% m = createMesh2D(Nx, Ny, Lx, Ly);\n% [X, Y] = ndgrid(m.cellcenters.x, m.cellcenters.y);\n% [Xf,Yf]=ndgrid(m.facecenters.x, m.facecenters.y);\n% plot(X, Y, 'or', ...\n% Xf, Yf, '-b', Xf', Yf', '-b');\n%\n% SEE ALSO:\n% createMesh1D, createMesh3D, createMeshCylindrical1D, ...\n% createMeshCylindrical2D, createCellVariable, createFaceVariable\n\n% Written by Ali A. Eftekhari\n% See the license file\n\nif nargin==4\n % uniform 1D mesh\n Nx=varargin{1};\n Ny=varargin{2};\n Width=varargin{3};\n Height=varargin{4};\n % cell size is dx\n dx = Width/Nx;\n dy = Height/Ny;\n G=reshape(1:(Nx+2)*(Ny+2), Nx+2, Ny+2);\n CellSize.x= dx*ones(Nx+2,1);\n CellSize.y= dy*ones(Ny+2,1);\n CellSize.z= [0.0];\n CellLocation.x= [1:Nx]'*dx-dx/2;\n CellLocation.y= [1:Ny]'*dy-dy/2;\n CellLocation.z= [0.0];\n FaceLocation.x= [0:Nx]'*dx;\n FaceLocation.y= [0:Ny]'*dy;\n FaceLocation.z= [0.0];\nelseif nargin==2\n % nonuniform 1D mesh\n facelocationX=varargin{1};\n facelocationY=varargin{2};\n facelocationX=facelocationX(:);\n facelocationY=facelocationY(:);\n Nx = length(facelocationX)-1;\n Ny = length(facelocationY)-1;\n G=reshape(1:(Nx+2)*(Ny+2), Nx+2, Ny+2);\n CellSize.x= [facelocationX(2)-facelocationX(1); ...\n facelocationX(2:end)-facelocationX(1:end-1); ...\n facelocationX(end)-facelocationX(end-1)];\n CellSize.y= [facelocationY(2)-facelocationY(1); ...\n facelocationY(2:end)-facelocationY(1:end-1); ...\n facelocationY(end)-facelocationY(end-1)];\n CellSize.z= [0.0];\n CellLocation.x= 0.5*(facelocationX(2:end)+facelocationX(1:end-1));\n CellLocation.y= 0.5*(facelocationY(2:end)+facelocationY(1:end-1));\n CellLocation.z= [0.0];\n FaceLocation.x= facelocationX;\n FaceLocation.y= facelocationY;\n FaceLocation.z= [0.0];\nend\nc=G([1,end], [1,end]);\nMS=MeshStructure(2, ...\n [Nx,Ny], ...\n CellSize, ...\n CellLocation, ...\n FaceLocation, ...\n c(:), ...\n [1]);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/MeshGeneration/createMesh2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6485591790345432}} {"text": "function model = kpca_train(X,varargin)\n% DESCRIPTION\n% Kernel principal component analysis (KPCA)\n%\n% model = kpca_train(X,varargin)\n%\n% INPUT\n% X Training samples (N*d)\n% N: number of samples\n% d: number of features\n%\n% OUTPUT\n% model KPCA model\n%\n%\n% Created on 18th April 2019, by Kepeng Qiu.\n%-------------------------------------------------------------%\n\n% Default Parameters setting\noptions.sigma = 10; % kernel width\noptions.dims = 2; % output dimension (dimensionality reduction)\n % 2D data is easy to visualize\noptions.type = 0; % 0: dimensionality reduction or feature extraction\n % 1: fault detection using KPCA\n % 2: fault detection using dynamic KPCA(DKPCA)\noptions.beta = 0.9; % corresponding probabilities (for fault detection)\n % \noptions.pcr = 0.65; % principal contribution rate (for fault detection)\noptions.fd = 0; % 0: No fault diagnosis (fd)\n % 1: fault diagnosis (fd)\noptions.lag = 4; % time lag (for DKPCA)\n%\n\nif rem(nargin-1,2)\n error('Parameters to kpca_train should be pairs')\nend\nnumParameters = (nargin-1)/2;\n\nfor n =1:numParameters\n Parameters = varargin{(n-1)*2+1};\n value\t= varargin{(n-1)*2+2};\n switch Parameters\n %\n case 'type'\n options.type = value;\n %\n case 'dims'\n options.dims = value;\n %\n case 'sigma'\n options.sigma = value;\n %\n case 'fd'\n options.fd = value;\n %\n case 'lag'\n options.lag = value;\n %\n case 'pcr'\n options.pcr = value;\n %\n case 'beta'\n options.beta = value;\n end\nend\n\n% number of training samples\nL = size(X,1);\n\n% DPCA\nif options.type == 2\n % Construct the augmented matrix\n X = constructAM(X,options.lag);\n L = size(X,1);\n model.lag = options.lag; % time lag\nend\n\n% Compute the kernel matrix\nK = computeKM(X,X,options.sigma);\n\n% Centralize the kernel matrix\nunit = ones(L,L)/L;\nK_c = K-unit*K-K*unit+unit*K*unit;\n\n% Solve the eigenvalue problem\n[V,D] = eigs(K_c/L);\n% [V,D] = eig(K_c/L);\nlambda = diag(D);\n\n% Normalize the eigenvalue\nV_s = V ./ sqrt(L*lambda)';\n% Lower version of MATLAB may report an error at line 70,\n% please replace it with the following code.\n% ------------------------------\n% for i = 1:size(lambda,1)\n% V_s(:,i) = V(:,i)/sqrt(L*lambda(i,1));\n% end\n% ------------------------------\n\n% Compute the numbers of principal component\nif options.type == 1 || options.type == 2 % fault detection\n dims = find(cumsum(lambda/sum(lambda)) >= ...\n options.pcr,1, 'first');\nelse % dimensionality reduction or feature extraction\n dims = options.dims;\nend\n\n% Extract the nonlinear component\nmappedX = K_c* V_s(:,1:dims) ;\n\n% Store the results\nmodel.mappedX = mappedX ;\nmodel.V_s = V_s;\nmodel.lambda = lambda;\nmodel.K_c = K_c;\nmodel.L = L;\nmodel.dims = dims;\nmodel.X = X;\nmodel.K = K;\nmodel.unit = unit;\nmodel.sigma = options.sigma;\nmodel.diagnosis = options.fd;\nmodel.type = options.type;\n\n% Compute the threshold for fault detection\nif options.type == 1 || options.type == 2\n model.beta = options.beta; % corresponding probabilities\n [SPE_limit,T2_limit] = comtupeLimit(model);\n model.SPE_limit = SPE_limit;\n model.T2_limit = T2_limit;\nend\n\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/特征提取算法/Kernel-Principal-Component-Analysis-KPCA-master/func/kpca_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6485591659944809}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n% Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% function [ D ] = dctn( A, varargin )\n%\n% N-D Discrete Cosine Transform\n%\n% Computes the N-dimensional dct of an array, by applying the\n% one-dimnesional dct along all dimensions.\n% \n% Input:\n%\n% A - full N-dimensional array\n% varargin - (optional flag in which dimensions to apply the dct)\n%\n% Output:\n%\n% D - discrete cosine transform of A\n%\n%==============================================================================\n\nfunction [ D ] = dctn( A, varargin )\n\nif nargin==0\n help(mfilename)\n return;\nend\n\n% size if the input array\nm = size(A);\ndim = length(m);\n\n% default parameters\ndimFlag = ones(1,dim); % apply dct in all dimensions by default\n\n% overwrites default parameter\nfor k=1:2:length(varargin), \n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\nm = size(A);\nD = A;\nmd = m;\nP = circshift(1:dim,[0 -1]);\n\nfor d=1:dim\n if dimFlag(d)\n D = reshape(D,md(1),prod(md(2:end)));\n D = dct(D);\n D = reshape(D,md);\n end\n md = circshift(md,[0 -1]);\n D = permute(D,P);\nend\n\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/add-ons/LagLDDMM/dctn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6483006810477997}} {"text": "function y = SSST (x, p)\n% SSST Spherical Surface Spline in Tension\n%\n% y = SSST (x, p)\n%\n% x is cos(theta) in range -1 <= x <= 1\n% p is tension (p >= 0)\n%\n% Returns the Green's' function for a spherical surface spline\n% in tension, following Wessel and Becker [2008].\n% If p == 0 or not given then we return Parker's [1994] minimum\n% curvature solution instead.\n\n% $Id: SSST.m,v 1.1.1.1 2008/05/09 21:34:52 myself Exp $\n% P. Wessel, SOEST, U of Hawaii, April 2008 (pwessel@hawaii.edu)\n\nif nargin == 1\n\tp = 0;\nend\nif (p == 0) % Just do Parker's dilog solution\n y = dilog (0.5 - 0.5 * x);\n return\nend\n\n% Here we have tension\nv = tension2nu (p);\n\ny = zeros(size(x)); % Initialize output array\nA = pi / sin(v*pi); % Constant scale\nk = find (abs(x) < (1-eps)); % Where Pv solution works\nif (~isempty(k))\n y(k) = A*Pv(-x(k),v) - log(1-x(k));\nend\n% Deal with special case x == -1\nk = find ((x-eps) <= -1);\nif (~isempty(k))\n y(k) = A - log(2);\nend\n% Deal with special case x == +1\nk = find ((x+eps) >= +1);\nif (~isempty(k))\n y(k) = pi*cot(v*pi) + 2*(0.577215664901 + psi(1+v)) - log(2);\nend\ny = real(y); % Knock off any insignificant imaginary noise\n\n% Sub-functions used by SSST\nfunction P = Pv (x, v)\n\nP = zeros(size(x));\nfor i = 1:length(x)\n if (x(i) == -1)\n p = inf;\n else\n [p q k] = PvQv (x(i), v);\n end\n P(i) = p;\nend\n\nfunction [Pv Qv iter] = PvQv (x, v)\n% Based on recipe in \"An Atlas of Functions\" by\n% Spanier and Oldham, 1987\niter = 0;\nif (x == -1)\n Pv = -inf;\n Qv = -inf;\n return\nend\nif (x == +1)\n Pv = 1;\n Qv = inf;\n return\nend\na = 1;\nR = 1;\nK = 4 * sqrt (abs(v - v^2));\nif (abs(1+v) + floor (1+v)) == 0\n\ta = 1.0e99;\n\tv = -1 - v;\nend\ns = sin (0.5*pi*v);\nc = cos (0.5*pi*v);\nw = (0.5 + v)^2;\nwhile v <= 6.0\n\tv = v + 2;\n\tR = R * (v - 1)/v;\nend\nX = 1.0 / (4 + 4*v);\ng = 1 + 5*X*(1 - 3*X*(0.35+6.1*X));\nR = R*(1 - X*(1 - g*X/2))/sqrt (8*X);\ng = 2*x;\nu = g;\nf = 1;\nt = 1;\nk = 0.5;\nX = 1 + (1e8/(1 - x.^2));\n\nt = t .* x.^2 * (k^2 - w) / ((k + 1)^2 - 0.25);\nk = k + 1;\nf = f + t;\nu = u .* x.^2 * (k^2 - w) / ((k + 1)^2 - 0.25);\nk = k + 1;\ng = g + u;\nwhile (k < K || abs (X*t) > abs(f))\n iter = iter + 1;\n\tt = t .* x.^2 * (k^2 - w) / ((k + 1)^2 - 0.25);\n\tk = k + 1;\n\tf = f + t;\n\tu = u .* x.^2 * (k^2 - w) / ((k + 1)^2 - 0.25);\n\tk = k + 1;\n\tg = g + u;\nend\nf = f + (x.^2.*t ./ (1 - x.^2));\ng = g + (x.^2.*u ./ (1 - x.^2));\nPv = ((s*g*R) + (c*f/R))/sqrt(pi);\nQv = a*sqrt(pi)*((c*g*R) - (s*f/R))/2;\n\nfunction [f] = psi(z)\n%Psi Psi (or Digamma) function valid in the entire complex plane.\n%\n% d\n% Psi(z) = --log(Gamma(z))\n% dz\n%\n%usage: [f] = psi(z)\n%\n% Z may be complex and of any size.\n%\n% This program uses the analytical derivative of the\n% Log of an excellent Lanczos series approximation\n% for the Gamma function.\n% \n%References: C. Lanczos, SIAM JNA 1, 1964. pp. 86-96\n% Y. Luke, \"The Special ... approximations\", 1969 pp. 29-31\n% Y. Luke, \"Algorithms ... functions\", 1977\n% J. Spouge, SIAM JNA 31, 1994. pp. 931\n% W. Press, \"Numerical Recipes\"\n% S. Chang, \"Computation of special functions\", 1996\n%\nsiz = size(z);\nz=z(:);\nzz=z;\n\nf = zeros(size(z));\n\n%reflection point\np=find(real(z)<0.5);\nif ~isempty(p)\n z(p)=1-z(p);\nend\n\n%Lanczos approximation for the complex plane\n \ng=607/128; % best results when 4<=g<=5\n \nc = [ 0.99999999999999709182;\n 57.156235665862923517;\n -59.597960355475491248;\n 14.136097974741747174;\n -0.49191381609762019978;\n .33994649984811888699e-4;\n .46523628927048575665e-4;\n -.98374475304879564677e-4;\n .15808870322491248884e-3;\n -.21026444172410488319e-3;\n .21743961811521264320e-3;\n -.16431810653676389022e-3;\n .84418223983852743293e-4;\n -.26190838401581408670e-4;\n .36899182659531622704e-5];\n\n\nn=0;\nd=0;\nfor k=size(c,1):-1:2\n dz=1./(z+k-2);\n dd=c(k).*dz;\n d=d+dd;\n n=n-dd.*dz;\nend\nd=d+c(1);\ngg=z+g-0.5;\n%log is accurate to about 13 digits...\n\nf = log(gg) + (n./d - g./gg) ;\n\nif ~isempty(p)\n f(p) = f(p)-pi*cot(pi*zz(p));\nend\n\np=find(round(zz)==zz & real(zz)<=0 & imag(zz)==0);\nif ~isempty(p)\n f(p) = Inf;\nend\n\nf=reshape(f,siz);\n\nfunction y = dilog (x)\n% DILOG The dilogarithm\n%\n% y = dilog (x)\n%\n% Compute dilog(x) (defined for x >= 0) by the method of Parker's\n% Appendix A of his Geophysical Inverse Theory. The function\n% is needed for x in the range 0 <= x <= 1 when solving the\n% spherical spline interpolation in section 2.07 of Parker.\n\ny = zeros (size (x));\n\npisqon6 = pi * pi / 6.0;\nk = find (x <= 0.0);\nif (~isempty(k))\n y(k) = pisqon6;\nend\nk = find (x > 0.0 & x < 0.5);\nif (~isempty(k))\n\ty(k) = -log (1.0 - x(k));\n\tysq = y(k) .* y(k);\n\tz = y(k) .* (1.0 + y(k) .* (-0.25 + y(k) .* (0.027777777777213 + ...\n ysq .* (-2.7777776990e-04 + ysq .* (4.724071696e-06 + ...\n ysq .* (-9.1764954e-08 + 1.798670e-09 .* ysq))))));\n\ty(k) = pisqon6 - z + y(k) .* log (x(k));\nend\nk = find (x >= 0.5 & x < 2.0);\nif (~isempty(k))\n y(k) = -log (x(k));\n\tysq = y(k) .* y(k);\n\tz = y(k) .* (1.0 + y(k) .* (-0.25 + y(k) .* (0.027777777777213 + ...\n ysq .* (-2.7777776990e-04 + ysq .* (4.724071696e-06 + ...\n ysq .* (-9.1764954e-08 + 1.798670e-09 .* ysq))))));\n y(k) = z;\nend\nk = find (x >= 2.0);\nif (~isempty(k))\n y(k) = log (x(k));\n\tysq = y(k) .* y(k);\n\tz = y(k) .* (1.0 + y(k) .* (-0.25 + y(k) .* (0.027777777777213 + ...\n ysq .* (-2.7777776990e-04 + ysq .* (4.724071696e-06 + ...\n ysq .* (-9.1764954e-08 + 1.798670e-09 .* ysq))))));\n y(k) = -z - 0.5 * ysq;\nend\n\nfunction nu = tension2nu (p)\nnu = (-1 + sqrt (1 - 4*p^2))/2;\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/sphsplineToolbox/SSST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6483006611989341}} {"text": "function value = r8_besk0 ( x )\n\n%*****************************************************************************80\n%\n%% R8_BESK0 evaluates the Bessel function K of order 0 of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the Bessel function K of order 0 of X.\n%\n persistent bk0cs\n persistent ntk0\n persistent xmax\n persistent xsml\n\n if ( isempty ( ntk0 ) )\n\n bk0cs = [ ...\n -0.353273932339027687201140060063153E-01, ...\n +0.344289899924628486886344927529213, ...\n +0.359799365153615016265721303687231E-01, ...\n +0.126461541144692592338479508673447E-02, ...\n +0.228621210311945178608269830297585E-04, ...\n +0.253479107902614945730790013428354E-06, ...\n +0.190451637722020885897214059381366E-08, ...\n +0.103496952576336245851008317853089E-10, ...\n +0.425981614279108257652445327170133E-13, ...\n +0.137446543588075089694238325440000E-15, ...\n +0.357089652850837359099688597333333E-18, ...\n +0.763164366011643737667498666666666E-21, ...\n +0.136542498844078185908053333333333E-23, ...\n +0.207527526690666808319999999999999E-26, ...\n +0.271281421807298560000000000000000E-29, ...\n +0.308259388791466666666666666666666E-32 ]';\n\n ntk0 = r8_inits (bk0cs, 16, 0.1 * r8_mach ( 3 ) );\n xsml = sqrt ( 4.0 * r8_mach ( 3 ) );\n xmax = - log ( r8_mach ( 1 ) );\n xmax = xmax - 0.5 * xmax * log ( xmax ) / ( xmax + 0.5 );\n\n end\n\n if ( x <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BESK0 = Fatal error!\\n' );\n fprintf ( 1, ' X <= 0.\\n' );\n error ( 'R8_BESK0 = Fatal error!' )\n elseif ( x <= xsml )\n y = 0.0;\n value = - log ( 0.5 * x ) * r8_besi0 ( x ) ...\n - 0.25 + r8_csevl ( 0.5 * y - 1.0, bk0cs, ntk0 );\n elseif ( x <= 2.0 )\n y = x * x;\n value = - log ( 0.5 * x ) * r8_besi0 ( x ) ...\n - 0.25 + r8_csevl ( 0.5 * y - 1.0, bk0cs, ntk0 );\n elseif ( x <= xmax )\n value = exp ( - x ) * r8_besk0e ( x );\n else\n value = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_besk0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6483006562957145}} {"text": "function [cost, gradf, hessian, hessianinv]=costgradf(px,py,pz,rho,u,param)\n% compute the cost function\n\ne=1e-6;\n\nh = param.h;\ndim = param.dim;\ngamma = param.gamma;\nA1x = param.A1x;\nA1y = param.A1y;\nA1z = param.A1z;\nA2 = param.A2;\nA3 = param.A3;\na = param.a;\nc = param.c;\nF1 = param.F1;\nF2 = param.F2;\n\nn = dim(1);\nnx = dim(2);\nny = dim(3);\nnz = dim(4);\nnt = dim(5);\nhx = h(1);\nhy = h(2);\nhz = h(3);\nht = h(4);\n\n\n%compute p^2 and u^2\n\npxsq = px.^2;\npysq = py.^2;\npzsq = pz.^2;\nusq = u.^2;\n\n% inverse of rho\nrhoinv = 1./rho;\nrhoinv1 = 1./(F1'*rho(:));\nrhoinv2 = 1./(F2'*rho(:));\n\nE=eye(n);\nE(n,n)=e;\nW1=kron(speye((nx-1)*ny*nz*nt),E);\nW2=kron(speye((ny-1)*nx*nz*nt),E);\nW3=kron(speye((nz-1)*nx*ny*nt),E);\n\n% cost f\n%cost = (A1x*W1*pxsq(:)+A1y*W2*pysq(:)+A1z*W3*pzsq(:))'*(A2*rhoinv(:) + a(:))*hx*hy*hz*ht + usq(:)'*(A3*rhoinv1(:)+A3*rhoinv2(:)+ c(:))*hx*hy*hz*ht*gamma;\ncost = (A1x*W1*pxsq(:)+A1y*W2*pysq(:)+A1z*W3*pzsq(:))'*(A2*rhoinv(:) + a(:))*hx*hy*hz*ht + usq(:)'*(A3*rhoinv2(:)+ c(:))*hx*hy*hz*ht*gamma;\n% compute gradient of f\nif nargout > 1\n % derivative wrt px\n A11xe = 2*W1*A1x'*(A2*rhoinv(:)+a(:));\n nablapxf = px(:).*A11xe(:);\n \n % derivative wrt py\n A11ye = 2*W2*A1y'*(A2*rhoinv(:)+a(:));\n nablapyf = py(:).*A11ye(:);\n\n % derivative wrt pz\n A11ze = 2*W3*A1z'*(A2*rhoinv(:)+a(:));\n nablapzf = pz(:).*A11ze(:);\n \n % derivative wrt rho\n A22e = A2'*(A1x*W1*pxsq(:) + A1y*W2*pysq(:)+ A1z*W3*pzsq(:));\n nablarhof = -A22e.*rhoinv(:).^2-gamma.*F2*((A3'*usq(:)).*rhoinv2(:).^2);\n %-gamma.*F1*((A3'*usq(:)).*rhoinv1(:).^2);\n \n % derivative wrt u\n %A33e = 2*gamma*(A3*(rhoinv2(:)+rhoinv1(:))+c(:));\n A33e = 2*gamma*(A3*(rhoinv2(:))+c(:));\n nablauf = u(:).*A33e(:);\n \n % gradient wrt p rho u\n gradf = [nablapxf; nablapyf; nablapzf; nablarhof; nablauf];\n \n % compute Hessian\n if nargout > 2\n % Hessian over px\n A11x = A11xe; \n \n % Hessian over py\n A11y = A11ye;\n \n % Hessian over py\n A11z = A11ze;\n \n % hessian over rho\n temp1 = 2.*A22e.*rhoinv(:).^3;\n temp2 = 2.*gamma.*(F2*((A3'*usq(:)).*rhoinv2(:).^3));\n %temp3 = 2.*gamma.*(F1*((A3'*usq(:)).*rhoinv1(:).^3));\n A22 = temp1(:)+temp2(:)...+temp3(:)\n +1e-4*ones(n*nx*ny*nz*(nt-1),1);\n \n % hessian over u\n A33 = A33e;\n \n % hessian\n hessian = [A11x(:);A11y(:);A11z(:);A22(:);A33(:)];\n\n % compute the inverse of Hessian\n if nargout > 3\n % inverse of hessian\n hessianinv = spdiags(1./(hessian),0,numel(hessian),numel(hessian));\n end\n end\nend\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/optimalMassTransport/costgradf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6482590907307695}} {"text": "function varargout = drawEllipse3d(varargin)\n%DRAWELLIPSE3D Draw a 3D ellipse\n%\n% Possible calls for the function :\n% drawEllipse3d([XC YC ZC A B THETA PHI])\n% drawEllipse3d([XC YC ZC A B THETA PHI PSI])\n% drawEllipse3d([XC YC ZC A B], [THETA PHI])\n% drawEllipse3d([XC YC ZC A B], [THETA PHI PSI])\n% drawEllipse3d([XC YC ZC A B], THETA, PHI)\n% drawEllipse3d([XC YC ZC], A, B, THETA, PHI)\n% drawEllipse3d([XC YC ZC A B], THETA, PHI, PSI)\n% drawEllipse3d([XC YC ZC], A, B, THETA, PHI, PSI)\n% drawEllipse3d(XC, YC, ZC, A, B, THETA, PHI)\n% drawEllipse3d(XC, YC, ZC, A, B, THETA, PHI, PSI)\n%\n% where XC, YC, ZY are coordinate of ellipse center, A and B are the\n% half-lengths of the major and minor axes of the ellipse,\n% PHI and THETA are 3D angle (in degrees) of the normal to the plane\n% containing the ellipse (PHI between 0 and 360 corresponding to\n% longitude, and THETA from 0 to 180, corresponding to angle with\n% vertical).\n% \n% H = drawEllipse3d(...)\n% return handle on the created LINE object\n% \n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2008-05-07\n% Copyright 2008 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n\n% Possible calls for the function, with number of arguments :\n% drawEllipse3d([XC YC ZC A B THETA PHI]) 1\n% drawEllipse3d([XC YC ZC A B THETA PHI PSI]) 1\n% drawEllipse3d([XC YC ZC A B], [THETA PHI]) 2\n% drawEllipse3d([XC YC ZC A B], [THETA PHI PSI]) 2\n% drawEllipse3d([XC YC ZC A B], THETA, PHI) 3\n% drawEllipse3d([XC YC ZC A B], THETA, PHI, PSI) 4\n% drawEllipse3d([XC YC ZC], A, B, THETA, PHI) 5\n% drawEllipse3d([XC YC ZC], A, B, THETA, PHI, PSI) 6\n% drawEllipse3d(XC, YC, ZC, A, B, THETA, PHI) 7\n% drawEllipse3d(XC, YC, ZC, A, B, THETA, PHI, PSI) 8\n\n\n% extract drawing options\nind = find(cellfun(@ischar, varargin), 1, 'first');\noptions = {};\nif ~isempty(ind)\n options = varargin(ind:end);\n varargin(ind:end) = [];\nend\n\nif length(varargin)==1\n % get center and radius\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n a = ellipse(:,4);\n b = ellipse(:,5);\n \n % get colatitude of normal\n if size(ellipse, 2)>=6\n theta = ellipse(:,6);\n else\n theta = zeros(size(ellipse, 1), 1);\n end\n\n % get azimut of normal\n if size(ellipse, 2)>=7\n phi = ellipse(:,7);\n else\n phi = zeros(size(ellipse, 1), 1);\n end\n \n % get roll\n if size(ellipse, 2)==8\n psi = ellipse(:,8);\n else\n psi = zeros(size(ellipse, 1), 1);\n end\n \nelseif length(varargin)==2\n % get center and radius\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n a = ellipse(:,4);\n b = ellipse(:,5);\n \n % get angle of normal\n angle = varargin{2};\n theta = angle(:,1);\n phi = angle(:,2);\n \n % get roll\n if size(angle, 2)==3\n psi = angle(:,3);\n else\n psi = zeros(size(angle, 1), 1);\n end\n\nelseif length(varargin)==3 \n % get center and radius\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n a = ellipse(:,4);\n b = ellipse(:,5);\n \n % get angle of normal and roll\n theta = varargin{2};\n phi = varargin{3};\n psi = zeros(size(phi, 1), 1);\n \nelseif length(varargin)==4\n % get center and radius\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n \n if size(ellipse, 2)==5\n a = ellipse(:,4);\n b = ellipse(:,5);\n end\n \n theta = varargin{2};\n phi = varargin{3};\n psi = varargin{4};\n \nelseif length(varargin)==5\n % get center and radius\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n a = varargin{2};\n b = varargin{3};\n theta = varargin{4};\n phi = varargin{5};\n psi = zeros(size(phi, 1), 1);\n\nelseif length(varargin)==6\n ellipse = varargin{1};\n xc = ellipse(:,1);\n yc = ellipse(:,2);\n zc = ellipse(:,3);\n a = varargin{2};\n b = varargin{3};\n theta = varargin{4};\n phi = varargin{5};\n psi = varargin{6};\n \nelseif length(varargin)==7 \n xc = varargin{1};\n yc = varargin{2};\n zc = varargin{3};\n a = varargin{4};\n b = varargin{5};\n theta = varargin{6};\n phi = varargin{7};\n psi = zeros(size(phi, 1), 1);\n \nelseif length(varargin)==8 \n xc = varargin{1};\n yc = varargin{2};\n zc = varargin{3};\n a = varargin{4};\n b = varargin{5};\n theta = varargin{6};\n phi = varargin{7};\n psi = varargin{8};\n\nelse\n error('drawEllipse3d: please specify center and radius');\nend\n\n% uses 60 intervals\nt = linspace(0, 2*pi, 61)';\n\n% polyline approximation of ellipse, centered and parallel to main axes\nx = a * cos(t);\ny = b * sin(t);\nz = zeros(length(t), 1);\nbase = [x y z];\n\n% compute transformation from local basis to world basis\ntrans = localToGlobal3d(xc, yc, zc, theta, phi, psi);\n\n% transform points composing the ellipse\nellipse = transformPoint3d(base, trans);\n\n% draw the curve\nh = drawPolyline3d(ellipse, options{:});\n\nif nargout > 0\n varargout = {h};\nend\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/drawEllipse3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6482403271086316}} {"text": "function x_new = r8sd_cg ( n, ndiag, offset, a, b, x )\n\n%*****************************************************************************80\n%\n%% R8SD_CG uses the conjugate gradient method on a R8SD linear system.\n%\n% Discussion:\n%\n% The R8SD storage format is for symmetric matrices whose only nonzero entries\n% occur along a few diagonals, but for which these diagonals are not all\n% close enough to the main diagonal for band storage to be efficient.\n%\n% In that case, we assign the main diagonal the offset value 0, and \n% each successive superdiagonal gets an offset value 1 higher, until\n% the highest superdiagonal (the A(1,N) entry) is assigned the offset N-1.\n%\n% Assuming there are NDIAG nonzero diagonals (ignoring subdiagonals!),\n% we then create an array B that has N rows and NDIAG columns, and simply\n% \"collapse\" the matrix A to the left:\n%\n% For the conjugate gradient method to be applicable, the matrix A must \n% be a positive definite symmetric matrix.\n%\n% The method is designed to reach the solution to the linear system\n% A * x = b\n% after N computational steps. However, roundoff may introduce\n% unacceptably large errors for some problems. In such a case,\n% calling the routine a second time, using the current solution estimate\n% as the new starting guess, should result in improved results.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Frank Beckman,\n% The Solution of Linear Equations by the Conjugate Gradient Method,\n% in Mathematical Methods for Digital Computers,\n% edited by John Ralston, Herbert Wilf,\n% Wiley, 1967,\n% ISBN: 0471706892,\n% LC: QA76.5.R3.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer NDIAG, the number of diagonals that are stored.\n% NDIAG must be at least 1 and no more than N.\n%\n% Input, integer OFFSET(NDIAG), the offsets for the diagonal storage.\n%\n% Input, real A(N,NDIAG), the R8SD matrix.\n%\n% Input, real B(N), the right hand side vector.\n%\n% Input, real X(N), an estimate for the solution, which may be 0.\n%\n% Output, real X_NEW(N), the approximate solution vector. Note that \n% repeated calls to this routine, with the output X_NEW from the\n% previous call used as the input value of X, MAY improve the solution.\n%\n x_new(1:n) = x(1:n);\n%\n% Initialize\n% AP = A * x,\n% R = b - A * x,\n% P = b - A * x.\n%\n ap(1:n) = r8sd_mxv ( n, ndiag, offset, a, x_new );\n\n r(1:n) = b(1:n) - ap(1:n);\n p(1:n) = b(1:n) - ap(1:n);\n%\n% Do the N steps of the conjugate gradient method.\n%\n for it = 1 : n\n%\n% Compute the matrix*vector product AP = A*P.\n%\n ap(1:n) = r8sd_mxv ( n, ndiag, offset, a, p );\n%\n% Compute the dot products\n% PAP = P*AP,\n% PR = P*R\n% Set\n% ALPHA = PR / PAP.\n%\n pap = p(1:n) * ap(1:n)';\n pr = p(1:n) * r(1:n)';\n\n if ( pap == 0.0E+00 )\n return;\n end\n\n alpha = pr / pap;\n%\n% Set\n% X = X + ALPHA * P\n% R = R - ALPHA * AP.\n%\n x_new(1:n) = x_new(1:n) + alpha * p(1:n);\n r(1:n) = r(1:n) - alpha * ap(1:n);\n%\n% Compute the vector dot product\n% RAP = R*AP\n% Set\n% BETA = - RAP / PAP.\n%\n rap = r(1:n) * ap(1:n)';\n\n beta = - rap / pap;\n%\n% Update the perturbation vector\n% P = R + BETA * P.\n%\n p(1:n) = r(1:n) + beta * p(1:n);\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8sd_cg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6482403121261577}} {"text": "% homodyne_recon_demo.m\n%\n% - Demonstrates use of homodyne_recon.m, which implements the homodyne\n% reconstruction method outlined in Doug Noll's 1991 IEEE T-MI paper\n% \"Homodyne detection in magnetic resonance imaging\"\n% - Figure shows the decrease in RMSE that results from sampling more.\n% - Reconstructed image can be rectangular, with odd or even dimensions.\n%\n% 2012-06-15, Mai Le\n% 2012-09-26 Jeff Fessler tweaked\n\n% set up \"true\" brain image\n%f.dir = [path_find_dir('mri') '/../data/mri/'];\n%f.xtrue = [f.dir 'brainweb_t1.jpg'];\n%mag_true = double(imread(f.xtrue))'; % true image magnitude\nmag_true = 25*ellipse_im(256);\nmag_true = mag_true(16:end-16,3:end-2); % make it rectangle to stress test\ndims = size(mag_true);\n\n% simulate linear phase over object\n[xx yy] = ndgrid(-dims(1)/2:dims(1)/2-1,-dims(2)/2:dims(2)/2-1);\nph_max = pi/2;\nph = ph_max*xx/(dims(1)/2) + ph_max*yy/(dims(2)/2);\nimage = mag_true .* exp(1i*ph); % modulate to make it complex\nim_fft = fftshift(fft2(image));\n\nim plc 2 3\nim(1, mag_true)\n\nfor homodyne_direction = [1 2] % partial k-space can be in direction 1 or 2\n\t% # of samples in \"half\" kspace:\n\tnhalf = ceil((dims(homodyne_direction)+1)/2);\n\toverlaps = dims(homodyne_direction) - nhalf; % maximum # of extra rows\n\toverlaps = [0:5:(overlaps-1) overlaps];\n\tnover = numel(overlaps);\n\n\tnrms_im = zeros(nover,1);\n\tnrms_ph_demod = zeros(nover,1);\n\n\tfor ii = 1:nover\n\t\toverlap = overlaps(ii);\n\t\tif (homodyne_direction == 1)\n\t\t\tk1 = 1:min(dims(1), nhalf+overlap);\n\t\t\tpartial_kspace = im_fft(k1,:);\n\t\telseif (homodyne_direction == 2)\n\t\t\tk2 = 1:min(dims(2), nhalf+overlap);\n\t\t\tpartial_kspace = im_fft(:,k2);\n\t\telse\n\t\t\tfail 'bug'\n\t\tend\n\n\t\tf.sigma = 800; % complex AWGN std dev\n\t\tnoisy_partial_kspace = partial_kspace + f.sigma * ...\n\t\t\t(randn(size(partial_kspace)) + 1i*randn(size(partial_kspace)));\n\n\t\t[recon_ph_demod, recon_im, lp_im, full_kspace] = ...\n\t\t\thomodyne_recon(noisy_partial_kspace, dims(1), dims(2), ...\n\t\t\t\toverlap, 'direction', homodyne_direction);\n\n\t\tnrms_fun = @(x,y) 100 * nrms(x(:), y(:));\n\t\tnrms_im(ii) = nrms_fun(abs(recon_im), mag_true);\n\t\tnrms_ph_demod(ii) = nrms_fun(abs(recon_ph_demod), mag_true);\n\n\t\tif overlap <= 15\n\t\t\tclim = minmax(mag_true)';\n\t\t\tim(2, abs(recon_im), clim)\n\t\t\ttitlef('Conventional, overlap=%d', overlap)\n\t\t\tim(3, abs(recon_ph_demod), clim)\n\t\t\ttitlef('Demodulated, overlap=%d', overlap)\n\t\t\tim(4, log(abs(partial_kspace)), clim)\n\t\t\tim(5, abs(recon_im) - mag_true, [-9 9], 'Error')\n\t\t\tim(6, abs(recon_ph_demod) - mag_true, [-9 9], 'Error')\n\t\t\tdrawnow\n\t%\t\tprompt\n\t\tend\n\tend\n\n\tf.snr = sqrt(mean(abs(partial_kspace(:)).^2)) / ...\n\t\tsqrt(mean(abs(noisy_partial_kspace(:) - partial_kspace(:)).^2));\n\tf.snr = 20*log10(f.snr);\n\tpr f.snr\n\n\tim subplot 4\n\tplot(overlaps, nrms_im, 'g-+', overlaps, nrms_ph_demod, 'b-o')\n\taxis tight\n\txtick([0 15 max(overlaps)])\n\ttitle('NRMSE (%)')\n\tlegend('without demodulation', 'phase demodulated');\n\txlabel('rows acquired beyond 1/2 of kspace');\n\tylabel('NRMS error of reconstructed image (%)');\nprompt\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/le-mai-sense/homodyne_recon_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6482350830648643}} {"text": "classdef DOC4 < PROBLEM\n% \n% Benchmark MOP with constraints in both decision and objective spaces\n\n%------------------------------- Reference --------------------------------\n% Z. Liu and Y. Wang, Handling constrained multiobjective optimization\n% problems with constraints in both the decision and objective spaces. IEEE\n% Transactions on Evolutionary Computation, 2019, 23(5): 870-884.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n obj.D = 8;\n obj.lower = [0 -10 -10 -10 -10 -10 -10 -10];\n obj.upper = [ 1 10 10 10 10 10 10 10];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values and constraint violations\n function Population = Evaluation(obj,varargin)\n X = varargin{1};\n X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n g_temp = (X(:, 2) - 10).^2 + 5 * (X(:, 3) - 12).^2 + X(:, 4).^4 + 3 * (X(:, 5) - 11).^2 + 10 * X(:, 6).^6 + ...\n 7 * X(:, 7).^2 + X(:, 8).^4 - 4 * X(:, 7).* X(:, 8) - 10 * X(:, 7) - 8 * X(:, 8);\n g = g_temp-680.6300573745 +1;\n PopObj(:,1) = X(:,1);\n PopObj(:,2) = g.*(1-sqrt(PopObj(:,1))./g);\n % Constraints in objective space\n c(:,1) = max( -(PopObj(:,1) + PopObj(:,2)-1), 0);\n c(:,2) = max(- ( PopObj(:,1)+ PopObj(:,2) - 1 - abs(sin(10*pi*(PopObj(:,1) - PopObj(:,2) + 1) ))), 0);\n % Constraints in decision space\n c(:,3) = -127 + 2 * X(:, 2).^2 + 3 * X(:, 3).^4 + X(:, 4) + 4 * X(:, 5).^2 + 5 * X(:, 6);\n c(:,4) = -282 + 7 * X(:, 2) + 3 * X(:, 3) + 10 * X(:, 4).^2 + X(:, 5) - X(:, 6);\n c(:,5) = -196 + 23 * X(:, 2) + X(:, 3).^2 + 6 * X(:, 7).^2 - 8 * X(:, 8);\n c(:,6) = 4 * X(:, 2).^2 + X(:, 3).^2 - 3 * X(:, 2).* X(:, 3) + 2 * X(:, 4).^2 + 5 * X(:, 7) - 11 * X(:, 8);\n Population = SOLUTION(X,PopObj,c,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = (0:20)/20;\n R(:,2) = 1 - R(:,1);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/DOC/DOC4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.648235058187351}} {"text": "function La = YeePattanaikLuminanceAdaptation(img, maxLayers)\n%\n%\n% La = YeePattanaikLuminanceAdaptation(img, maxLayers)\n%\n%\n% Input:\n% -img: HDR image\n% -maxLayers: the number of layers in [16,96]\n%\n% Output:\n% -La: luminance adaptation\n% \n% Copyright (C) 2010-2020 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% The paper describing this technique is:\n% \"Segmentation and Adaptive Assimilation for Detail-Preserving Display of High-Dynamic Range Images\"\n% \t by Hector Yee, Sumanta N. Pattanaik\n% in Elsevier The Visual Computer 2003\n%\n\n%is it a three color channels image?\ncheck13Color(img);\n\ncheckNegative(img);\n\n%check parameters\nif(~exist('maxLayers', 'var'))\n maxLayers = 32;\nend\n\nif((maxLayers < 16) || (maxLayers > 96))\n maxLayers = 32;\nend\n\nmaxLayers = round(maxLayers);\n\n%these could be parameters\nbin_size1 = 0.5;\nbin_size2 = 2.0;\n\n%compute luminance channel\nL = lum(img);\n\n%compute the adaptation\nL_log = log10(L + 1e-6);\nminL_Log = min(L_log(:));\n\nLa = zeros(size(L));\n\nfor i=0:(maxLayers - 1)\n bin_size = bin_size1 + (bin_size2 - bin_size1) * i / (maxLayers - 1); \n category = round((L_log - minL_Log) / bin_size) + 1; \n\n %compute layers\n [imgLabel, ~, ~] = computeConnectedComponents(category, 8); \n labels = unique(imgLabel); \n \n for j=1:length(labels) %adaptation group\n indx = find(imgLabel == labels(j));\n La(indx) = La(indx) + mean(L_log(indx));\n end\nend\n\nLa = 10.^(La / maxLayers);\nLa(La < 0.0) = 0.0;\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/util/YeePattanaikLuminanceAdaptation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.648166875696035}} {"text": "function [ R ] = vl_nnr2R( r,dCdR )\n%r2R Axis angle to rotation matrix layer\n% Forwards mode:\n% R = vl_nnr2R(r);\n% r is of size 1 x 1 x 3 x nbatch containing axis angle vectors\n% R is of size 1 x 3 x 3 x nbatch containing rotation matrices\n% Backwards mode:\n% dCdr = vl_nnr2R(r,dCdR);\n% dCdR is derivative of the cost function with respect to R and is of\n% size 1 x 3 x 3 x nbatch\n% dCdr is derivative of the cost function with respect to r and is of\n% size 1 x 1 x 3 x nbatch\n%\n% Useful reference for formula:\n% [1] Gallego, Guillermo, and Anthony Yezzi. \"A compact formula for the \n% derivative of a 3-D rotation in exponential coordinates.\" Journal \n% of Mathematical Imaging and Vision 51.3 (2015): 378-384.\n\nnbatch = size(r,4);\nif nargin<2\n % Forwards\n\n % Vectors with zero length are a special case - they just have an\n % identity rotation matrix\n idmask = squeeze(all(r==0,3));\n\n R = zeros(1,3,3,nbatch,'single');\n \n % Fill in the identity cases\n R(1,1,1,idmask)=1;\n R(1,2,2,idmask)=1;\n R(1,3,3,idmask)=1;\n\n theta = sqrt(sum(r(:,:,:,~idmask).^2,3)); % 1 x 1 x 1 x non-zero nbatch rotation angles\n k1 = r(:,:,1,~idmask)./theta; % rotation axis unit vectors\n k2 = r(:,:,2,~idmask)./theta; % rotation axis unit vectors\n k3 = r(:,:,3,~idmask)./theta; % rotation axis unit vectors\n \n % Fill in the non-identity cases using the following formula (see [1]):\n % K = [0 -k(3) k(2); k(3) 0 -k(1); -k(2) k(1) 0]; \n % R = eye(3) + sin(theta).*K + (1-cos(theta)).*K*K;\n \n R(1,1,1,~idmask) = (cos(theta) - 1).*k2.^2 + (cos(theta) - 1).*k3.^2 + 1;\n R(1,1,2,~idmask) = -k3.*sin(theta) - k1.*k2.*(cos(theta) - 1);\n R(1,1,3,~idmask) = k2.*sin(theta) - k1.*k3.*(cos(theta) - 1);\n R(1,2,1,~idmask) = k3.*sin(theta) - k1.*k2.*(cos(theta) - 1);\n R(1,2,2,~idmask) = (cos(theta) - 1).*k1.^2 + (cos(theta) - 1).*k3.^2 + 1;\n R(1,2,3,~idmask) = -k1.*sin(theta) - k2.*k3.*(cos(theta) - 1);\n R(1,3,1,~idmask) = -k2.*sin(theta) - k1.*k3.*(cos(theta) - 1);\n R(1,3,2,~idmask) = k1.*sin(theta) - k2.*k3.*(cos(theta) - 1);\n R(1,3,3,~idmask) = (cos(theta) - 1).*k1.^2 + (cos(theta) - 1).*k2.^2 + 1;\nelse\n % Backwards\n \n\tidmask = squeeze(all(r==0,3));\n \n % Handle identity case\n dRdr1 = zeros(size(dCdR));\n dRdr1(1,2,3,idmask)=-1;\n dRdr1(1,3,2,idmask)=1;\n dRdr2 = zeros(size(dCdR));\n dRdr2(1,1,3,idmask)=1;\n dRdr2(1,3,1,idmask)=-1;\n dRdr3 = zeros(size(dCdR));\n dRdr3(1,1,2,idmask)=-1;\n dRdr3(1,2,1,idmask)=1;\n \n % Call forwards version to get R\n [ R ] = vl_nnr2R( r );\n \n % Subselect and precompute some values\n R11 = R(1,1,1,~idmask); R12 = R(1,1,2,~idmask); R13 = R(1,1,3,~idmask);\n R21 = R(1,2,1,~idmask); R22 = R(1,2,2,~idmask); R23 = R(1,2,3,~idmask);\n R31 = R(1,3,1,~idmask); R32 = R(1,3,2,~idmask); R33 = R(1,3,3,~idmask);\n r1 = r(1,1,1,~idmask); r2 = r(1,1,2,~idmask); r3 = r(1,1,3,~idmask);\n sqnorm = (r1.^2 + r2.^2 + r3.^2);\n \n % For all other cases, find 3x3 derivatives of R with respect to each\n % element of r\n dRdr1(1,1,1,~idmask) = (R31.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm - (R21.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm;\n dRdr1(1,1,2,~idmask) = (R32.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm - (R22.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm;\n dRdr1(1,1,3,~idmask) = (R33.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm - (R23.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm;\n dRdr1(1,2,1,~idmask) = (R11.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm - (R31.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm;\n dRdr1(1,2,2,~idmask) = (R12.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm - (R32.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm;\n dRdr1(1,2,3,~idmask) = (R13.*(r1.*r3 - R21.*r1 + r2.*(R11 - 1)))./sqnorm - (R33.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm;\n dRdr1(1,3,1,~idmask) = (R21.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm - (R11.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm; \n dRdr1(1,3,2,~idmask) = (R22.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm - (R12.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm;\n dRdr1(1,3,3,~idmask) = (R23.*(r1.^2 + R21.*r3 - R31.*r2))./sqnorm - (R13.*(R31.*r1 + r1.*r2 - r3.*(R11 - 1)))./sqnorm;\n \n dRdr2(1,1,1,~idmask) = (R31.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm - (R21.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm;\n dRdr2(1,1,2,~idmask) = (R32.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm - (R22.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm;\n dRdr2(1,1,3,~idmask) = (R33.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm - (R23.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm;\n dRdr2(1,2,1,~idmask) = (R11.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm - (R31.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm;\n dRdr2(1,2,2,~idmask) = (R12.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm - (R32.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm;\n dRdr2(1,2,3,~idmask) = (R13.*(R12.*r2 + r2.*r3 - r1.*(R22 - 1)))./sqnorm - (R33.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm;\n dRdr2(1,3,1,~idmask) = (R21.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm - (R11.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm;\n dRdr2(1,3,2,~idmask) = (R22.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm - (R12.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm;\n dRdr2(1,3,3,~idmask) = (R23.*(r1.*r2 - R32.*r2 + r3.*(R22 - 1)))./sqnorm - (R13.*(r2.^2 - R12.*r3 + R32.*r1))./sqnorm;\n\n dRdr3(1,1,1,~idmask) = (R31.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm - (R21.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm;\n dRdr3(1,1,2,~idmask) = (R32.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm - (R22.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm;\n dRdr3(1,1,3,~idmask) = (R33.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm - (R23.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm;\n\tdRdr3(1,2,1,~idmask) = (R11.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm - (R31.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm;\n dRdr3(1,2,2,~idmask) = (R12.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm - (R32.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm;\n dRdr3(1,2,3,~idmask) = (R13.*(r3.^2 + R13.*r2 - R23.*r1))./sqnorm - (R33.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm;\n dRdr3(1,3,1,~idmask) = (R21.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm - (R11.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm;\n dRdr3(1,3,2,~idmask) = (R22.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm - (R12.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm;\n dRdr3(1,3,3,~idmask) = (R23.*(R23.*r3 + r1.*r3 - r2.*(R33 - 1)))./sqnorm - (R13.*(r2.*r3 - R13.*r3 + r1.*(R33 - 1)))./sqnorm;\n\n dCdr(1,1,1,:) = sum(sum(dCdR.*dRdr1,2),3);\n dCdr(1,1,2,:) = sum(sum(dCdR.*dRdr2,2),3);\n dCdr(1,1,3,:) = sum(sum(dCdR.*dRdr3,2),3);\n \n R = dCdr;\nend\n\nend", "meta": {"author": "anilbas", "repo": "3DMMasSTN", "sha": "c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837", "save_path": "github-repos/MATLAB/anilbas-3DMMasSTN", "path": "github-repos/MATLAB/anilbas-3DMMasSTN/3DMMasSTN-c6562b5fda5c2f742a27dc1b4a7ff15ec5e83837/layer/vl_nnr2R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6481668593030167}} {"text": "function [ n_data, alpha, beta, x, fx ] = extreme_values_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% EXTREME_VALUES_CDF_VALUES returns some values of the Extreme Values CDF.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`ContinuousDistributions`\"]\n% dist = ExtremeValuesDistribution [ alpha, beta ]\n% CDF [ dist, x ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real ALPHA, the first parameter of the distribution.\n%\n% Output, real BETA, the second parameter of the distribution.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 12;\n\n alpha_vec = [ ...\n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.1000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.4000000000000000E+01, ... \n 0.5000000000000000E+01 ];\n\n beta_vec = [ ...\n 0.5000000000000000E+00, ... \n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.2000000000000000E+01, ...\n 0.3000000000000000E+01, ...\n 0.4000000000000000E+01, ...\n 0.5000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2000000000000000E+01 ];\n\n fx_vec = [ ...\n 0.3678794411714423E+00, ...\n 0.8734230184931166E+00, ...\n 0.9818510730616665E+00, ...\n 0.9975243173927525E+00, ...\n 0.5452392118926051E+00, ...\n 0.4884435800065159E+00, ...\n 0.4589560693076638E+00, ...\n 0.4409910259429826E+00, ...\n 0.5452392118926051E+00, ...\n 0.3678794411714423E+00, ...\n 0.1922956455479649E+00, ...\n 0.6598803584531254E-01 ];\n\n x_vec = [ ...\n 0.1000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.4000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.2000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01, ... \n 0.3000000000000000E+01 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n alpha = 0.0;\n beta = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n alpha = alpha_vec(n_data);\n beta = beta_vec(n_data);\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/extreme_values_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.648143207269536}} {"text": "function a = r8mat_geinverse ( a, n, pivot )\n\n%*****************************************************************************80\n%\n%% R8MAT_GEINVERSE computes the inverse of a matrix factored by R8MAT_GEFA.\n%\n% Discussion:\n%\n% R8MAT_GEINVERSE is a modified version of the LINPACK routine DGEDI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input/output, real A(N,N).\n% On input, the factor information computed by R8MAT_GEFA.\n% On output, the inverse matrix.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, integer PIVOT(N), the pivot vector from R8MAT_GEFA.\n%\n\n%\n% Compute Inverse(U).\n%\n for k = 1 : n\n\n a(k,k) = 1.0 / a(k,k);\n\n a(1:k-1,k) = - a(1:k-1,k) * a(k,k);\n\n for j = k + 1 : n\n\n temp = a(k,j);\n a(k,j) = 0.0;\n\n a(1:k,j) = a(1:k,j) + temp * a(1:k,k);\n\n end\n\n end\n%\n% Form Inverse(U) * Inverse(L).\n%\n for k = n - 1 : -1 : 1\n\n work(k+1:n) = a(k+1:n,k);\n a(k+1:n,k) = 0.0;\n\n for j = k + 1 : n\n a(1:n,k) = a(1:n,k) + work(j) * a(1:n,j);\n end\n\n if ( pivot(k) ~= k )\n\n for i = 1 : n\n temp = a(i,k);\n a(i,k) = a(i,pivot(k));\n a(i,pivot(k)) = temp;\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/r8mat_geinverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.648143187856752}} {"text": "function [ C , coord , MN ] = ccv ( A , N , F )\n% Generates a crystal consists of lattice sites and bases, Calculates\n% connecting vectors from point to point, Finds the number of nearest\n% neighbors of each atomic site.\n%\n% function [ C , coord , MN ] = ccv ( A , N , F )\n%\n% arguments: ( input )\n%\n% A - ( class - double ) a ( 3 * 3 ) matrix that each row is a vector that\n% shows primary generator vectors of a lattice in three dimensions.\n%\n% N - ( class - double ) a matrix with three possitive integers that shows\n% the number of atoms in each dimensions.\n%\n% F - ( class - double ) a ( m * 3 ) matrix that show the bases\n% coordinates. ( m is the number of bases )\n%\n% arguments: ( output )\n%\n% C - ( class - double ) A ( N ( 1 ) * N ( 2 ) * N ( 3 ) ) * ( N ( 1 ) *\n% N ( 2 ) * N ( 3 ) ) * 3 matrix connecting vector between each two atomic\n% sites\n%\n% coord - ( class - double ) Coordination number ( Number of nearest\n% neighbors ) of each atomic site\n%\n% MN - ( class - double ) Mean distance between the nearest neighbor of\n% each atomic site\n%\n% Example:\n% A = [ 2 3 3 ; 6 5 3 ; 2 5 3 ] ;\n% N = [ 4 3 5 ] ;\n% F = [ 0 0 0 ; 0 0 1 ; 0 -2 0 ] ;\n% [ CV , COORD , MN ] = ccv ( A , N , F )\n%\n% See also rcv.\n%\n% Copyright 2009\n%\n% Release Date: 2009-10-12\n\n% check for simple errors\n\nif nargin < 3\n F = [ 0 0 0 ] ;\nend % end of if loop\n\nif nargin < 2\n N = [ 3 3 3 ] ;\nend % end of if loop\n\nif nargin < 1\n A = [ 1 0 0 ; 0 1 0 ; 0 0 1 ] ;\nend % end of if loop\n\nif ( N ( 1 ) <= 0 ) || ( N ( 2 ) <= 0 ) || ( N ( 3 ) <= 0 ) % condition of negative numbers\n error ' Enterd demensions must be positive integers. ' % error message\nend % end of if loop\n\nV = dot ( A ( 1 , : ) , cross ( A ( 2 , : ) , A ( 3 , : ) ) ) ; % Primitive Cell Volume\n\nif V == 0 % condition of same plane vectors\n error ' Vectors must not be in same plane. ' % error message\nend % end of if loop\n\n% end of error checking\n\nn = ( N ( 1 ) * N ( 2 ) ) * N ( 3 ) ; % calculates the total number of atomic sites\nxy = zeros ( n , 3 ) ; % Preallocating\n\nfor i = 0 : N ( 1 ) - 1 % i is the numerator of for loop\n for j = 0 : N ( 2 ) - 1 % j is the numerator of for loop\n for k = 0 : N ( 3 ) - 1 % k is the numerator of for loop\n xy ( ( ( N ( 1 ) * j ) + ( i + 1 ) ) + ( N ( 1 ) * N ( 2 ) ) * k , : ) = A ( 1 , : ) * i + A ( 2 , : ) * j + A( 3 , : ) * k ;\n end % end of for loop\n end % end of for loop\nend % end of for loop\n\nxyold = xy ;\nf = size ( F ) ; \nxyo = [ ] ;\n\nfor q = 1 : f ( 1 ) % q is the numerator of for loop\n for p = 1 : 3 % p is the numerator of for loop\n xy ( : , p ) = xyold ( : , p ) + F ( q , p ) ;\n end % end of for loop\n xyo = [ xyo ; xy ] ;\nend % end of for loop\n\nn = length ( xyo ) ;\nxy = xyo ;\n\n\nC = zeros ( n , n , 3 ) ; % Preallocating\nD = zeros ( n , n , 3 ) ; % Preallocating\nE = zeros ( n , 3 ) ; % Preallocating\ncoord = zeros ( 1 , n ) ; % Preallocating\nMIN = zeros ( n-1 , n ); % Preallocating\nk = 1 ; % Preallocating\n\nfor P = 1 : n % P is the numerator of for loop\n for j = 1 : 3 % j is the numerator of for loop\n C ( P , 1 : n , j ) = xy ( 1 : n , j ) - xy ( P , j ) ; % Connecting vector elements between to lattice atomic sites\n D ( P , 1 : n , j ) = ( xy ( 1 : n , j ) - xy ( P , j ) ) .^ 2 ;\n end % end of for loop\n E ( P , 1 : n ) = sqrt ( D ( P , 1 : n , 1 ) + D ( P , 1 : n , 2 ) + D ( P , 1 : n , 3 ) ) ;\nend % end of for loop\n\nfor P = 1 : n % P is the numerator of for loop\n for i = 1 : n % i is the numerator of for loop\n if E ( P , i ) ~= 0\n MIN ( k ) = E ( P , i ) ; % Eliminates zero value elements\n k = k + 1 ;\n end % end of if loop\n end % end of for loop\nend % end of for loop\n\nMN = min ( MIN ) ; % Nearest neighbors distance\n\nfor P = 1 : n % P is the numerator of for loop\n t = 0 ; % Preallocating\n for i = 1 : n % i is the numerator of for loop\n if E ( P , i ) == MN ( P )\n t = t + 1 ; % Counts number of nearest neighbors\n end % end of if loop\n end % end of for loop\n coord ( P ) = t ;\nend % end of for loop\n\n% With special thanks to John D'Errico\n% By Ali Mohammad Razeghi\n% My Email ( am_razeghi@yahoo.com ) is also ready to get full detailed\n% commentation.", "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/25552-solid-state-physics-simulation-packv-0-02/ccv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384595, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6481151409457017}} {"text": "%% Tracking of rotating point using Kalman filter\n%\n% Tracking of rotating point.\n% Rotation speed is constant.\n% Both state and measurements vectors are 1D (a point angle),\n% Measurement is the real point angle + gaussian noise.\n% The real and the estimated points are connected with yellow line segment,\n% the real and the measured points are connected with red line segment.\n% (if Kalman filter works correctly,\n% the yellow segment should be shorter than the red one).\n%\n% Pressing any key will reset the tracking with a different speed.\n% Close the window to stop the program.\n%\n% Sources:\n%\n% * \n% * \n%\n\n%%\n% set up display window\nimg = zeros(500, 500, 3, 'uint8');\nhFig = figure('KeyPressFcn',@(o,e)setappdata(o, 'flag',true), ...\n 'Menubar','none', 'Name','Kalman Filter demo');\nsetappdata(hFig, 'flag',false);\nhImg = imshow(img);\n\n%%\n% helper anonymous functions\ncalcPoint = @(center,R,angle) center + [cos(angle), -sin(angle)]*R;\ndrawCross = @(img,center,clr,d) cv.line(...\n cv.line(img, center-d, center+d, 'Color',clr, ...\n 'Thickness',1, 'LineType','AA'), ...\n center+[d -d], center+[-d d], 'Color',clr, ...\n 'Thickness',1, 'LineType','AA');\n\n%%\n% create and initialize Kalman filter\nKF = cv.KalmanFilter(2, 1);\nstate = zeros(2,1); % [phi; delta_phi]\nprocessNoise = zeros(2,1);\nmeasurement = zeros(1,1);\n\n%%\n% keep repeating until figure is closed\nwhile ishghandle(hFig)\n setappdata(hFig, 'flag',false);\n\n % initialize KF\n state = randn(size(state))*0.1;\n KF.transitionMatrix = [1 1; 0 1];\n KF.measurementMatrix = eye(size(KF.measurementMatrix));\n KF.processNoiseCov = eye(size(KF.processNoiseCov))*1e-5;\n KF.measurementNoiseCov = eye(size(KF.measurementNoiseCov))*1e-1;\n KF.errorCovPost = eye(size(KF.errorCovPost));\n KF.statePost = randn(size(KF.statePost))*0.1;\n\n % main loop\n while ishghandle(hFig)\n center = [size(img,2) size(img,1)]/2;\n R = size(img,2)/3;\n stateAngle = state(1);\n statePt = calcPoint(center, R, stateAngle);\n\n prediction = KF.predict();\n predictAngle = prediction(1);\n predictPt = calcPoint(center, R, predictAngle);\n\n measurement = randn(size(measurement))*KF.measurementNoiseCov(1);\n\n % generate measurement\n measurement = measurement + KF.measurementMatrix*state;\n\n measAngle = measurement(1);\n measPt = calcPoint(center, R, measAngle);\n\n % plot points\n img(:) = 0;\n img = drawCross(img, statePt, [255 255 255], 3);\n img = drawCross(img, measPt, [255 0 0 0], 3);\n img = drawCross(img, predictPt, [0 255 0], 3);\n img = cv.line(img, statePt, measPt, 'Color',[255 0 0], ...\n 'Thickness',3, 'LineType','AA');\n img = cv.line(img, predictPt, measPt, 'Color',[255 255 0], ...\n 'Thickness',3, 'LineType','AA');\n\n if rand > 0.75\n KF.correct(measurement);\n end\n\n processNoise = randn(size(processNoise))*sqrt(KF.processNoiseCov(1,1));\n state = KF.transitionMatrix*state + processNoise;\n\n % update display\n set(hImg, 'CData',img);\n\n % break of inner loop on any key press\n flag = getappdata(hFig, 'flag');\n if isempty(flag)||flag, break; end\n pause(0.1)\n end\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/kalman_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6481151352623964}} {"text": "function logpdf = logmvtpdf(t,mu,f,Sigma);\n% function logpdf = logmvtpdf(t,mu,f,Sigma);\n% log pdf of multivariate t-student dist.\n% t : D by N\n\n[d,n] = size(t);\n\nc = gammaln((d+f)*0.5) - (d*0.5)*log(f*pi) - gammaln(f*0.5) - 0.5*detln(Sigma);\ndiff = t - repmat(mu,1,n); % d by n\nlogpdf = c - (f+d)*0.5 * log(1 + sum(diff.*(inv(f*Sigma)*diff),1));\n\n% Local Variables: ***\n% mode: matlab ***\n% End: ***\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/vdpgm-2010-06-01/logmvtpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6481151352623964}} {"text": "function [u,v,px,py] = perform_tv_hilbert_projection(f,kernel,lam,options)\n\n% Aujol & Chambolle projection for solving TV-K regularization\n%\n% [u,v,px,py] = perform_tv_hilbert_projection(f,kernel,lam,options);\n%\n% Solve the image separation problem :\n% u = argmin_u |f-u|_K^2 + lam*|u|_TV\n%\n% f = u+v\n% u is the cartoon part.\n% v is the texture part.\n%\n% where |.|_K is an hilber space norm defined by some operator K\n% _K = \n% |f|_K^2 = _K\n%\n% f is the input image.\n% kernel is a callback function of the kernel operator, should be like\n% f = kernel(f, options);\n%\n%\tSet options.use_gabor==1 to setup the Gabor Kernel automatically\n%\tand options.use_gabor==-1 to set up the L2 identity kernel.\n%\n% Original code by Guy Gilboa, modified by Gabriel Peyre\n%\n% Copyright (c) 2006 Gabriel Peyre\n\n[ny,nx]=size(f);\n\noptions.null = 0;\nif isfield(options, 'niter')\n niter = options.niter;\nelse\n niter = 30;\nend\nif isfield(options, 'dt')\n dt = options.dt;\nelse\n dt = 0.01;\nend\nif isfield(options, 'p0x') && ~isempty(options.p0x)\n p0x = options.p0x;\nelse\n p0x=zeros(ny,nx); \nend\nif isfield(options, 'p0y') && ~isempty(options.p0y)\n p0y = options.p0y;\nelse\n p0y=p0x;\nend\n\nuse_gabor = 1;\nif isfield(options, 'use_gabor')\n use_gabor = options.use_gabor;\nend\n\npx=p0x; py=p0y;\nlami=1/lam; % here the algorithm works with inverse of lambda\n\nif use_gabor==1\n sig_k=1; freq=0.25; bias=0;\n n=11; %kernel size\n x=ones(n,1)*(-(n-1)/2:(n-1)/2); y=x';\n gs=exp(-((x/sig_k).^2+(y/sig_k).^2)/2); % 2D gaussian\n gs=gs/sum(sum(gs)); % normalize\n r=sqrt(x.^2+y.^2); cs=cos(2*pi*r*freq); %radially symmetric\n iKx = cs.*gs; %% \"Gabor filter\" for inverse K\n iKx=iKx-mean(mean(iKx)); % zero mean filter\n cp=(n+1)/2; % center of kernel\n iKx(cp,cp) = iKx(cp,cp)-bias;\nelseif use_gabor==-1\n iKx = 1;\nend\n\n\n%% perform iterations\nif use_gabor~=0\n for i=1:niter, %% do niterations\n progressbar(i,niter);\n %% compute projection\n km1div = filter2(iKx,div(px,py))-f*lam;\n %[Gx,Gy] = grad(km1div);\n Gx=gradx(km1div); Gy=grady(km1div);\n aG = sqrt(Gx.^2+Gy.^2); %abs(G)\n px = (px + dt*Gx)./(1+dt*aG);\n py = (py + dt*Gy)./(1+dt*aG);\n end % for i\n v = filter2(iKx,div(px,py))/lam;\nelse\n for i=1:niter, %% do niterations\n progressbar(i,niter);\n % compute projection\n km1div = feval( kernel, div(px,py), options ) - f*lam;\n % compute gradient \n Gx=gradx(km1div); Gy=grady(km1div);\n% [Gx,Gy] = grad(km1div);\n aG = sqrt(Gx.^2+Gy.^2); %abs(G)\n px = (px + dt*Gx)./(1+dt*aG);\n py = (py + dt*Gy)./(1+dt*aG);\n end % for i\n v = lami*feval( kernel, div(px,py), options );\nend\n\nu=f-v;\n\n%% additional functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient (forward difference)\nfunction [fx,fy] = grad(P)\nerror('Should not be used.');\nfx = P(:,[2:end end])-P;\nfy = P([2:end end],:)-P;\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Divergence (backward difference)\nfunction M=div(px,py)\n[m,n]=size(px);\nM=zeros(m,n);\nMx=M; My=M;\nMx(2:m-1,1:n)=px(2:m-1,1:n)-px(1:m-2,1:n);\nMx(1,:)=px(1,:);\nMx(m,:)=-px(m-1,:);\nMy(1:m,2:n-1)=py(1:m,2:n-1)-py(1:m,1:n-2);\nMy(:,1)=py(:,1);\nMy(:,n)=-py(:,n-1);\nM=Mx+My;\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Laplacian (central difference)\nfunction fl = lap(P)\n[gx,gy]=grad(P);\nfl=div(gx,gy);\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient on X (forward difference)\nfunction M=gradx(I)\n[m,n]=size(I);\nM=zeros(m,n);\nM(1:m-1,1:n)=-I(1:m-1,:)+I(2:m,:);\nM(m,1:n)=zeros(1,n);\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Gradient on Y (forward difference)\nfunction M=grady(I)\n[m,n]=size(I);\nM=zeros(m,n);\nM(1:m,1:n-1)=-I(:,1:n-1)+I(:,2:n);\nM(1:m,n)=zeros(m,1);\n\n\n\n", "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_image/perform_tv_hilbert_projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6481123526497857}} {"text": "function [month, day, year] = gdate (jdate)\n\n% convert Julian date to Gregorian (calendar) date\n\n% input\n\n% jdate = julian day\n\n% output\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% note: day may include fractional part\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\njd = jdate;\n\nz = fix(jd + .5);\nfday = jd + .5 - z;\n\nif (fday < 0)\n fday = fday + 1;\n z = z - 1;\nend\n\nif (z < 2299161)\n a = z;\nelse\n alpha = floor((z - 1867216.25) / 36524.25);\n a = z + 1 + alpha - floor(alpha / 4);\nend\n\nb = a + 1524;\nc = fix((b - 122.1) / 365.25);\nd = fix(365.25 * c);\ne = fix((b - d) / 30.6001);\nday = b - d - fix(30.6001 * e) + fday;\n\nif (e < 14)\n month = e - 1;\nelse\n month = e - 13;\nend\n\nif (month > 2)\n year = c - 4716;\nelse\n year = c - 4715;\nend\n\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/novas/gdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6481123399358173}} {"text": "function [var_prc,pci,Nneeded,pcitarget] = var_prctile(p,n_in_sample,varargin)\n% :Usage:\n% ::\n%\n% [var_prc,pci,Nneeded,pcitarget] = var_prctile(p,n_in_sample,['nboot',nboot],['x',data])\n%\n% [var_prc,pci,Nneeded,pcitarget] = var_prctile(p,50,'nboot',5000)\n%\n% :Inputs:\n%\n% **p:**\n% is desired prctile of data (threshold)\n%\n% **nboot:**\n% is number of bootstrap samples (if bootstrapping)\n%\n% **n_in_sample:**\n% is number of obs. in original sample\n%\n% **x:**\n% is data sample of distribution of interest (empirical pdf based on\n% this)\n%\n% Note: using empirical PDF/CDF depends a great deal on choice of h (see\n% code).\n%\n% :Examples:\n% ::\n%\n% Nneeded = [];\n% for p = [.05:-.001:.001]\n% [var_prc,pci,Nneeded(end+1),pcitarget] = var_prctile(x,p);\n% end\n% figure;\n% plot([.05:-.001:.001],Nneeded)\n%\n% ..\n% tor wager, jan 2007\n% ..\n\nnboot = Inf;\nnorm_model = 1;\nx = [];\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n case 'nboot', nboot = varargin{i+1}; % # bootstrap samples\n case {'x','data'}, x = varargin{i+1}; norm_model = 0; % use empirical PDF\n\n otherwise\n error('Unknown string option');\n end\n end\nend\n\n% ------------------------------------------------------------\n% * get PDF\n% ------------------------------------------------------------\n\n\nif norm_model\n % get normal PDF at p-th percentile\n % -------------------------------------------\n prc = norminv(p);\n pdfval = normpdf(prc);\nelse\n % empirical estimate of PDF from x (data)\n % -------------------------------------------\n % prc is x-score at prctile of interest\n prc = prctile(x,100*p);\n\n % now we need pdf at that prctile.\n % pick some unit h, and differentiate around prc\n\n h = max(.01,1000 ./ length(x)); % enough so we have reasonable idea\n h = min(h,p);\n h = max(h,1000 ./ length(x));\n \n pdfval = 0;\n\n while pdfval == 0\n pdfval = emppdf(x,prc,h);\n\n h = h + .01;\n end\nend\n\n\n% ------------------------------------------------------------\n% * get variance\n% ------------------------------------------------------------\n\n%for normal: fit = ( 1./ (normpdf(norminv(p)).^2) ) .* (p *(1-p)./N);\n% from Brown and Wolfe, asymptotic\n%var_prc = ( 1./ (pdfval.^2) ) .* (p *(1-p)./N);\n\n% from Martin's bootstrap book, Ch 19, Eq. 19.7, p. 275\nvar_prc = ( 1./ (pdfval.^2) ) .* (p *(1-p)) .* (1./nboot + 1./n_in_sample);\n\nif nargout < 2, return, end\n\n\n% ------------------------------------------------------------\n% * get confidence interval\n% ------------------------------------------------------------\n\nhalfci_prc = 1.96 .* sqrt(var_prc);\n\n% lower and upper bounds on p-value derived from distribution of x\npci = get_pval_ci(x,prc,halfci_prc);\n\nif nargout < 3, return, end\n\n% now get nboot needed to achieve target\n% ---------------------------------------\n\n% expression for tolerance: if upper bound of p-value is within 10% of p-value\nmaxN = 50000; % maximum number of iterations\nNneeded = 500; % starting estimate for nboot needed (should be fairly low)\nNstep = 500; % increase Nneeded in units of Nstep until satisfied\np_upper_bound = p + .1 * p; % upper bound for p desired; now 10% larger than p\npcitarget = Inf; % target conf. interval for p-values with Nneeded boot samples\n\n% computations we don't have to repeat. Divide by sqrt(N) to get halfci of prc\nhalfci_squared_determiner = 1.96 .* sqrt( ( 1./ (pdfval.^2) ) .* p *(1-p) );\n\nwhile ( max(pcitarget) > p_upper_bound ) && ( Nneeded < maxN )\n\n Nneeded = Nneeded + Nstep;\n halfci_prc = halfci_squared_determiner ./ sqrt(Nneeded);\n pcitarget = get_pval_ci(x,prc,halfci_prc);\n\nend\n\n\n\n\n\nend\n\n\n\nfunction pci = get_pval_ci(x,prc,halfci_prc)\n% get confidence interval for p-value, based on data x, x-axis-value prc,\n% and confidence half-interval for prc\n\nif isempty(x)\n % normal CDF\n pci = [max(0,normcdf(prc - halfci_prc)) min(1,normcdf(prc + halfci_prc))];\nelse\n % empirical CDF\n pci = [max(0,empcdf(x,prc - halfci_prc)) min(1,empcdf(x,prc + halfci_prc))];\nend\n\nend\n\n\n\nfunction pdfval = emppdf(x,prc,h)\n% empirical PDF of data numerically differentiated in a window h\npdfval = ( sum(x <= prc + h) - sum(x <= prc - h) ) ./ (length(x) * 2 * h);\n\nend\n\n\nfunction p = empcdf(x,prc)\n% empirical CDF of data x at prctile prc\n\np = sum(x <= prc) ./ length(x);\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/var_prctile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6480702111499528}} {"text": "function [output, fs] = sp_johansson_impl_n3(inp_fs, input, time_skew)\n% Reconstruction of a signal from non-uniform samples\n% Based on Sindhi and Prabhu's implementation of Johansson's\n% method\n\n% index_mapping is used to reorded filters in case the first input\n% signal is actually delayed comparing to the second and not vice versa\nN = length(time_skew); % number of samplers\nfs = inp_fs * N; % full sampling frequency\n\nT_inp = 1/inp_fs;\n\n% index_mapping is used to reorded filters in case the first input\n% signal is actually delayed comparing to the second and not vice versa\n[time_skew, index_mapping] = sort(time_skew);\nx11 = cell2mat(input')';\nx11 = x11(index_mapping, :);\n\nTQ = 1; % Nyquist sampling period\n\n% Decimation Periods - in our case all ADCs sample with the same rate\nT = [3*TQ 3*TQ 3*TQ];\n\nK = 0.5*lcm(2*T(1), 2*T(2))/TQ; % number of samples in recurrent period\nK = 0.5*lcm(2*K, 2*T(3))/TQ;\ncapT = K*TQ; % the full sampling period - of all samplers\nM = capT./T;\ncapM = lcm(M(1), M(2));\ncapM = lcm(capM, M(3));\nexcess = ceil((K-1)/capM);\n\nmaxf = K/(excess*capM+1);\nK1 = K/maxf;\n\nML = min(cellfun('length', input)); % number of slices\nw_c = 0.85;\n\nLF = capM*2*K1+1; %% min length of LF should be capM*2*K1\nn = -(LF-1)/2:1:(LF-1)/2;\n\ntaus = time_skew / T_inp * capT; % ADC delays in seconds\ntausI = sort([taus(1) taus(2) taus(3)]);\ntauI = zeros(K,ML);\nfor p = 1:K\n tauI(p,:) = tausI(p)+(0:ML-1)*capT;\nend;\n\nr = tausI-TQ*(0:K-1);\nr = r.';\nw_o = w_c*pi*TQ;\nhJ = zeros(K,LF);\nC = zeros(1,LF);\nNt = (LF-1)/2;\nfor i = 1:K\n C = -2*sin(w_o*(n-r(1+(mod(i-1-n,K)))'))./(pi*(n-r(1+(mod(i-1-n,K)))'));\n C(isnan(C))=-2*w_o/pi;\n C = C.';\n S = zeros(LF,LF);\n for k = 1:LF\n S(k,:) = sin(w_o*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')))./(pi*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')));\n end;\n S(isnan(S))=w_o/pi;\n hJ(i,:) = -0.5*S\\C;\nend;\n\nx1 = reshape(x11,1,size(x11,2)*K);\ny1 = zeros(K,length(x1));\nfor j=1:K\n y1(j,:) = filter(hJ(j,:),1,x1);\n y1(j,:) = upsample(downsample(y1(j,:),K,j-1),K)/K;\n y1(j,:) = filter([zeros(1,j-1),1],1,y1(j,:));\nend;\ny = K*0.25*sum(y1,1);\ndelayJ = (size(hJ,2)-1)/2;\ny = real(y(1+delayJ:end));\n\noutput = y;\nend", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/sp_johansson_impl_n3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6480650620005206}} {"text": "%%********************************************************************\n%% minEpts: minimum volume ellipsoid containing given \n%% points, V(:,1),...,V(:,m). \n%%\n%% max log(det(B))\n%% s.t. || Bx + d || <= 1, for all x = V(:,1),...,V(:,m)\n%%\n%% [blk,At,C,b,OPTIONS,B,d] = minEpts(V,solve)\n%% \n%% For problem formulation, see \n%% Vandenberghe, Boyd, Wu, Determinant maximization with linear \n%% matrix inequalities, SIAM J. Matrix Analysis and Applications,\n%% 19 (1998), pp. 499--533.\n%%\n%%********************************************************************\n\n function [blk,At,C,b,OPTIONS,B,d] = minEpts(V,solve)\n\n if (nargin < 2); solve = 0; end; \n%%\n%% form data matrices \n%%\n [p,m] = size(V); N = (p+1)*m; \n blk{1,1} = 's'; blk{1,2} = (p+1)*ones(1,m);\n blk{2,1} = 's'; blk{2,2} = p; \n%%\n count = 0; \n for j = 1:p\n s1 = V(j,:)'; i1 = [j:(p+1):(p+1)*(m-1)+j]; j1 = [p+1:p+1:(p+1)*m];\n tmp = sparse(i1,j1,s1,N,N);\n tmp = tmp + tmp'; \n count = count + 1; \n F{1,count} = -tmp;\n F{2,count} = sparse(j,j,-1,p,p); \n end\n for j = 2:p\n for k = 1:j-1 \n s1 = V(k,:)'; i1 = [j:(p+1):(p+1)*(m-1)+j]; j1 = [p+1:p+1:(p+1)*m]; \n s2 = V(j,:)'; i2 = [k:(p+1):(p+1)*(m-1)+k]; j2 = [p+1:p+1:(p+1)*m]; \n tmp = sparse(i1,j1,s1,N,N); \n tmp = tmp + sparse(i2,j2,s2,N,N);\n tmp = tmp + tmp'; \n count = count + 1; \n F{1,count} = -tmp; \n F{2,count} = sparse([j k],[k j],[-1 -1],p,p); \n end\n end\n for j = 1:p\n s1 = ones(m,1); \n i1 = [j:(p+1):(p+1)*(m-1)+j]; j1 = [p+1:p+1:(p+1)*m];\n tmp = sparse(i1,j1,s1,N,N); \n tmp = tmp + tmp'; \n count = count + 1; \n F{1,count} = -tmp;\n F{2,count} = sparse(p,p); \n end \n At = svec(blk,F,ones(2,1));\n C{1,1} = speye(N); \n C{2,1} = zeros(p); \n b = zeros(p*(p+1)/2+p,1); \n parbarrier{1,1} = 0;\n parbarrier{2,1} = 1; \n OPTIONS.parbarrier = parbarrier; \n%%\n%% || Bx + d || <= 1. \n%% x'*(B'*B)*x + 2(B'*d)'*x + d'*d <= 1.\n%%\n if (solve) \n [obj,X,y,Z,info] = sqlp(blk,At,C,b,OPTIONS);\n if (length(y) ~= p*(p+3)/2)\n error('length of y not compatible with p'); \n end\n B = diag(y(1:p));\n tmp = p; \n for k = 1:p-1\n B(k+1:p,k) = y(tmp + [1:p-k]);\n B(k,k+1:p) = B(k+1:p,k)';\n tmp = tmp + p-k;\n end; \n d = y(tmp+1:length(y)); \n else \n B = []; d = []; \n end \n%%********************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Examples/minEpts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6480650599227022}} {"text": "% Computes gain using the covariance matrix.\n% Copyrights Farhat Masood (NUST) Pakistan\n\n\n\nfunction [k,s] = kfilter(A,C,V1,V2,V12)%function [k,s] = kfilter(A,C,V1,V2,V12)%KFILTER can have arguments: (A,C,V1,V2) if there are no cross% products, V12=0.% KFILTER calculates the kalman gain, k, and the stationary% covariance matrix, s, using the Kalman filter for:% %\t\tx[t+1] = Ax[t] + Bu[t] + w1[t+1]% y[t] = Cx[t] + Du[t] + w2[t]%% E [w1(t+1)] [w1(t+1)]' = [V1 V12;% [ w2(t) ] [ w2(t) ] V12' V2 ]%% where x is the mx1 vector of states, u is the nx1 vector of controls, y is% the px1 vector of observables, A is mxm, B is mxn, C is pxm, V1 is mxm,% V2 is pxp, V12 is mxp.%m=max(size(A));[rc,cc]=size(C);if nargin==4; V12=zeros(m,rc); end;if (rank(V2)==rc); A=A-(V12/V2)*C; V1=V1-V12*(V2\\V12'); [k,s]=doubleo(A,C,V1,V2); k=k+(V12/V2);else; s0=.01*eye(m); dd=1; it=1; maxit=1000; while (dd>1e-8 & it<=maxit); k0= (A*s0*C'+V12)/(V2+C*s0*C'); s1= A*s0*A' + V1 -(A*s0*C'+V12)*k0'; k1= (A*s1*C'+V12)/(V2+C*s1*C'); dd=max(max(abs(k1-k0))); it=it+1; s0=s1; end; k=k1;s=s0; if it>=maxit; disp('WARNING: Iteration limit of 1000 reached in KFILTER.M'); end;end;\u001a", "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/24486-kalman-filter-in-matlab-tutorial/Kalman Filter/kalmanf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.6480650484691202}} {"text": "function fourthorder\n%% \n% laplace^2 u = f; [0,1]^2\n% u = g_D; \n% Du\\cdot n = g_N. \n%\n%more information , you can check fourorderdata.m,biharmonicP1.m,biharmonicP2.m\n%biharmonicP3.m.\n% Created by Jie Zhou.\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\nclose all\n%% Parameters\n%maxN = 2e3; theta = 0.5; \nmaxIt = 6; \nN = zeros(maxIt,1); errL2 = zeros(maxIt,1); errH1 = zeros(maxIt,1);\n\n%% Generate an initial mesh\nnode = [0,0; 0,1; 1,0;1,1]; % nodes\nelem = [1,3,2; 4,2,3]; % elements\nelem = label(node,elem); % label the mesh\nbdEdge = setboundary(node,elem,'Dirichlet'); % Dirichlet boundary condition\n\n \n% showmesh(node,elem); % plot mesh \n% findelem(node,elem,'all','index','color','g'); % plot element indices\n% findnode(node,'all','index','color','r'); % plot node indices\n\n\n%% Get a fine mesh by uniform bisection\nfor k = 1:2\n [node,elem,bdEdge] = uniformbisect(node,elem,bdEdge); \n% [node,elem,bdEdge] = bisect(node,elem,'all',bdEdge);\nend\n\nshowmesh(node,elem);\nfindnode(node,'all','index','color','r');\nfindelem(node,elem,'all','index','color','r');\n\n%% Set up PDE data\npde = fourorderdata;\n\n\n%% Adaptive Finite Element Method\n% *SOLVE* -> *ESTIMATE* -> *MARK* -> *REFINE*\n for k = 1:maxIt\n% [w,u] = biharmonicP1(node,elem,pde,bdEdge);\n [w,u] = biharmonicP2(node,elem,pde,bdEdge);\n% [w,u] = biharmonicP3(node,elem,pde,bdEdge);\n errL2(k) = getL2error(node,elem,pde.exactu,u);\n errH1(k) = getH1error(node,elem,pde.Du,u);\n N(k) = size(w,1)+size(u,1);\n [node,elem,bdEdge] = uniformbisect(node,elem,bdEdge);\n end\n\n% Plot convergence rates\nN= N(1:k); errH1 = errH1(1:k); errL2 = errL2(1:k); \nfigure;\nshowrate2(N,errH1,3,'-*','||Du-Du_h||',...\n N,errL2,3,'k-+','||u-u_h||');\n\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/iFEM/example/2D/biharmonicMixedFEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6480384588226027}} {"text": "function fe2d_r_fast_test ( )\n\n%*****************************************************************************80\n%\n%% FE2D_R_FAST_TEST tests the FE2D_R_FAST code.\n%\n% Discussion:\n%\n% This function sets all parameter values and initial condition information\n% necessary to execute the \"fast\" version of the fe2d_r algorithm.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 28 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Reference:\n%\n% Marcus R Garvie, John Burkardt, Jeff Morgan,\n% Simple Finite Element Methods for Approximating Predator-Prey Dynamics\n% in Two Dimensions using MATLAB,\n% Submitted to Bulletin of Mathematical Biology, 2014.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2D_R_FAST_TEST:\\n' );\n fprintf ( 1, ' Test the FE2D_R_FAST function\\n' );\n fprintf ( 1, ' which applies Robin boundary conditions as it\\n' );\n fprintf ( 1, ' approximates a solution to a predator-prey system.\\n' );\n%\n% Set the parameters.\n%\n alpha = 0.4;\n beta = 2.0;\n gamma = 0.6;\n delta = 1.0;\n%\n% Use T=150.0 for normal run.\n% Use T=0.50 for a \"quick\" run that might take 15 minutes of computing.\n%\n% T = 150.0;\n T = 0.50;\n delt = 1.0 / 384.0;\n k1 = 0.01;\n k2 = 0.01;\n\n t = tic;\n fe2d_r_fast ( alpha, beta, gamma, delta, T, delt, @u0f, @v0f, k1, k2 );\n t = toc ( t );\n\n fprintf ( 1, ' Execution took %10.2g minutes \\n', t / 60.0 );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2D_R_FAST_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n\nfunction value = u0f ( x, y )\n\n%*****************************************************************************80\n%\n%% U0F evaluates the initial condition for U.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for U at (X,Y).\n%\n value = 6.0 / 35.0 - 2.0E-07 * ( x - 0.1 * y - 225.0 ) * ( x - 0.1 * y - 675.0 );\n\n return\nend\n\nfunction value = v0f ( x, y )\n\n%*****************************************************************************80\n%\n%% V0F evaluates the initial condition for V.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for V at (X,Y).\n%\n value = 116.0 / 245.0 - 3.0E-05 * ( x - 450.0 ) - 1.2E-04 * ( y - 150.0 );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fe2d_predator_prey_fast/fe2d_r_fast_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.6480384520081969}} {"text": "function [W,Idx] = barycentricWeights(X,xBnd,N)\n% [W,Idx] = barycentricWeights(X,xBnd,N)\n%\n% This function computes the weights and indicies such that\n%\n% INPUTS:\n% X = [d , n] = n points of interest, each is d-dimensional\n% xBnd = [d , 2] = [min,max] along each dimension\n% N = [1, d] = number of grid points along each dimension\n%\n% OUTPUTS:\n% W = [d+1, n] weight to apply to each index\n% Idx = [d+1, n] linear index corresponding to each weight\n%\n% NOTES:\n% --> y = f(x), where x is d-dimensional, and y is scalar\n% --> Y = Y(x1,x2,...,xd)\n% --> n = size(Y);\n% --> y(X(:,i)) = dot(W(:,i)*Y(Idx(:,i));\n%\n% ASSUME:\n% --> all data is uniformly spaced:\n% {xi} = linspace(xBnd(i,1), xBnd(i,2), n(i));\n%\n% REFERENCE:\n% \n% Based on paper: \"Multidimensional Triangulation and Interpolation for\n% Reinforcement Learning\" by Scott Davies, NIPS 1996\n%\n% See Also: barycentricInterpolate\n\n[d, n] = size(X);\nW = zeros(d+1,n);\nIdx = zeros(d+1,n);\nfor i=1:n\n [W(:,i),Idx(:,i)] = barycentricWeightsCore(X(:,i),xBnd,N);\nend\n\nend\n\nfunction [w,idx] = barycentricWeightsCore(x,xBnd,N)\n% [w,idx] = barycentricWeights(x,xBnd,n)\n%\n% This function computes the weights and indicies such that y = Y(idx)*w,\n% where Y is some data, stored on a length(N) dimensional grid.\n%\n% INPUTS:\n% x = [d , 1] point of interest\n% xBnd = [d , 2] = [min,max] along each dimension\n% N = [1, d] = number of grid points along each dimension\n%\n% OUTPUTS:\n% w = [d+1,1] weight to apply to each index\n% idx = [d+1,1] linear index corresponding to each weight\n%\n% NOTES:\n% --> y = f(x), where x is d-dimensional, and y is scalar\n% --> Y = Y(x1,x2,...,xd)\n% --> n = size(Y);\n% --> y = dot(Y(idx),w);\n%\n% ASSUME:\n% --> all data is uniformly spaced:\n% {xi} = linspace(xBnd(i,1), xBnd(i,2), n(i));\n%\n% REFERENCE:\n% \n% Based on paper: \"Multidimensional Triangulation and Interpolation for\n% Reinforcement Learning\" by Scott Davies, NIPS 1996\n\n% Coerce any data that is out of range:\ncheckLow = xxBnd(:,2); x(checkUpp) = xBnd(checkUpp,2);\n\n% Translate and scale such that each grid cell is a unit cube:\nx = x-xBnd(:,1);\nx = x./(xBnd(:,2)- xBnd(:,1));\nx = x.*(N-1);\n\n% Seperate out into bin number and fractional length:\nxBaseIdx = floor(x); %Figure out the lower index (bin) number\ncheckCeil = xBaseIdx==(N-1); newCeil = N-2;\nxBaseIdx(checkCeil) = newCeil(checkCeil); %Fix special case for points on upper grid\nx = x-xBaseIdx; %Keep the fraction along each dimension:\n\n% Figure out which dimensions to build simplex along:\n[~,I] = sort(x); %x must be a column vector!\n\n% Build simplex by walking along each successive dimension\n% The matrix X stores the verticies of the simplex, where each vertex is on\n% the unit hypercube. The first vertex is always zeros(n,1) and the last is\n% always ones(n,1). The intermediate verticies are selected based on the\n% sort step. Since X will be triangular, and all entries are unity, it is\n% trivial to solve the system: x = X*w for the unknown weights w by row\n% reduction.\nn = length(N);\nX = zeros(n,n+1);\nw = zeros(n+1,1);\nwSum = 0;\nfor i=1:n\n X(I(i), (n+2-i):(n+1)) = 1;\n w(n+2-i) = x(I(i)) - wSum;\n wSum = wSum + w(n+2-i);\nend\nw(1) = 1-wSum; %Final convex combination\n\n% Compute the linear indices:\nidx = zeros(n+1,1);\nfor i=1:(n+1)\n idx(i) = sub2idx(N, X(:,i)+xBaseIdx+1, n);\nend\n\nend\n\n\n%%%% Custom version of sub2ind, that takes a vector input for the desired\n%%%% input dimension, rather than a comma seperated list.\nfunction idx = sub2idx(n,idxVec,d)\n%\n% Based on Matlab's sub2ind command\n% Modified by Matthew Kelly, April 8, 2015\n%\n% CHANGES:\n% - must explicitly enter all dimensions: length(n) == length(idxVec)\n% - pass through for scalar: length(n)==1 is valid input\n% - must pass desired subscripts as a vector (not a comma-seperated-list)\n% - disabled most error checking\n%\n% INPUTS:\n% n = size(dataMatrix)\n% idxVec = list of desired indices. For example A(2,1) -> [2,1]\n%\n% OUTPUTS:\n% idx = linear index, such that:\n%\n% A(idx) = A(idxVec(1), ... , idxVec(length(n));\n%\n\nif d == 1\n idx = idxVec;\nelseif d ==2\n idx = idxVec(1) + (idxVec(2) - 1).*n(1);\nelse\n %Compute linear indices\n k = [1 cumprod(n(1:end-1))'];\n idx = 1;\n for i = 1:d\n v = idxVec(i);\n idx = idx + (v-1)*k(i);\n end\nend\n\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/MDP_Pendulum/barycentricWeights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914788, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6480384462897106}} {"text": "function [Xhat] = aprxMAPGMM(Y,patchSize,noiseSD,imsize,GS,excludeList,SigmaNoise)\n% approximate GMM MAP estimation - a single iteration of the \"hard version\"\n% EM MAP procedure (see paper for a reference)\n%\n% Inputs:\n% Y - the noisy patches (in columns)\n% noiseSD - noise standard deviation\n% imsize - size of the original image (not used in this case, but may be\n% used for non local priors)\n% GS - the gaussian mixture model structure\n% excludeList - used only for inpainting, misleading name - it's a list\n% of patch indices to use for estimation, the rest are just ignored\n% SigmaNoise - if the noise is non-white, this is the noise covariance\n% matrix\n%\n% Outputs:\n% Xhat - the restore patches\n\n\n% handle exclusion list - used for inpainting\nif ~exist('excludeList','var')\n excludeList = [];\nend\n\n% Supports general noise covariance matrices\nif (~exist('SigmaNoise','var'))\n SigmaNoise = noiseSD^2*eye(patchSize^2);\nend\n\nif ~isempty(excludeList)\n T = Y;\n Y = Y(:,excludeList);\nend\n\n% remove DC component\nmeanY = mean(Y);\nY = bsxfun(@minus,Y,meanY);\n\n% calculate assignment probabilities for each mixture component for all\n% patches\nGS2 = GS;\nPYZ = zeros(GS.nmodels,size(Y,2));\nfor i=1:GS.nmodels\n GS2.covs(:,:,i) = GS.covs(:,:,i) + SigmaNoise;\n PYZ(i,:) = log(GS.mixweights(i)) + loggausspdf2(Y,GS2.covs(:,:,i));\nend\n\n% find the most likely component for each patch\n[~,ks] = max(PYZ);\n\n% and now perform weiner filtering\nXhat = zeros(size(Y));\nfor i=1:GS.nmodels\n inds = find(ks==i);\n Xhat(:,inds) = ((GS.covs(:,:,i)+SigmaNoise)\\(GS.covs(:,:,i)*Y(:,inds) + SigmaNoise*repmat(GS.means(:,i),1,length(inds))));\nend\n\n% handle exclusion list stuff (inpainting only)\nif ~isempty(excludeList)\n tt = T;\n tt(:,excludeList) = bsxfun(@plus,Xhat,meanY);\n Xhat = tt;\nelse\n Xhat = bsxfun(@plus,Xhat,meanY);\nend\n \n \n", "meta": {"author": "lbasek", "repo": "image-denoising-benchmark", "sha": "9d753198d715b7628c8e7d9259dfa5c219d033ea", "save_path": "github-repos/MATLAB/lbasek-image-denoising-benchmark", "path": "github-repos/MATLAB/lbasek-image-denoising-benchmark/image-denoising-benchmark-9d753198d715b7628c8e7d9259dfa5c219d033ea/algoritms/matlab/EPLL/extra/aprxMAPGMM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6479054818012896}} {"text": "function err = getHdiverrorBDM1(node,elem,divSigma,sigmah,markedElem)\n%% GETHDIVERRORBDM1 Hdiv norm of the approximation error for BDM1.\n%\n% The input divSigma is a function bundle, and sigma_h is a vector array \n% whose component including two parts, the first part (i.e., sigmah(1:NE)) \n% is the line integral of flux in norm direction, i.e. \n% sigmah_i = \\int_{e_i} sigma\\cdot n.\n% the second part (i.e., sigmah(NE+1:2*NE)) is the dual basis written as \n% sigmah_i = 3\\int_{e_i} (\\lambda1-\\lambda2) sigma\\cdot n (ei = < 1 , 2 >)\n%\n% err = getHdiverrorBDM1(node,elem,divSigma,sigmah)\n%\n% Example\n%\n% maxIt = 5;\n% node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n% elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % elements\n% bdEdge = setboundary(node,elem,'Dirichlet');\n% pde = mixBCdata;\n% err = zeros(maxIt,1); N = zeros(maxIt,1);\n% for i =1:maxIt\n% [node,elem,bdEdge] = uniformrefine(node,elem,bdEdge);\n% [u,sigma,NULL] = PoissonBDM1(node,elem,pde,bdEdge);\n% err(i) = getHdiverrorBDM1(node,elem,pde.f,-sigma,[]);\n% N(i) = size(u,1);\n% end\n% r1 = showrate(N,err,2);\n% legend('||\\sigma - \\sigma_h||_{H(div)}',['N^{' num2str(r1) '}'],...\n% 'LOCATION','Best');\n%\n% See also getHdiverror3RT0, getL2errorRT0.\n%\n% Created by Ming Wang at Jan 17, 2011, M-lint modified at May 15, 2011.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%% Construct Data Structure\n[elem2dof,~,elem2edgeSign] = dofedge(elem);\nNT = size(elem,1);\n% compute div phi\n[Dlambda,area] = gradbasis(node,elem); \n% div phi = 2*(Dlambda_i,Rot_j);\nrotMat = [0 -1; 1 0]; % rotation matrix for computing rotLambda.\ndivPhi(:,3) = 2*dot(Dlambda(:,:,1),Dlambda(:,:,2)*rotMat,2);\ndivPhi(:,1) = 2*dot(Dlambda(:,:,2),Dlambda(:,:,3)*rotMat,2);\ndivPhi(:,2) = 2*dot(Dlambda(:,:,3),Dlambda(:,:,1)*rotMat,2);\ndivSigmahp = zeros(NT,1);\nfor k = 1:3\n divSigmahp = divSigmahp + elem2edgeSign(:,k).*sigmah(elem2dof(:,k)).*divPhi(:,k);\nend\n\n%% compute Hdiv error element-wise\n[lambda,w] = quadpts(2);\nnQuad = size(lambda,1);\nerr = zeros(NT,1);\nfor p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n divSigmap = divSigma(pxy);\n % compute divSigmahp at quadrature points\n err = err + w(p)*sum((divSigmap - divSigmahp).^2,2);\nend\nerr = err.*area;\n% modify the error\nerr(isnan(err)) = 0; % remove the singular part\nif (nargin == 5) && ~isempty(markedElem)\n err = err(markedElem); % error on some marked region\nend\nerr = sqrt(sum(err));\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getHdiverrorBDM1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6478875668253554}} {"text": "%DTRANSFORM Distance transform\n%\n% DT = DTRANSFORM(IM, OPTIONS) is the distance transform of the \n% binary image IM. The value of each output pixel is the distance (pixels)\n% to the closest set pixel.\n%\n% Options::\n% 'Euclidean' use Euclidean distance (default)\n% 'cityblock' use cityblock (Manhattan) distance\n% 'show',T display the evolving distance transform, with a delay of T\n% seconds between frames\n%\n% See also IMORPH, DISTANCEXFORM, DXform.\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nfunction d = dtransform(world, varargin)\n\n opt.metric = {'Euclidean', 'cityblock'};\n opt.show = [];\n\n [opt,args] = tb_optparse(opt, varargin);\n if length(args) > 0 && isnumeric(args{1})\n opt.show = args{1};\n end\n\n if strcmpi(opt.metric, 'cityblock')\n m = ones(3,3);\n m(2,2) = 0;\n elseif strcmpi(opt.metric, 'Euclidean')\n r2 = sqrt(2);\n m = [r2 1 r2; 1 0 1; r2 1 r2];\n end\n\n world(world==0) = Inf;\n world(world==1) = 0;\n\n count = 0;\n while 1\n world = imorph(world, m, 'plusmin');\n count = count+1;\n if opt.show\n cmap = gray(256);\n cmap = [1 0 0; cmap];\n colormap(cmap)\n image(world+1, 'CDataMapping', 'direct');\n set(gca, 'Ydir', 'normal');\n xlabel('x');\n ylabel('y');\n pause(opt.show);\n end\n\n if length(find(world(:)==Inf)) == 0\n break;\n end\n end\n\n if opt.show\n fprintf('%d iterations\\n', count);\n end\n\n d = world;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/dtransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6478284646567524}} {"text": "function m = hlp_minor(X, row, col)\n%\n% calculate the ijth minor of matrix X by returning the determinant of X\n% after removing the ith row and jth column\n%\n% Input: \n%\n% X: 2- or 3-dimensional matrix\n% row,col to remove\n%\n% output: \n%\n% m: if X is 2-D, m = minor(X)\n% if X is 3-D, m(i) = minor(X(:,:,i))\n%\n%\n% References:\n%\n% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):\n% Theoretical Handbook and User Manual.\n% Available at: http://www.sccn.ucsd.edu/wiki/Sift/\n% \n% \n% Author: Tim Mullen Dec 1st, 2010, SCCN/INC, UCSD. \n% Email: tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\nnd = ndims(X);\nif nd < 2 || nd > 3\n error('X must have 2 or 3 dimensions');\nend\n\nX(row,:,:) = [];\nX(:,col,:) = [];\n\nif nd==2\n m = det(X);\nelse\n m=zeros(size(X,3),1);\n for k=1:size(X,3)\n m(k) = det(X(:,:,k));\n end \nend\n\n \n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/hlp/hlp_minor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6478284605623839}} {"text": "function y = sigmoid(y, fac)\n% SIGMOID nonlinear funcion for cochlear model\n%\ty = sigmoid(y, fac);\n%\tfac: non-linear factor\n%\t -- fac > 0, transister-like function\n%\t -- fac = 0, hard-limiter\n%\t -- fac = -1, half-wave rectifier\n%\t -- else, no operation, i.e., linear \n%\n%\tSIGMOID is a monotonic increasing function which simulates \n%\thair cell nonlinearity. \n%\tSee also: WAV2AUD, AUD2WAV\n \n% Auther: Powen Ru (powen@isr.umd.edu), NSL, UMD\n% v1.00: 01-Jun-97\n\nif fac > 0,\n\t%y = exp(y/fac); y = 1/(1+.1)-1./(1+.1*y);\n\ty = exp(-y/fac); y = 1./(1+y);\nelseif fac == 0,\n\ty = (y > 0);\t% hard-limiter\nelseif fac == -1,\n\ty = max(y, 0);\t% half-wave rectifier\nelseif fac == -3,\n\ty = halfregu(y);\nend;\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/refVAD/vad-master/mfiles/sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6478141405237632}} {"text": "% INTERNAL FUNCTION: Prediction step for Kalman filter\n% \n% ::\n% \n% [a,P,Tt,Rt,Record]=prediction_step(T,R,att,Ptt)\n% [a,P,Tt,Rt,Record]=prediction_step(T,R,att,Ptt,MUt,OMGt,DPHI,DT,Record,ExpandedFlag)\n% \n% Args:\n% \n% - **T** [matrix] : m x m state matrix (autoregressive part)\n% - **R** [matrix] : m x n state matrix (shock impacts)\n% - **att** [vector] : m x 1 state update\n% - **Ptt** [matrix] : m x m covariance matrix of state update\n% - **MUt** [matrix] : k x l matrix with forward information to match\n% - **OMGt** [matrix|{[]}] : kl x kl covariance matrix of forward\n% information\n% - **DPHI** [matrix] : Matrix representing the restrictions on future\n% shocks\n% - **DT** [matrix] : Convoluted impact of initial conditions\n% - **Record** [] : Holder of invariant information\n% - **ExpandedFlag** [true|false] : if true, returns the expanded state\n% vector including the future shocks. If false, returns only the\n% endogenous variables\n% \n% Returns:\n% :\n% \n% - **a** [vector] : m x 1 or mm x 1 vector of predictions\n% - **P** [matrix] : m x m or mm x mm covariance of predictions\n% - **Tt** [matrix] : m x m or mm x mm time-varying matrix, modifying the\n% impact of lagged endogenous (T)\n% - **Rt** [] : m x n or mm x nn matrix of impact of shocks\n% - **Record** [] : Holder of invariant information\n% \n%", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/m/+utils/+filtering/prediction_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6478141355239855}} {"text": "function [ basis, filt_sig, param ] = gsp_eigenspace_estimation( G, k, param )\n%GSP_EIGENSPACE_ESTIMATION Estimation of first eigenvectors of any graph Laplacian\n% Usage: basis = gsp_eigenspace_estimation(G,k);\n% [basis, approx_U, param] = gsp_eigenspace_estimation(G,k,param);\n%\n% Input parameters :\n% G : Graph structure.\n% k : Dimension of the subspace.\n% param : Optional parameters\n% Output parameters:\n% basis : Approximated basis of k first eigenvectors\n% filt_sig : Filtered random signal\n% param : Optional parameters (with new entries)\n%\n% 'gsp_eigenspace_estimation(G,k)' computes an estimation of the first \n% $k$ eigenvectors of the Laplacian of G using Gaussian random signal\n% filtering, following the FEARS method described in paratte2017fast.\n%\n%\n% Example:::\n%\n% G = gsp_sensor(256);\n% G = gsp_estimate_lmax(G);\n% k = 8;\n% param.order = 100;\n% Uk_est = gsp_eigenspace_estimation(G, k, param);\n% G = gsp_compute_fourier_basis(G);\n% proj_energy = norm(Uk_est' * G.U(:, 1:k), 'fro');\n% \n%\n% Additional parameters\n% ---------------------\n% \n% * *param.filter* : Select the filter to be used for the computation. \n% * 'lp-ch' : Chebyshev polynomial approximation\n% * 'lp-jch' : Jackson-Chebyshev polynomial approximation\n% * 'expwin' : Exponentially decreasing polynomial approximation Default: 'lp-jch'\n% * *param.order* : Degree of the polynomial approximation (default=50).\n% * *param.lk_est_method* : Select the version of lk estimation.\n% * 'fast' : Accelerated method using local uniformity assumption\n% * 'std' : Usual method using dichotomy all the time Default: 'fast'\n% * *param.R* : Random matrix to use (of size N > d, d >= k)\n% (default: Gaussian(0, 1/k) of size Nxk)\n% * *param.pcoef* : Polynomial coefficients if already known.\n% * *param.lk* : Estimated value of lambda_k if already known.\n% * *param.verbose* : Verbosity level (0 no log - 1 display warnings) (default 1). \n%\n% \n% References: paratte2016fast\n%\n\n% Author: Johan Paratte, Lionel Martin\n% Date: 3 November 2016\n\nif nargin < 3, param = struct; end\nif ~isfield(param, 'filter'), param.filter = 'lp-jch'; end\nif ~isfield(param, 'order'), param.order = 50; end\nif ~isfield(param, 'lk_est_method'), param.lk_est_method = 'fast'; end\nif ~isfield(param, 'R'), param.R = randn(G.N, k)/sqrt(k); end\nif ~isfield(param, 'verbose'), param.verbose = 1; end\n\nassert(size(param.R, 1) == G.N && size(param.R, 2) >= k, 'The optional parameter R has wrong size.');\n\nif ~isfield(param, 'pcoefs')\n if param.verbose, disp('Polynomial filtering required. Computing polynomial coefficients...'); end\n\n if ~isfield(G, 'lmax')\n G = gsp_estimate_lmax(G);\n warning(['GSP_EIGENSPACE_ESTIMATION: The variable lmax is not available.', ...\n 'The function will compute it for you. However, if you apply ', ...\n 'many time this function, you should precompute it using the ', ...\n 'function: gsp_estimate_lmax.']);\n end\n\n if ~isfield(param, 'lk')\n if param.verbose, fprintf('Estimation of lambda_k');\n end\n\n tic;\n switch param.lk_est_method\n case 'fast'\n [param.lk, info] = gsp_fast_estimate_lk(G, k, param);\n if param.verbose, disp('using our accelerated method.'); end\n\n case 'std'\n [~, param.lk, ~, ~, nb_iter_lk, k_est_lk] = gsp_estimate_lk(G, k, param);\n if param.verbose, disp('using the standard method.'); end\n\n otherwise\n error('Unknown method for lk_est_method.');\n end\n t = toc;\n\n if param.verbose\n fprintf(['* Estimated lk: %d\\n', ...\n '* Time to estimate lk: %f sec\\n', ...\n '* in %d iterations with k_est=%d (target=%d)\\n'], ...\n param.lk, t, mean(info.calls), mean(info.k_est), k);\n end\n else\n warning('lambda_k was provided to the method from param.');\n end\n\n tic;\n switch param.filter\n case 'lp-ch'\n [param.pcoefs, ~] = jackson_cheby_poly_coefficients(0, param.lk, [0, G.lmax], param.order);\n\n case 'lp-jch'\n [~, param.pcoefs] = jackson_cheby_poly_coefficients(0, param.lk, [0, G.lmax], param.order);\n\n case 'expwin'\n ew = gsp_design_expwin(G, param.lk/G.lmax);\n param.pcoefs = gsp_cheby_coeff(G, ew, param.order);\n\n otherwise\n error('Unknown filter type!'); \n end\n\n t = toc;\n if param.verbose, fprintf('* Time to compute polynomial coefficients: %f sec.\\n', t); end\n\nelse\n if param.verbose, warning('pcoef was provided to the method from param.'); end\nend\n\nif param.verbose, disp('Filtering random signals...'); end\ntic;\nfilt_sig = gsp_cheby_op(G, param.pcoefs, param.R);\nt = toc;\nif param.verbose, fprintf('* Time to filter random signals: %f sec.\\n', t); end\n\nif param.verbose, disp('Computing the SVD for eigenspace recovery...'); end\ntic;\n[basis, ~, ~] = svd(filt_sig, 'econ');\nt = toc;\nif param.verbose, fprintf('* Time to compute SVD: %f sec.\\n', t); end\n\nend\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/embedding/gsp_eigenspace_estimation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6478075323848438}} {"text": "function [G, cliques, fill_ins] = triangulate(G, order)\n% TRIANGULATE Ensure G is triangulated (chordal), i.e., every cycle of length > 3 has a chord.\n% [G, cliques, fill_ins, cliques_containing_node] = triangulate(G, order)\n% \n% cliques{i} is the i'th maximal complete subgraph of the triangulated graph.\n% fill_ins(i,j) = 1 iff we add a fill-in arc between i and j.\n%\n% To find the maximal cliques, we save each induced cluster (created by adding connecting\n% neighbors) that is not a subset of any previously saved cluster. (A cluster is a complete,\n% but not necessarily maximal, set of nodes.)\n\nMG = G;\nn = length(G);\neliminated = zeros(1,n);\ncliques = {};\nfor i=1:n\n u = order(i);\n U = find(~eliminated); % uneliminated\n nodes = myintersect(neighbors(G,u), U); % look up neighbors in the partially filled-in graph\n nodes = myunion(nodes, u); % the clique will always contain at least u\n G(nodes,nodes) = 1; % make them all connected to each other\n G = setdiag(G,0); \n eliminated(u) = 1;\n \n exclude = 0;\n for c=1:length(cliques)\n if mysubset(nodes,cliques{c}) % not maximal\n exclude = 1;\n break;\n end\n end\n if ~exclude\n cnum = length(cliques)+1;\n cliques{cnum} = nodes;\n end\nend\n\nfill_ins = sparse(triu(max(0, G - MG), 1));\n\n%assert(check_triangulated(G)); % takes 72% of the time!\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/graph/triangulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.647743100847609}} {"text": "function r = bisect_characteristic ( x0, theta, characteristic )\n\n%*****************************************************************************80\n%\n%% BISECT_CHARACTERISTIC: characteristic function transition surface.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X0(M,1), the coordinates of the base point inside the surface.\n%\n% Input, real THETA, the coordinates of a direction from the base point.\n%\n% Input, real y = CHARACTERISTIC ( m, n, x ), the handle for a function which\n% evaluates the characteristic for the object at N M-dimensional points X,\n% returning a 1 for points inside the object, and 0 for points outside.\n%\n% Output, real R, the distance from X0 to the surface in direction THETA.\n%\n\n x0 = x0(:);\n\n m = length ( x0 );\n n = 1;\n%\n% Initially, X1 = X0, and so Y1 should be 1.\n%\n x1(1:m,1) = x0(1:m,1);\n y1 = characteristic ( m, n, x1 );\n%\n% Seek an exterior point.\n%\n x2 = exterior_point_characteristic ( m, x0, theta, characteristic );\n%\n% Carry out the bisection search in the interval [X1,X2].\n%\n it_num = 0;\n\n while ( 1.0E-3 < sqrt ( norm ( x2 - x1 ) ) )\n \n x3 = ( x1 + x2 ) / 2.0;\n y3 = characteristic ( m, n, x3 );\n \n if ( y3 == 0 )\n x2 = x3;\n else\n x1 = x3;\n end\n\n it_num = it_num + 1;\n\n if ( 1000 < it_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BISECT_CHARACTERISTIC - Fatal error!\\n' );\n fprintf ( 1, ' Too many iterations.\\n' );\n error ( 'BISECT_CHARACTERISTIC - Fatal error!' )\n end\n \n end\n%\n% Measure the distance from X0 to the transition.\n% We estimate the transition to occur at the average of X1 and X2.\n%\n x3 = ( x1 + x2 ) / 2.0;\n r = norm ( x3 - x0 );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hypersphere_surface/bisect_characteristic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6477430943855192}} {"text": "\n% funSimLogNormProbCov returns SINR-based k-coverage probability \n% under log-normal shadowing based on repeated simulations of\n% of model outlined in [1]\n%\n% simPCovk=funSimLogNormProbCov(tValues,betaConst,K,lambda,sigma,W,diskRadius,simNumb,k)\n% simPCovk is the k-coverage probability\n% tValues are the SINR threshold values. tValues can be a vector\n% betaConst is the pathloss exponent.\n% K = path-loss constant\n% lambda = density of base station/nodes of cellular network\n% sigma = standard deviation of log-normal shadowing (not in dB)\n% W = noise constant\n% diskRadius = radius of simulation region (Warning: if too small, edge\n% effects will not be sufficiently included and disagreement with analytic\n% results may occurr)\n% simNumb = number of simulations\n% k = coverage number (often set to one)\n% All input values (except tValues) are scalars\n%\n% Author: H.P. Keeler, Inria Paris/ENS, 2013\n%\n% References\n% [1] H.P. Keeler, B. Błaszczyszyn and M. Karray,\n% 'SINR-based k-coverage probability in cellular networks with arbitrary\n% shadowing', accepted at ISIT, 2013 \n\n\n\nfunction simPCovk=funSimLogNormProbCov(tValues,betaConst,K,lambda,sigma,W,diskRadius,simNumb,k)\n\nif nargin==8\n k=1;\nend\n\ntNumb=length(tValues);\n\n%%% Simulation Section %%%\n%(uniformly) randomly places nodes on a disk of radius diskRadius\ndiskArea=pi*diskRadius^2;\ncoveredNumbk=zeros(size(tValues));\nESTwoBeta=exp(sigma^2*(2-betaConst)/betaConst^2);\n%rescale lambda - see foot note 5 in [1]\nlambdaSim=lambda*ESTwoBeta;\nfor i=1:simNumb\n randNumb=poissrnd(lambdaSim*diskArea);\n %shadowing distribution can be constant if lambda is rescaled - see [1]\n shadowRand=ones(randNumb,1); \n %random distances from the typical node \n rRand=diskRadius*sqrt(rand(randNumb,1)); %uniform in cartesion, not polar coordinates\n \n signalRand=shadowRand.*(K*rRand).^(-betaConst);\n interferTotal=sum(signalRand); %total inteference in network\n SINR=signalRand./((interferTotal-signalRand)+W); %calculate SINR for each node in the network\n \n for j=1:tNumb\n T=tValues(j);\n %counts how many nodes are exactly k or more connected/covered\n if sum(SINR>=T)>=k\n coveredNumbk(j)=coveredNumbk(j)+1;\n end\n end\n \nend\n\nsimPCovk=coveredNumbk/simNumb;\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/40087-sinr-based-k-coverage-probability-in-cellular-networks/To be uploaded/funSimLogNormProbCov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6475419867347644}} {"text": "function H = higuchi(sequence,isplot)\n%\n% 'higuchi' estimate the hurst parameter of a given sequence with\n% higuchi's method.\n%\n% Inputs:\n% sequence: the input sequence for estimate \n% isplot: whether display the plot. without a plot if isplot equal to 0 \n% Outputs:\n% H: the estimated hurst coeffeient of the input sequence\n\n% Author: Chu Chen \n% Version 1.0, 03/10/2008\n% chen-chu@163.com\n%\n\nif nargin == 1\n isplot = 0;\nend\n\nsequence = cumsum(sequence);\nN = length(sequence);\nmlarge = floor(N/5);\nM = [floor(logspace(0,log10(mlarge),50))];\nM = unique(M(M>1));\nn = length(M);\ncut_min = ceil(n/10);\ncut_max = floor(6*n/10);\n\ncurve_length = zeros(1,n);\nfor h = 1:n\n m = M(h);\n k = floor((N-m)/m);\n temp_length = zeros(m,k);\n \n for i = 1:m\n for j = 1:k\n temp_length(i,j) = abs(sequence(i+j*m)-sequence(i+(j-1)*m));\n end\n end\n \n curve_length(h) = sum(mean(temp_length,2)) * ((N-1)/m^3);\nend\n\nx = log(M);\ny = log(curve_length);\nX = x(cut_min:cut_max);\nY = y(cut_min:cut_max);\np1 = polyfit(X,Y,1);\nYfit = polyval(p1,X);\nyfit = polyval(p1,x);\nH = 2 + (Yfit(end)-Yfit(1))/(X(end)-X(1));\n\nif isplot ~= 0\n figure,hold on;\n plot(x,y,'b*');\n plot(X,Yfit,'r-','LineWidth',2);\n plot(x(1:cut_min),yfit(1:cut_min),'r:','LineWidth',2);\n plot(x(cut_max:end),yfit(cut_max:end),'r:','LineWidth',2);\n xlabel('Log10(Aggregate Level)'),ylabel('Log10(Curve Legnth)'),title('Higuchi Method');\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/19148-hurst-parameter-estimate/hurst estimator/higuchi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6475334453052548}} {"text": "function [g,a]=ar1nv(x)\n% AR1NV - Estimate the parameters for an AR(1) model\n% Syntax: [g,a]=ar1nv(x);\n%\n% Input: x - a time series.\n%\n% Output: g - estimate of the lag-one autocorrelation.\n% a - estimate of the noise variance.\n\n% (c) Eric Breitenberger\n\nx=x(:);\nN=length(x);\nm=mean(x);\nx=x-m;\n\n% Lag zero and one covariance estimates:\nc0=x'*x/N;\nc1=x(1:N-1)'*x(2:N)/(N-1);\n\ng=c1/c0;\na=sqrt((1-g^2)*c0);\n", "meta": {"author": "grinsted", "repo": "wavelet-coherence", "sha": "b8c3925f54c8d113620925070eb1ac572fbcac05", "save_path": "github-repos/MATLAB/grinsted-wavelet-coherence", "path": "github-repos/MATLAB/grinsted-wavelet-coherence/wavelet-coherence-b8c3925f54c8d113620925070eb1ac572fbcac05/ar1nv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6475334411874246}} {"text": "function [prices, alphas] = Heston1993KahlJaeckelLordRev3(PC, S,K,T,t,r,q,v0,theta,rho,kappa,sigma, alphas)\n% Heston pricing function based on the implementation suggested by\n% Roger Lord and Chrisitan Kahl in \"Optimal Fourier inversion in \n% semi-analytical option pricing\"\n%\n%\n% Input: (PC till q can be vectorized)\n% PC: 1 for Calls, 2 for Puts\n% S: Spot\n% K: Strike\n% T: Maturity\n% t: start date\n% r: interest rate\n% q: dividend\n% v0: initial variance\n% theta: long run mean variance\n% kappa: mean reversion speed of volatility\n% sigma: volatility of volatility\n% rho: correlation between returns volatility\n% alpha: alpha can be a vector supplied by the user, otherwise the\n% function attempts to find a payoff-dependent optimal alpha\n%\n% Output: Price for each option, optionally generated alphas\n%\n% Usage: Heston1993KahlJaeckelLordRev3(1, 100, 100, 20,0, 0.05, 0.0, \n% 0.00003, 0.00003,-0.3, 0.5, 0.0008)\n%\n% Author: Jonathan Frei, 2015\n% \n\n % force column vector\n PC=PC(:);\n S=S(:);\n K=K(:);\n T=T(:);\n t=t(:);\n r=r(:);\n q=q(:);\n\n nos = numel(S);\n prices=NaN(nos,1);\n tau=T-t;\n mu=(r-q);\n F = S.*exp(mu.*tau);\n\n if(~exist('alphas','var'))\n alphas = NaN(numel(S),1);\n elseif(numel(alphas)==1)\n alphas = repmat(alphas,numel(S),1);\n end\n \n alpha0=0.75;\n \n for(ind=1:nos)\n if(isnan(alphas(ind)))\n try\n % using fzero here instead of fminsearch\n alphas(ind) = fzero( @(a) psi(a,K(ind), F(ind), kappa, theta, rho, sigma, tau(ind), v0), alpha0);\n catch\n alphas(ind) = alpha0;\n end\n end\n prices(ind) = Ralpha(F(ind), K(ind), alphas(ind))+1/pi*integral(@(x) phi(x, K(ind), alphas(ind), F(ind), kappa, theta, rho, sigma, tau(ind), v0) , 0, Inf);\n if (PC(ind)==2)\n prices(ind) = prices(ind) + K(ind)*exp(-r(ind)*tau(ind))-S(ind)*exp(-q(ind)*tau(ind));\n end\n end\n\n \nend\n\n\nfunction p = psi(alpha, K, F, kappa, theta, rho, sigma, tau, v0)\n k = log(K);\n p = -alpha*k+0.5*log(phi(-(alpha+1)*1i, K, alpha, F, kappa, theta, rho, sigma, tau, v0)^2);\nend\n\nfunction r = Ralpha(F, K, alpha)\n r = F*(alpha<=0)-K*(alpha<=-1)-0.5*(F*(alpha==0)-K*(alpha==-1));\nend\n\nfunction y = phi(v, K, alpha, F, kappa, theta, rho, sigma, tau, v0)\n k = log(K);\n y = real(exp(-1i*(v-1i*alpha)*k).*( cf(v-1i*(alpha+1), F, kappa, theta, rho, sigma, tau, v0)./(-(v-1i*(alpha+1)).*(v-1i*alpha))));\nend\n\nfunction c = cf(u, F, kappa, theta, rho, sigma, tau, v0)\n f = log(F);\n c = exp(1i*u*f+ A(u, kappa, theta, rho, sigma, tau)+Bv(u, rho, sigma, kappa, tau)*v0);\nend\n\nfunction b = Bv(u, rho, sigma, kappa, tau)\n b = ((beta(u,rho,sigma,kappa)-D(u, rho, sigma, kappa)).*(1-exp(-D(u, rho, sigma, kappa)*tau)))./(sigma.^2*(1-G(u, rho, sigma, kappa).*exp(-D(u, rho, sigma, kappa)*tau)));\nend\n\nfunction a = A(u, kappa, theta, rho, sigma, tau)\n a = (kappa*theta*((beta(u,rho,sigma,kappa)-D(u, rho, sigma, kappa))*tau-2*log(phi2(u, rho, sigma, kappa, tau))))/sigma.^2;\nend\n\nfunction p = phi2(u, rho, sigma, kappa, tau)\n p = (G(u, rho, sigma, kappa).*exp(-D(u, rho, sigma, kappa)*tau)-1)./(G(u, rho, sigma, kappa)-1);\nend\n\nfunction g = G(u, rho, sigma, kappa)\n g = (beta(u,rho,sigma,kappa)-D(u, rho, sigma, kappa))./(beta(u,rho,sigma,kappa)+D(u, rho, sigma, kappa));\nend\n\nfunction d = D(u, rho, sigma, kappa)\n d = sqrt(beta(u,rho,sigma,kappa).^2-4*alphahat(u)*gamma(sigma));\nend\n\nfunction a = alphahat(u)\n a = -0.5*u.*(1i+u);\nend\n\nfunction b = beta(u,rho,sigma,kappa)\n b = kappa-rho*sigma*u*1i;\nend\n\nfunction y = gamma(sigma)\n y = 0.5*sigma.^2;\nend", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Fourier/Heston/Heston1993KahlJaeckelLordRev3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6475334305685176}} {"text": "% Figure 10.67 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% fig10_67.m is a script to generate Fig. 10.67 the linear RTP response \n% PI controller\n% RTP chamber demo Example\nclf;\na=[-0.068208813989939 0.014929776357245 0.000000065782442;...\n 0.045809672136430 -0.118134773528570 0.021802006306129;...\n 0.000000433637498 0.046839194867347 -0.100884399149872];\nb3=[0.37873508304055 0.110575403544586 0.022912893467038;...\n 0.000000002974222 0.449046982554739 0.073572900808161;...\n 0.000000027324116 0.000702342292121 0.417797228783230];\nc3=eye(3,3);\nd3=0*eye(3,3);\n\n% Combine 3 lamps into a single actuator\nb=b3(:,1)+b3(:,2)+b3(:,3);\n% Select center temperature\nc=c3(2,:)\n%\nd=[0];\n% PI controller\nac=[0];\nbc=[1.0];\ncc=[0.0527];\ndc=[1];\nsysG=ss(a,b,c,d);\nsysD=ss(ac,bc,cc,dc);\nsysL=series(sysD,sysG);\nsysH=tf(1,1);\nsysCL=feedback(sysL,sysH);\n\n%CL Step Response\nt=0:.1:100;\nR=[0:.1:25, 25*ones(1,500), 0*ones(1,250)];\nR11=[R'];\n[yy,t]=lsim(sysCL,R11,t);\nplot(t,yy,'--');\ngrid;\nhold on;\nplot(t,R11,'-');\nxlabel('Time (sec)');\nylabel('Temperature (K)');\ntitle('Fig. 10.67 (a) PI controller: temperature tracking response');\n%legend('y')\npause\nhold off\n% Control effort\nsysCLu=feedback(sysD,sysG);\n[uuu,t]=lsim(sysCLu,R11,t);\nplot(t(1:753,:),uuu(1:753,:));\nhold on;\nplot(t(752:818,:),0*ones(67,3));\nhold on;\nplot(t(753:818,:),uuu(753:818,:),'--');\nhold on;\nplot(t(819:1001,:),uuu(819:1001,:));\nxlabel('Time (sec)');\nylabel('Lamp voltage');\ntitle('Fig. 10.67 (b) PI controller :control effort');\nlegend('u')\ngrid;\nhold off;\n\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_67.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6475334243917721}} {"text": "function value = r4_tan ( x )\n\n%*****************************************************************************80\n%\n%% R4_TAN evaluates the tangent of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the tangent of X.\n%\n persistent nterms\n persistent sqeps\n persistent tancs\n persistent xmax\n persistent xsml\n\n pi2rec = 0.0116197723675813430;\n\n if ( isempty ( nterms ) )\n tancs = [ ...\n 0.226279327631293578, ...\n 0.0430179131465489618, ...\n 0.0006854461068256508, ...\n 0.0000110453269475970, ...\n 0.0000001781747790392, ...\n 0.0000000028744968582, ...\n 0.0000000000463748541, ...\n 0.0000000000007481760, ...\n 0.0000000000000120704, ...\n 0.0000000000000001947, ...\n 0.0000000000000000031 ]';\n nterms = r4_inits ( tancs, 11, 0.1 * r4_mach ( 3 ) );\n xmax = 1.0 / r4_mach ( 4 );\n xsml = sqrt ( 3.0 * r4_mach ( 3 ) );\n sqeps = sqrt ( r4_mach ( 4 ) );\n end\n\n y = abs ( x );\n\n if ( xmax < y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_TAN - Warning!\\n' );\n fprintf ( 1, ' No precision because |X| is big.\\n' );\n value = 0.0;\n return\n end\n%\n% Carefully compute y * (2/pi) = (aint(y) + rem(y)) * (.625 + pi2rec)\n% = aint(.625*y) + rem(.625*y) + y*pi2rec = aint(.625*y) + z\n% = aint(.625*y) + aint(z) + rem(z)\n%\n ainty = floor ( y );\n yrem = y - ainty;\n prodbg = 0.625 * ainty;\n ainty = floor ( prodbg );\n y = ( prodbg - ainty ) + 0.625 * yrem + y * pi2rec;\n ainty2 = floor ( y );\n ainty = ainty + ainty2;\n y = y - ainty2;\n\n ifn = floor ( mod ( ainty, 2.0 ) );\n\n if ( ifn == 1 )\n y = 1.0 - y;\n end\n\n if ( 1.0 - y < abs ( x ) * sqeps )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_TAN - Warning!\\n' );\n fprintf ( 1, ' Answer < half precision.\\n' );\n fprintf ( 1, ' |X| big or X near pi/2 or 3*pi/2.\\n' );\n end\n\n if ( y == 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_TAN - Fatal error!\\n' );\n fprintf ( 1, ' X is pi/2 or 3*pi/2.\\n' );\n error ( 'R4_TAN - Fatal error!' )\n end\n\n if ( y <= 0.25 )\n\n value = y;\n if ( xsml < y )\n value = y * ( 1.5 ...\n + r4_csevl ( 32.0 * y * y - 1.0, tancs, nterms ) );\n end\n\n elseif ( y <= 0.5 )\n\n value = 0.5 * y * ( 1.5 ...\n + r4_csevl ( 8.0 * y * y - 1.0, tancs, nterms ) );\n\n value = 2.0 * value / ( 1.0 - value * value );\n\n else\n\n value = 0.25 * y * ( 1.5 ...\n + r4_csevl ( 2.0 * y * y - 1.0, tancs, nterms ) );\n value = 2.0 * value / ( 1.0 - value * value );\n value = 2.0 * value / ( 1.0 - value * value );\n\n end\n\n if ( x < 0.0 )\n value = - abs ( value );\n elseif ( 0.0 < x )\n value = + abs ( value );\n end\n\n if ( ifn == 1 )\n value = - value;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6474570389473077}} {"text": "function b = r83t_mv ( m, n, a, x )\n\n%*****************************************************************************80\n%\n%% R83T_MV multiplies an R83T matrix times an R8VEC.\n%\n% Discussion:\n%\n% The R83T storage format is used for a tridiagonal matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,3), the matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(M), the product A * x.\n%\n b = zeros ( m, 1 );\n x = x(:);\n\n mn = min ( m, n );\n\n if ( n == 1 )\n b(1) = a(1,2) * x(1);\n if ( 1 < m )\n b(2) = a(2,1) * x(1);\n end\n return\n end\n\n b(1) = a(1,2) * x(1) ...\n + a(1,3) * x(2);\n\n b(2:mn-1) = a(2:mn-1,1) .* x(1:mn-2) ...\n + a(2:mn-1,2) .* x(2:mn-1) ...\n + a(2:mn-1,3) .* x(3:mn);\n\n b(mn) = a(mn,1) * x(mn-1) ...\n + a(mn,2) * x(mn);\n\n if ( n < m )\n b(mn+1) = b(mn+1) + a(mn+1,1) * x(mn);\n elseif ( m < n )\n b(mn) = b(mn) + a(mn,3) * x(mn+1);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cg/r83t_mv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6474570227671299}} {"text": "% test of hufmann coding by concatening several token\n\n% probability of having 0\nt = .12;\nn = 4096*2;\nx = (rand(n,1)>t)+1;\n\n% entropy lower bound\np = [t 1-t];\ne = -sum(p.*log2(p));\n\n% create a new vector by lifting\nq = 3;\nn1 = ceil(n/q)*q;\nx1 = x;\nx1(end+1:n1) = 1;\nx1 = reshape(x1,[q n1/q]);\n[Y,X] = meshgrid(1:n1/q,0:q-1);\nx1 = sum( (x1-1) .* (2.^X), 1 )' + 1;\n\n% generate probability table\nP = p(:); p = p(:);\nfor i=1:q-1\n Pold = P;\n P = [];\n for i=1:length(p)\n P = [P; Pold*p(i)];\n end\nend\n\n% compute the tree\nT = compute_hufftree(P);\n% do the coding\ny = perform_huffcoding(x1,T,+1);\n% average number of bits\ne1 = length(y)/length(x);\n\ndisp(['Entropy=' num2str(e) ', Huffman(block size ' num2str(q) ')=' num2str(e1)]);", "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_signal/tests/test_vector_huff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6474484916288713}} {"text": "function f = tone2freq(T)\n% MUSIC.TONE2FREQ converts a musical semitone to a frequency.\n% F = MUSIC.TONE2FREQ(T) converts the musical semitones in T to frequencies.\n%\n% Example\n% f = music.tone2freq(0:2); % returns [261.63 277.19 293.67]\n%\n% See also music.tone2interval, music.tone2note, music.freq2tone.\n\n% Author: E. Johnson\n% Copyright 2010 The MathWorks, Inc.\n\n\nfC4 = 261.625565300599; % Middle C (C4) is 261.63 Hz\n\nf = fC4 .* 2 .^ (T / 12);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26509-musical-notes/Pitch/+music/tone2freq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6474484856637582}} {"text": "function [W,H] = nmf_cjlin(V,Winit,Hinit,tol,timelimit,maxiter)\n% \n% Copyright (c) 2005-2006 Chih-Jen Lin\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% 1. Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n% \n% 2. Redistributions in binary form must reproduce the above copyright\n% notice, this list of conditions and the following disclaimer in the\n% documentation and/or other materials provided with the distribution.\n% \n% 3. Neither name of copyright holders nor the names of its contributors\n% may be used to endorse or promote products derived from this software\n% without specific prior written permission.\n% \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 FOR\n% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR\n% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n% PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n%\n%\n% NMF by alternative non-negative least squares using projected gradients\n% Author: Chih-Jen Lin, National Taiwan University\n%\n% W,H: output solution\n% Winit,Hinit: initial solution\n% tol: tolerance for a relative stopping condition\n% timelimit, maxiter: limit of time and iterations\n\n\n\nW = Winit; H = Hinit; initt = cputime;\n\ngradW = W*(H*H') - V*H'; gradH = (W'*W)*H - W'*V;\ninitgrad = norm([gradW; gradH'],'fro');\nfprintf('Init gradient norm %f\\n', initgrad); \ntolW = max(0.001,tol)*initgrad; tolH = tolW;\n\nfor iter=1:maxiter,\n % stopping condition\n projnorm = norm([gradW(gradW<0 | W>0); gradH(gradH<0 | H>0)]);\n if projnorm < tol*initgrad | cputime-initt > timelimit,\n break;\n end\n \n [W,gradW,iterW] = nlssubprob(V',H',W',tolW,1000); W = W'; gradW = gradW';\n if iterW==1,\n tolW = 0.1 * tolW;\n end\n\n [H,gradH,iterH] = nlssubprob(V,W,H,tolH,1000);\n if iterH==1,\n tolH = 0.1 * tolH; \n end\n\n if (iterW==1 & iterH==1 & tolH + tolW < tol*initgrad),\n fprintf('Failed to move\\n'); break;\n end\n if rem(iter,10)==0, fprintf('.'); end\nend\nfprintf('\\nIter = %d Final proj-grad norm %f\\n', iter, projnorm);\n\n\n\nfunction [H,grad,iter] = nlssubprob(V,W,Hinit,tol,maxiter)\n% H, grad: output solution and gradient\n% iter: #iterations used\n% V, W: constant matrices\n% Hinit: initial solution\n% tol: stopping tolerance\n% maxiter: limit of iterations\n\nH = Hinit; \nWtV = W'*V;\nWtW = W'*W; \n\nalpha = 1; beta = 0.1;\nfor iter=1:maxiter, \n grad = WtW*H - WtV;\n projgrad = norm(grad(grad < 0 | H >0));\n if projgrad < tol,\n break\n end\n\n % search step size \n Hn = max(H - alpha*grad, 0); d = Hn-H;\n gradd=sum(sum(grad.*d)); dQd = sum(sum((WtW*d).*d));\n if gradd + 0.5*dQd > 0.01*gradd, \n % decrease alpha\n while 1,\n alpha = alpha*beta;\n Hn = max(H - alpha*grad, 0); d = Hn-H;\n gradd=sum(sum(grad.*d)); dQd = sum(sum((WtW*d).*d));\n if gradd + 0.5*dQd <= 0.01*gradd | alpha < 1e-20, \n H = Hn; break;\n end\n end \n else \n % increase alpha\n while 1,\n Hp = Hn;\n alpha = alpha/beta;\n Hn = max(H - alpha*grad, 0); d = Hn-H;\n gradd=sum(sum(grad.*d)); dQd = sum(sum((WtW*d).*d));\n if gradd + 0.5*dQd > 0.01*gradd | Hn == Hp | alpha > 1e10, \n H = Hp; alpha = alpha*beta; break;\n end\n end \n end\nend\n\nif iter==maxiter,\n fprintf('Max iter in nlssubprob\\n');\nend\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/nmf/NMF-DTU-Toolbox/nmf_cjlin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6474484804744074}} {"text": "function Z=SoftThreshold_GS( A, thres )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Soft-thresholding for group lasso\n%\n% Reference:\n% Yuan, Ming, and Yi Lin. \n% \"Model selection and estimation in regression with grouped variables.\" \n% Journal of the Royal Statistical Society: Series B \n% (Statistical Methodology) 68.1 (2006): 49-67.\n%\n% Provider:\n% Hongteng Xu @ Georgia Tech\n% June 12, 2017\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nZ = zeros(size(A));\nfor u = 1:size(A, 3)\n for v = 1:size(A, 1)\n tmp = 1 - thres/norm(A(v,:,u));\n if tmp>0\n Z(v,:,u) = tmp*A(v,:,u);\n end\n end\nend\n", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/BasicFunc/SoftThreshold_GS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6474314789199791}} {"text": "function [d pred] = shortest_paths(A,u,varargin)\n% SHORTEST_PATHS Compute the weighted single source shortest path problem.\n%\n% [d pred] = shortest_paths(A,u) returns the distance (d) and the predecessor\n% (pred) for each of the vertices along the shortest path from u to every\n% other vertex in the graph. \n% \n% ... = shortest_paths(A,u,...) takes a set of\n% key-value pairs or an options structure. See set_matlab_bgl_options\n% for the standard options. \n% options.algname: the algorithm to use \n% [{'auto'} | 'dijkstra' | 'bellman_ford' | 'dag']\n% options.inf: the value to use for unreachable vertices \n% [double > 0 | {Inf}]\n% options.target: a special vertex that will stop the search when hit\n% [{'none'} | any vertex number besides the u]; target is ignored if\n% visitor is set.\n% options.visitor: a structure with visitor callbacks. This option only\n% applies to dijkstra or bellman_ford algorithms. See dijkstra_sp or\n% bellman_ford_sp for details on the visitors.\n% options.edge_weight: a double array over the edges with an edge\n% weight for each edge, see EDGE_INDEX and EXAMPLES/REWEIGHTED_GRAPHS\n% for information on how to use this option correctly\n% [{'matrix'} | length(nnz(A)) double vector]\n%\n% Note: if you need to compute shortest paths with 0 weight edges, you must\n% use an edge_weight vector, see the examples for details.\n%\n% Note: 'auto' cannot be used with 'nocheck' = 1. The 'auto' algorithm\n% checks if the graph has negative edges and uses bellman_ford in that\n% case, otherwise, it uses 'dijkstra'. In the future, it may check if the\n% graph is a dag and use 'dag'. \n%\n% Example:\n% load graphs/clr-25-2.mat\n% shortest_paths(A,1)\n% shortest_paths(A,1,struct('algname','bellman_ford'))\n%\n% See also DIJKSTRA_SP, BELLMAN_FORD_SP, DAG_SP\n\n% David Gleich\n% Copyright, Stanford University, 2006-2008\n\n%% History\n% 2006-04-19: Initial coding\n% 2007-04-18: Added edge_weight option.\n% 2007-04-19: Added target option.\n% Added additional error checks.\n% 2007-07-12: Fixed edge_weight documentation\n%%\n\n[trans check full2sparse] = get_matlab_bgl_options(varargin{:});\nif full2sparse && ~issparse(A), A = sparse(A); end\n\noptions = struct('algname', 'auto', 'inf', Inf, 'edge_weight', 'matrix', ...\n 'target', 'none');\noptions = merge_options(options,varargin{:}); \n\n% edge_weights is an indicator that is 1 if we are using edge_weights\n% passed on the command line or 0 if we are using the matrix.\nedge_weights = 0;\nedge_weight_opt = 'matrix';\n\nif strcmp(options.edge_weight, 'matrix')\n % do nothing if we are using the matrix weights\nelse\n edge_weights = 1;\n edge_weight_opt = options.edge_weight;\nend\n\nif strcmp(options.target,'none')\n target = 0; % a flag used to denote \"no target\" to the mex\nelseif isa(options.target, 'double')\n target = options.target;\nelse\n error('matlab_bgl:invalidParameter', ...\n 'options.target is not ''none'' or a vertex number.');\nend\n\nif check\n % check the values of the matrix\n check_matlab_bgl(A,struct('values',edge_weights ~= 1));\n \n if edge_weights && nnz(A) ~= length(edge_weight_opt)\n error('matlab_bgl:invalidParameter', 'the vector of edge weights must have length nnz(A)');\n end\n \n % set the algname\n if (strcmpi(options.algname, 'auto'))\n if edge_weights\n mv = min(edge_weights);\n else\n mv = min(min(A));\n end\n \n if (mv < 0)\n options.algname = 'bellman_ford';\n else\n options.algname = 'dijkstra';\n end\n else\n % check the data provided to match the algorithm\n if strcmpi(options.algname, 'dijkstra')\n if edge_weights\n mv = min(edge_weight_opt);\n else\n mv = min(min(A));\n end\n if mv < 0\n error('matlab_bgl:invalidParameter', ...\n 'dijkstra''s algorithm cannot be used with negative edge weights.');\n end\n end\n end\n \nelse\n if (strcmpi(options.algname, 'auto'))\n error('shortest_paths:invalidParameter', ...\n 'algname auto is not compatible with no check'); \n end\nend\n\nif options.inf < 0, error('options.inf must be larger than 0'); end\n\nif trans, A = A'; end\n\nif isfield(options,'visitor')\n [d pred] = matlab_bgl_sp_mex(A,u,target,lower(options.algname),options.inf,...\n edge_weight_opt, options.visitor);\nelse\n [d pred] = matlab_bgl_sp_mex(A,u,target,lower(options.algname),options.inf,...\n edge_weight_opt);\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/shortest_paths.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.647431477271631}} {"text": "function ttf = sin_test()\n\nd = 10;\nr = 2;\nn = 2;\nN = 20000;\nx = 2*pi*rand(d,N);\ny = sin(sum(x));\ntt_rank = [1 ; r*ones(d-1,1) ; 1];\nn_basis = n*ones(d,1);\nbasis_ps = cumsum([1 ; n_basis*N]);\nbasis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);\nfor dim = 1: d\n t = zeros(n, N);\n t(1,:) = sin(x(dim,:));\n t(2,:) = cos(x(dim,:));\n\tbasis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);\nend \ncoeff = reg_als(basis_cr, y, tt_rank, n_basis);\nttf = tt_function(@fun, coeff);\n\nend\n\nfunction fx = fun(~, j, x)\n% i-th dimension, j-th basis function at x\n\nif j == 1\n fx = sin(x);\nelseif j == 2\n fx = cos(x);\nend\n\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tt_regression/sin_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6474184896973469}} {"text": "function [convRVTOut, rvtOut, verbose] = tapas_physio_create_rvt_regressors(...\n ons_secs, sqpar, model_rvt, verbose)\n% computes respiratory response function regressor and respiratory volume per time\n%\n% [convRVTOut, rvtOut, verbose] = tapas_physio_create_rvt_regressors(...\n% ons_secs, sqpar, model_rvt, verbose)\n% References:\n%\n% Birn, R.M., Smith, M.A., Jones, T.B., Bandettini, P.A., 2008.\n% The respiration response function: The temporal dynamics of\n% fMRI signal fluctuations related to changes in respiration.\n% NeuroImage 40, 644-654.\n%\n% Harrison, S.J., Bianchi, S., Heinzle, J., Stephan, K.E., Iglesias, S., \n% Kasper L., 2021.\n% A Hilbert-based method for processing respiratory timeseries.\n% NeuroImage, 117787. https://doi.org/10.1016/j.neuroimage.2021.117787\n\n% IN\n% ons_secs.\n% ons_secs ons_secs structure with variable `fr`\n% (filtered respiratory signal time series)\n% sqpar scan timing information (sequence parameters)\n% slice onsets etc.\n% model_rvt rvt modeling parameter structure. e.g.\n% model_rvt.method\n% 'hilbert' (default, [Harrison2021]) or\n% 'peaks' [Birn2006]\n%\n% OUT\n% convRVTOut [nScans, nDelays, nSampleSlices]\n% respiratory response function regressor after\n% convolution for specified delays and downsampled\n% to given slices.\n% EXAMPLE\n% [convHRV, hr] = tapas_physio_create_hrv_regressor(physio_out.ons_secs, physio_out.sqpar);\n%\n% See also tapas_physio_rvt_hilbert tapas_physio_rvt_peaks tapas_physio_rrf\n\n% Author: Lars Kasper\n% Created: 2014-01-20\n% Copyright (C) 2014 TNU, Institute for Biomedical Engineering, \n% University of Zurich and ETH Zurich.\n%\n% This file is part of the physIO toolbox, which is released under the\n% terms of the GNU General Public Licence (GPL), version 3. You can\n% redistribute it and/or modify it under the terms of the GPL (either\n% version 3 or, at your option, any later version). For further details,\n% see the file COPYING or .\n\nif nargin < 3\n physio = tapas_physio_new;\n model_rvt = physio.model.rvt;\nend\n\ndelays = model_rvt.delays;\n\n\nif nargin < 4\n verbose.level = [];\n verbose.fig_handles = [];\nend\n\nslicenum = 1:sqpar.Nslices;\n\n\n% Calculate RVT\nsample_points = tapas_physio_get_sample_points(ons_secs, sqpar, slicenum);\nswitch lower(model_rvt.method)\n case 'peaks'\n [rvt, ~, ~, verbose] = tapas_physio_rvt_peaks(ons_secs.fr, ons_secs.t, sample_points, verbose);\n case 'hilbert'\n [rvt, verbose] = tapas_physio_rvt_hilbert(ons_secs.fr, ons_secs.t, sample_points, verbose);\n otherwise\n error('Unrecognised value for ''rvt.method'' (%s)!', model_rvt.method)\nend\nrvt = rvt / max(abs(rvt)); % normalize for reasonable range of regressor\n\nif verbose.level >=2\n verbose.fig_handles(end+1) = tapas_physio_get_default_fig_params();\n set(gcf, 'Name', 'Model: Convolution Respiration RVT X RRF');\n subplot(2,2,1)\n plot(sample_points,rvt, 'g');xlabel('time (seconds)');\n title('Respiratory volume per time');\n ylabel('a.u.');\nend\n\n\n% Generate RRF\ndt = sqpar.TR / sqpar.Nslices;\nt = 0:dt:60; % seconds\nrrf = tapas_physio_rrf(t);\nrrf = rrf / max(abs(rrf));\n\nif verbose.level >= 2\n subplot(2,2,2)\n plot(t, rrf,'g'); xlabel('time (seconds)');\n title('Respiratory response function');\nend\n\n\n% Convolve and rescale for display purposes\nconvRVT = tapas_physio_conv(rvt, rrf, 'causal');\nconvRVT = convRVT / max(abs(convRVT));\n\nif verbose.level >= 2\n subplot(2,2,3)\n plot(sample_points, convRVT,'g');xlabel('time (seconds)');\n title('Resp vol time X resp response function');\nend\n\n\n% Create shifted regressors convolved time series, which is equivalent to\n% delayed response functions according to Wikipedia (convolution)\n%\n% \"Translation invariance[edit]\n% The convolution commutes with translations, meaning that\n%\n% \\tau_x ({f}*g) = (\\tau_x f)*g = {f}*(\\tau_x g)\\,\n% where \\tau_x is the translation of the function f by x defined by\n% (\\tau_x f)(y) = f(y-x).\n\n% remove mean and linear trend to fulfill periodicity condition for\n% shifting\nconvRVT = detrend(convRVT);\n\n% TODO: what happens at the end/beginning of shifted convolutions?\nnDelays = numel(delays);\nnShiftSamples = ceil(delays/dt);\n\n% resample to slices needed\nnSampleSlices = numel(sqpar.onset_slice);\nnScans = numel(sample_points(sqpar.onset_slice:sqpar.Nslices:end));\n\nrvtOut = zeros(nScans,nSampleSlices);\nconvRVTOut = zeros(nScans,nDelays,nSampleSlices);\nsamplePointsOut = zeros(nScans,nSampleSlices);\n\nfor iDelay = 1:nDelays\n convRVTShifted = circshift(convRVT, nShiftSamples(iDelay));\n for iSlice = 1:nSampleSlices\n onset_slice = sqpar.onset_slice(iSlice);\n rvtOut(:,iSlice) = rvt(onset_slice:sqpar.Nslices:end)';\n convRVTOut(:,iDelay,iSlice) = convRVTShifted(onset_slice:sqpar.Nslices:end);\n samplePointsOut(:,iSlice) = sample_points(onset_slice:sqpar.Nslices:end);\n end\nend\n\nif verbose.level >= 2\n subplot(2,2,4)\n [tmp, iShiftMin] = min(abs(delays));\n hp{1} = plot(samplePointsOut, rvtOut,'k--');hold all;\n hp{2} = plot(samplePointsOut, squeeze(convRVTOut(:,iShiftMin,:)),'g');\n xlabel('time (seconds)');\n title('RVT regessor');\n legend([hp{1}(1), hp{2}(1)], 'respiratory volume / time (a. u.)', ...\n 'respiratory response regressor');\nend\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/PhysIO/code/model/tapas_physio_create_rvt_regressors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.647409612605642}} {"text": "addpath('../src/')\naddpath('../src/utils/')\n\n% fix random seed\nrng(0);\n\n% make your own discrete linear system with disturbance\nA = [1 1; 0 1];\nB = [0.5; 1]; \nQ = diag([1, 1]);\nR = 0.1;\n\nW_vertex = [0.15, 0.15; 0.15, -0.15; -0.15, -0.15; -0.15, 0.15]; % construct a convex set of disturbance (2dim here)\nW = Polyhedron(W_vertex);\n\n% construct disturbance Linear system\ndisturbance_system = DisturbanceLinearSystem(A, B, Q, R, W);\n\n% constraints on state Xc and input Uc\nXc_vertex = [2, -2; 2 2; -10 2; -10 -2];\nUc_vertex = [1; -1];\nXc = Polyhedron(Xc_vertex);\nUc = Polyhedron(Uc_vertex);\n\n% create a tube_mpc simulater\n% if N_horizon is too small, the path will never reach inside the robust MPI-set X_mpi_robust in time step N_horizon, then the problem becomes infeasible. \nN_horizon = 10;\nw_min = [0; -0.10];\nw_max = [0; 0.10];\nmpc = TubeModelPredictiveControl(disturbance_system, Xc, Uc, N_horizon);\n\n% The robust MPC guidances the path inside the robust MPI-set so that the path will reach the robust MPI-set in N_horizon. \nx = [-7; -2];\nsavedir_name = './results/';\nmkdir(savedir_name);\n\nfor i = 1:15\n disp(i)\n u_next = mpc.solve(x);\n x = disturbance_system.propagate(x, u_next); % additive disturbance is considered inside the method \n mpc.show_prediction();\n filename = strcat(savedir_name, 'tmpc_seq', number2string(i), '.png')\n saveas(gcf, char(filename)); % removing this line makes the code much faster\n clf;\nend\n\n", "meta": {"author": "HiroIshida", "repo": "robust-tube-mpc", "sha": "427a181dd368f0b60b1ecfa81e33e062ff0359e0", "save_path": "github-repos/MATLAB/HiroIshida-robust-tube-mpc", "path": "github-repos/MATLAB/HiroIshida-robust-tube-mpc/robust-tube-mpc-427a181dd368f0b60b1ecfa81e33e062ff0359e0/example/example_tubeMPC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6472087079660608}} {"text": "function [X1, Y1] = Direction2Angular(D, r, c)\n%\n% [X1, Y1] = Direction2Angular(D, r, c)\n%\n%\n% Input:\n% -D: 3D directions of the img format\n% -r: height of the angular image\n% -c: width of the angular image\n% Output:\n% -X1: X coordinates in the Angular format\n% -Y1: Y coordinates in the Angular format\n%\n% Copyright (C) 2011-15 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\n%Coordinates generation\nR = acos(-D(:,:,3)) ./ (pi * 2 * sqrt(D(:,:,1).^2 + D(:,:,2).^2));\n\nX1 = (0.5 + R .* D(:,:,1)) * c;\nY1 = (0.5 - R .* D(:,:,2)) * r;\n\nX1 = RemoveSpecials(X1);\nY1 = RemoveSpecials(Y1);\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/EnvironmentMaps/Direction2Angular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7154239957834732, "lm_q1q2_score": 0.6472087006095363}} {"text": "function GaussianHighpass\na=imread('cameraman.tif');\nfigure(1)\nimshow(a)\n[m n]=size(a);\nf_transform=fft2(a);\nf_shift=fftshift(f_transform);\np=m/2;\nq=n/2;\nd0=70;\nfor i=1:m\nfor j=1:n\ndistance=sqrt((i-p)^2+(j-q)^2);\nlow_filter(i,j)=1-exp(-(distance)^2/(2*(d0^2)));\nend\nend\nfilter_apply=f_shift.*low_filter;\nimage_orignal=ifftshift(filter_apply);\nimage_filter_apply=abs(ifft2(image_orignal));\nfigure(2)\nimshow(image_filter_apply,[])", "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/39701-gaussian-high-pass-filter/GaussianHighpass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.647115660074412}} {"text": "function y = lorentzian(x, sigma, type)\n%LORENTZIAN Lorentzian robust function.\n% LORENTZIAN(X, SIGMA, TYPE) evaluates the Lorentzian robust function\n% with sigma SIGMA at point(s) X. \n% TYPE selects the evaluation type:\n% - 0: function value\n% - 1: first derivative\n% - 2: second derivative\n% \n% This is a private member function of the class 'robust_function'. \n%\n% Author: Stefan Roth, Department of Computer Science, TU Darmstadt\n% Contact: sroth@cs.tu-darmstadt.de\n% $Date: $\n% $Revision: $\n\n% Copyright 2004-2007, Brown University, Providence, RI. USA\n% Copyright 2007-2010 TU Darmstadt, Darmstadt, Germany.\n% \n% All Rights Reserved\n% \n% All commercial use of this software, whether direct or indirect, is\n% strictly prohibited including, without limitation, incorporation into in\n% a commercial product, use in a commercial service, or production of other\n% artifacts for commercial purposes. \n%\n% Permission to use, copy, modify, and distribute this software and its\n% documentation for research purposes is hereby granted without fee,\n% provided that the above copyright notice appears in all copies and that\n% both that copyright notice and this permission notice appear in\n% supporting documentation, and that the name of the author and Brown\n% University not be used in advertising or publicity pertaining to\n% distribution of the software without specific, written prior permission. \n%\n% For commercial uses contact the Technology Venture Office of Brown University\n% \n% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO\n% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n% FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR\n% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n% THIS SOFTWARE. \n\n\n switch (type)\n case 0\n y = log(1 + x.^2 / (2 * sigma^2));\n case 1\n y = 2 * x ./ (2 * sigma^2 + x.^2);\n case 2\n y = 2 ./ (2 * sigma^2 + x.^2); % not second order, but first order/x (Deqing Sun 24 Nov 2007)\n end", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/spaceTime/optflow_deqing/utils/@robust_function/private/lorentzian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.647090261806499}} {"text": "function M = stiefelgeneralizedfactory(n, p, B)\n% Returns a manifold structure of \"scaled\" orthonormal matrices.\n%\n% function M = stiefelgeneralizedfactory(n, p)\n% function M = stiefelgeneralizedfactory(n, p, B)\n%\n% The generalized Stiefel manifold is the set of \"scaled\" orthonormal \n% nxp matrices X such that X'*B*X is identity. B must be positive definite.\n% If B is identity, then this is the standard Stiefel manifold.\n%\n% The generalized Stiefel manifold is endowed with a scaled metric\n% by making it a Riemannian submanifold of the Euclidean space,\n% again endowed with the scaled inner product.\n%\n% Some notions (not all) are from Section 4.5 of the paper\n% \"The geometry of algorithms with orthogonality constraints\",\n% A. Edelman, T. A. Arias, S. T. Smith, SIMAX, 1998.\n%\n% Paper link: http://arxiv.org/abs/physics/9806030.\n%\n% Note: egrad2rgrad and ehess2rhess involve solving linear systems in B. If\n% this is a bottleneck for a specific application, then a way forward is to\n% create a modified version of this file which preprocesses B to speed this\n% up (typically, by computing a Cholesky factorization of it, then calling\n% an appropriate solver).\n%\n% See also: stiefelfactory grassmannfactory grassmanngeneralizedfactory \n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, June 30, 2015.\n% Contributors:\n%\n% Change log:\n% \n\n \n if ~exist('B', 'var') || isempty(B)\n B = speye(n); % Standard Stiefel manifold.\n end\n \n M.name = @() sprintf('Generalized Stiefel manifold St(%d, %d)', n, p);\n \n M.dim = @() (n*p - .5*p*(p+1));\n \n M.inner = @(X, eta, zeta) trace(eta'*(B*zeta)); % Scaled metric.\n \n M.norm = @(X, eta) sqrt(M.inner(X, eta, eta));\n \n M.dist = @(X, Y) error('stiefelgeneralizedfactory.dist not implemented yet.');\n \n M.typicaldist = @() sqrt(p);\n \n % Orthogonal projection of an ambient vector U to the tangent space\n % at X.\n M.proj = @projection;\n function Up = projection(X, U)\n BX = B*X;\n \n % Projection onto the tangent space\n Up = U - X*symm(BX'*U); \n end\n \n M.tangent = M.proj;\n \n M.egrad2rgrad = @egrad2rgrad;\n function rgrad = egrad2rgrad(X, egrad)\n \n % First, scale egrad according the to the scaled metric in the\n % Euclidean space.\n egrad_scaled = B\\egrad;\n \n % Second, project onto the tangent space.\n % rgrad = egrad_scaled - X*symm((B*X)'*egrad_scaled);\n %\n % Verify that symm(BX'*egrad_scaled) = symm(X'*egrad).\n \n rgrad = egrad_scaled - X*symm(X'*egrad);\n end\n \n \n \n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, H)\n egraddot = ehess;\n Xdot = H;\n \n % Directional derivative of the Riemannian gradient.\n egrad_scaleddot = B\\egraddot;\n rgraddot = egrad_scaleddot - Xdot*symm(X'*egrad)...\n - X*symm(Xdot'*egrad)...\n - X*symm(X'*egraddot);\n \n % Project onto the tangent space.\n rhess = M.proj(X, rgraddot);\n end\n \n \n M.retr = @retraction;\n function Y = retraction(X, U, t)\n if nargin < 3\n t = 1.0;\n end\n Y = guf(X + t*U); % Ensure that Y'*B*Y is identity.\n end\n \n \n M.exp = @exponential;\n function Y = exponential(X, Z, t)\n if nargin < 3\n t = 1.0;\n end\n Y = retraction(X, Z, t);\n warning('manopt:stiefelgeneralizedfactory:exp', ...\n ['Exponential for generalized Stiefel manifold ' ...\n 'manifold not implemented yet. Used retraction instead.']);\n end\n\n\n M.hash = @(X) ['z' hashmd5(X(:))];\n \n M.rand = @random;\n function X = random()\n X = guf(randn(n, p)); % Ensure that X'*B*X is identity;\n end\n \n M.randvec = @randomvec;\n function U = randomvec(X)\n U = projection(X, randn(n, p));\n U = U / norm(U(:));\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(X) zeros(n, p);\n \n % This transport is compatible with the generalized polar retraction.\n M.transp = @(X1, X2, d) projection(X2, d);\n \n M.vec = @(X, u_mat) u_mat(:);\n M.mat = @(X, u_vec) reshape(u_vec, [n, p]);\n M.vecmatareisometries = @() false;\n \n % Some auxiliary functions\n symm = @(D) (D + D')/2;\n \n function X = guf(Y)\n % Generalized polar decomposition of an n-by-p matrix Y.\n % X'*B*X is identity.\n \n % Method 1\n [u, ~, v] = svd(Y, 0);\n \n % Instead of the following three steps, an equivalent, but an \n % expensive way is to do X = u*(sqrtm(u'*(B*u))\\(v')).\n [q, ssquare] = eig(u'*(B*u));\n qsinv = q/sparse(diag(sqrt(diag(ssquare))));\n X = u*((qsinv*q')*v'); % X'*B*X is identity.\n \n \n % Another computation using restricted_svd\n % [u, ~, v] = restricted_svd(Y);\n % X = u*v'; % X'*B*X is identity.\n \n end\n \n function [u, s, v] = restricted_svd(Y)\n % We compute a thin svd-like decomposition of an n-by-p matrix Y \n % into matrices u, s, and v such that u is an n-by-p matrix\n % with u'*B*u being identity, s is a p-by-p diagonal matrix \n % with positive entries, and v is a p-by-p orthogonal matrix.\n % Y = u*s*v'.\n [v, ssquare] = eig(symm(Y'*(B*Y))); % Y*B*Y is positive definite\n ssquarevec = diag(ssquare);\n \n s = sparse(diag(abs(sqrt(ssquarevec))));\n u = Y*(v/s); % u'*B*u is identity.\n end\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/stiefel/stiefelgeneralizedfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6470363063179431}} {"text": "function [zPred,PzPred,otherInfo]=reducedStateMeasPred(xPred,PPred,H)\n%%REDUCEDSTATEMEASPRED Perform the measurement prediction part of the\n% measurement update step of the reduced state estimator. The\n% function reducedStateMeasUpdateWithPred can be used to complete\n% the measurement update. Separating the measurement prediction\n% step from the rest of the update step can make the creation of\n% multiple measurement association hypotheses from a single\n% target prediction more efficient. The full measurement update\n% function is reducedStateUpdate.\n%\n%INPUTS: xPred The xDimXnumComp predicted target states.\n% PPred The xDimXxDimXnumComp predicted state covariance matrices.\n% H The zDimXxDim measurement matrix. The measurement is modeled\n% as z=H*x+noise.\n%\n%OUTPUTS: zPred The zDimXnumComp measurement predictions from the filter.\n% PzPred The zDimXzDimXnumComp covariance matrix associated with the\n% values in zPred.\n% otherInfo A structure containing members of intermediate results of\n% this function that can be passed to KalmanUpdateWithPred\n% when updating with a measurement.\n%\n%The measurement prediction step in the measurement update step of the\n%reduced state estimator is the same as that in the Kalman filter. Thus,\n%this function just calls KalmanMeasPred. \n%\n%The filter is taken from [1]. See the comments to reducedStateUpdate for\n%more information.\n%\n%EXAMPLE:\n%With this example, we demonstrate that one gets the same result using\n%reducedStateUpdate versus calling reducedStateMeasPred and then\n%reducedStateMeasUpdateWithPred. \n% xPred=[1e3;-2e3;100;200];\n% MPred=[28, 3.5, 6, 8.5;\n% 3.5, 23, 8.5, 11;\n% 6, 8.5, 18, 13.5;\n% 8.5, 11, 13.5, 13];\n% DPred=[8, 0;\n% 0, 8;\n% 8, 0;\n% 0, 8];\n% PPred=MPred+(1/2)*(DPred*DPred');\n% z=1e3*[-5.498856156296510;\n% 1.199241491470584];\n% R=eye(2);\n% H=[0, 4, 9, 8;\n% 6, 3, 0, 6];\n% %The update in one step.\n% [xUpdate,MUpdate,DUpdate,innov,Pzz,W]=reducedStateUpdate(xPred,PPred,MPred,DPred,z,R,H);\n% %The update in two steps.\n% [zPred,PzPred,otherInfo]=reducedStateMeasPred(xPred,PPred,H);\n% [xUpdate1,MUpdate1,DUpdate1,innov1,Pzz1,W1]=reducedStateMeasUpdateWithPred(z,R,zPred,PzPred,otherInfo,MPred,DPred);\n% %One will see that the one and two step updates agree.\n% max(abs([xUpdate1-xUpdate;MUpdate1(:)-MUpdate(:);DUpdate1(:)-DUpdate(:);innov1(:)-innov;Pzz1(:)-Pzz(:);W1(:)-W(:)]))\n%\n%REFERENCES:\n%[1] P. Mookerjee and F. Reifler, \"Reduced state estimator for systems with\n% parametric inputs,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 40, no. 2, pp. 446-461, Apr. 2004.\n%\n%June 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[zPred,PzPred,otherInfo]=KalmanMeasPred(xPred,PPred,H);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Measurement_Update/Update_Parts/Filter_Measurement_Prediction/reducedStateMeasPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117812622842, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6470362879113786}} {"text": "function [I,k] = verifyquad(funfcn,a,b,tol,see,mmax,varargin)\n%QUAD Verified quadrature using Romberg's scheme - rudimentary implementation\n%\n%The input function must be real and at least 4 times differentiable. The quadrature\n% does NOT work if f or its derivatives have poles in or near the interval [a,b].\n% Not much optimization of the parameters is done; if the routine works well, there\n% is at least a verified inclusion of the integral available.\n%\n% [ I , k ] = verifyquad(f,a,b,tol,see,mmax,varargin)\n%\n%The univariate real function f is integrated from a to b; must at least be 4 times differentiable.\n%\n% optional input tol anticipated (relative) tolerance (default 1e-6)\n% see see intermediate results \n% mmax maximal order of Romberg scheme <=16; note that derivatives \n% up to 2*mmax+2 are computed (default mmax=4)\n% P1,... extra parameters for function evaluation\n% f(x,P1,P2,...)\n% optional output k number of subintervals\n%\n%A simple example:\n%\n% Q = verifyquad('exp(x*sin(x))',0,10)\n%\n%Routine verifyquad is by no means optimized, just written straightforwardly. But sometimes\n%it is even faster (and much more accurate) than the Matlab built-in function quad:\n% f = @(x)(sinh(exp(x))), a = 0; b = 5; \n% tic, Approx = quad(f,a,b), toc, \n% tic, Incl = verifyquad(f,a,b), toc\n%produces\n% f = \n% @(x)(sinh(exp(x)))\n% Warning: Maximum function count exceeded; singularity likely.\n% > In quad at 100\n% Approx =\n% 3.3124e+032\n% Elapsed time is 0.281967 seconds.\n% intval Incl = \n% 1.0e+061 *\n% 9.6709\n% Elapsed time is 0.161995 seconds.\n%\n%Note that verifyquad is almost twice as fast, and the approximate value is off\n% by several orders of magnitude. But a warning is given.\n%It may also happen that no warning is given:\n% f = @(x)(sin(x+exp(x))), a = 0; b = 8; \n% tic, Approx = quad(f,a,b), toc, \n% tic, Incl = verifyquad(f,a,b), toc\n% f = \n% @(x)(sin(x+exp(x)))\n% Approx =\n% 0.2511\n% Elapsed time is 0.178671 seconds.\n% intval Incl = \n% 0.3474\n% Elapsed time is 1.125084 seconds.\n%\n%Note, however, that the approximate value is only correct to one figure, and no warning is given.\n%\n%Based on Romberg's rule with error term by\n% F. L. Bauer, H. Rutishauser, and E. Stiefel: New Aspects in Numerical Quadrature, \n% Proc. Symp. Appl. Math. Vol. XV, AMS 1963, pp. 198-218.\n%\n\n% written 05/29/09 S.M. Rump\n% modified 11/30/09 S.M. Rump function check and vectorize\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 % store standard function exception mode\n RealStdFctsExcptnMode = intvalinit('RealStdFctsExcptn',0);\n intvalinit('RealStdFctsExcptnNaN',0);\n\n % Convert to inline function as needed\n try\n if isa(funfcn,'function_handle')\n strfun = fcnchk(eval(vectorize(funfcn)),length(varargin));\n else\n strfun = fcnchk(vectorize(funfcn),length(varargin));\n end\n catch\n strfun = fcnchk(funfcn,length(varargin));\n end\n\n if ( nargin<4 ) | isempty(tol)\n tol = 1e-6; % default (absolute) tolerance 1e-6\n end\n tol = max(tol,1e-16); % avoid tiny tolerances\n D = intval(b)-a; % inclusion of b-a\n if ( nargin<5 ) | isempty(see)\n see = 0;\n end\n if ( nargin<6 ) | isempty(mmax)\n mmax = 4; % up to 2*mmax+2 derivatives\n end\n if mmax>16\n warning('maximum order of Romberg scheme is mmax=16.')\n mmax = 16;\n end\n \n % store warning mode\n wng = warning;\n warning off\n \n I = infsup(-inf,inf);\n relerrold = inf;\n kmin = max(5,mmax); % start with at least 2^kmin subintervals\n \n % bounds for taylor^(2*m+2) for m=1..mmax\n xi = linspace(a,b,17);\n TF_ = feval(strfun,taylorinit(infsup(xi(1:end-1),xi(2:end)),2*mmax+2),varargin{:});\n if any(isnan(TF_.t(:))) | any(isinf(TF_.t(:))) % second try with many subintervals\n xi = linspace(a,b,1025);\n TF_ = feval(strfun,taylorinit(infsup(xi(1:end-1),xi(2:end)),2*mmax+2),varargin{:});\n end\n if any(isnan(TF_.t(:))) | any(isinf(TF_.t(:))) % derivative calculation failed\n X = feval(strfun,xi,varargin{:});\n if any(isnan(X(:))) | any(isinf(X(:)))\n error('function evaluation failed over interval [a,b]')\n else\n error('evaluation of higher derivatives failed, try smaller maximum order')\n end\n end\n for m=1:mmax\n TF{m} = infsup(min(TF_{2*m+2}.inf),max(TF_{2*m+2}.sup));\n end\n if see\n disp(['Inclusions of ' int2str(mmax) '-th derivative'])\n TF{mmax}\n end\n \n % first T{kmin..kmin-mmax+1}(m) for m=1\n k = kmin+1;\n h = 2^(-k)*D; % inclusion of (b-a)/2^k\n Xi = a + ( (0:2^k)*(2^(-k)) ) * D; % inclusion of grid points a+i*(b-a)/2^k\n w = [ 1 repmat([4 2],1,2^(k-1)) ]; % no rounding errors\n w(end) = 1;\n y = feval(strfun,Xi,varargin{:})/3;\n T{k-1}(1) = h * sum(w.*y);\n for j=1:m-1\n w = w(1:(2^(k-j)+1));\n w(end) = 1;\n h = 2*h; % inclusion of (b-a)/2^k\n T{k-j-1}(1) = h * sum(w.*y(1:2^j:end));\n end\n \n % create tableaux up to mmax\n for m=2:mmax\n for k=kmin-mmax+1:kmin-m+1\n T{k}(m) = ( 4^m*T{k+1}(m-1) - T{k}(m-1) ) / ( 4^m-1 );\n end\n end\n \n % first error term for m=1 [ B(m) = +/- Bernoulli(2*m+2) ]\n B = intval([1 1 1 5 691 7 3617 43867 174611 854513 236364091 8553103 ...\n 23749461029 8615841276005 7709321041217 2577687858367]) ./ ...\n [30 42 30 66 2730 6 510 798 330 138 2730 6 870 14322 510 6];\n m = mmax;\n k = kmin-m+1;\n E = 2^(-2*k*(m+1)-m*(m+1)) * TF{m}*D^(2*m+3);\n err = B(m)*E;\n I = T{k}(m) - err;\n if see\n disp('First inclusion')\n I\n end\n \n % initialize Romberg iteration\n if in(0,I)\n relerrI = diam(I);\n else\n relerrI = relerr(I);\n end\n j = 0;\n \n while ( relerrI>tol ) & ( relerrIrelerrold\n I = Iold;\n k = k-1;\n end\n \n % restore warning and exception mode\n warning(wng)\n % restore out-of-range exception mode\n intvalinit(RealStdFctsExcptnMode,0);\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/intval/verifyquad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6470129662926987}} {"text": "function fe2d_d_fast_test ( )\n\n%*****************************************************************************80\n%\n%% FE2D_D_FAST_TEST tests the FE2D_D_FAST code.\n%\n% Discussion:\n%\n% This function sets all parameter values and initial condition information\n% necessary to execute the \"fast\" version of the fe2d_d algorithm.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 28 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Reference:\n%\n% Marcus R Garvie, John Burkardt, Jeff Morgan,\n% Simple Finite Element Methods for Approximating Predator-Prey Dynamics\n% in Two Dimensions using MATLAB,\n% Submitted to Bulletin of Mathematical Biology, 2014.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2D_D_FAST_TEST:\\n' );\n fprintf ( 1, ' Test the FE2D_D_FAST function\\n' );\n fprintf ( 1, ' which applies Dirichlet boundary conditions as it\\n' );\n fprintf ( 1, ' approximates a solution to a predator-prey system.\\n' );\n%\n% Set the parameters.\n%\n alpha = 0.4;\n beta = 2.0;\n gamma = 0.6;\n delta = 1.0;\n%\n% Use T=150.0 for normal run.\n% Use T=0.50 for a \"quick\" run that might take 15 minutes of computing.\n%\n% T = 150.0;\n T = 0.50;\n delt = 1.0 / 384.0;\n\n t = tic;\n fe2d_d_fast ( alpha, beta, gamma, delta, T, delt, @u0f, @v0f, @guf, @gvf );\n t = toc ( t );\n\n fprintf ( 1, ' Execution took %10.2g minutes \\n', t / 60.0 );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FE2D_D_FAST_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n\nfunction value = u0f ( x, y )\n\n%*****************************************************************************80\n%\n%% U0F evaluates the initial condition for U.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for U at (X,Y).\n%\n value = 6.0 / 35.0 - 2.0E-07 * ( x - 0.1 * y - 225.0 ) * ( x - 0.1 * y - 675.0 );\n\n return\nend\n\nfunction value = v0f ( x, y )\n\n%*****************************************************************************80\n%\n%% V0F evaluates the initial condition for V.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 26 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location in the region.\n%\n% Output, real VALUE, the initial condition for V at (X,Y).\n%\n value = 116.0 / 245.0 - 3.0E-05 * ( x - 450.0 ) - 1.2E-04 * ( y - 150.0 );\n\n return\nend\n\nfunction value = guf ( x, y, t )\n\n%*****************************************************************************80\n%\n%% GUF evaluates the Dirichlet boundary condition for U.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 28 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location on the boundary.\n%\n% Input, real T, the time.\n%\n% Output, real VALUE, the prescribed value for U at (X,Y,T).\n%\n value = 0.0;\n\n return\nend\nfunction value = gvf ( x, y, t )\n\n%*****************************************************************************80\n%\n%% GVF evaluates the Dirichlet boundary condition for V.\n%\n% Licensing:\n%\n% Copyright (C) 2014 Marcus R. Garvie. \n% See 'mycopyright.txt' for details.\n%\n% Modified:\n%\n% 28 April 2014\n%\n% Author:\n%\n% Marcus R. Garvie. \n%\n% Parameters:\n%\n% Input, real X, Y, a location on the boundary.\n%\n% Input, real T, the time.\n%\n% Output, real VALUE, the prescribed value for V at (X,Y,T).\n%\n value = 0.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fe2d_predator_prey_fast/fe2d_d_fast_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6470129399594688}} {"text": "%% RATE OF CONVERGENCE OF BILINEAR FINITE ELEMENT METHOD\n%\n% This example is to show the rate of convergence of bilinear finite\n% element approximation of the Poisson equation on the unit square with the\n% following boundary conditions:\n%\n% - Non-empty Dirichlet boundary condition.\n% - Pure Neumann boundary condition.\n% - Robin boundary condition.\n%\n% The basis, data structure and numerical test is summarized in PoissonQ1femrate.\n%\n% See also Poissonfemrate, Poissonafemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear variable\n%% Setting\n[node,elem] = squarequadmesh([0,1,0,1],1/2^3); \nmesh = struct('node',node,'elem',elem);\noption.L0 = 2;\noption.maxIt = 4;\noption.printlevel = 1;\noption.plotflag = 0;\noption.elemType = 'Q1';\n\n%% Non-empty Dirichlet boundary condition.\npde = sincosdata;\nmesh.bdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nfemPoisson(mesh,pde,option);\n\n%% Pure Neumann boundary condition.\npde = sincosNeumanndata;\nmesh.bdFlag = setboundary(node,elem,'Neumann');\nfemPoisson(mesh,pde,option);\n\n%% Pure Robin boundary condition.\noption.plotflag = 0;\npde = sincosRobindata;\nmesh.bdFlag = setboundary(node,elem,'Robin');\nfemPoisson(mesh,pde,option);\n\n%% Conclusion\n% To do:\n% 1. Fix the getH1errorQ1. The H1 error is computed wrong.\n% 2. For pure Neuman boundary condition, the rate is not quite right.", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Poisson/PoissonQ1femrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6470000507042389}} {"text": "function [operator_pt]=pt(operator, partition, dimensions)\n%returns the partial transpose of the operator 'operator' with respect to \n%the particles indicated by a one in the binary vector 'partition'.\n%the optional parameter 'dimensions' includes the dimensions of the systems\n%in array form. per default, it is assumed that each system is a qubit.\n\n%otherwise, number of systems is given by the length of 'dimensions'\nn=size(partition);\nn=n(2);\n\nif (nargin == 2) \n %if 'dimensions' are not given, assume qubits, i.e. always dimension 2\n dimensions = 2*ones(1,n);\nelse\n %throw an error if 'partion' and 'dimensions' have different length\n if (max(size(partition) ~= size(dimensions))==1)\n error('partition array and dimensions have different length');\n end\nend\n\n%throw an error if 'operator' is not a square matrix\nopdims=size(operator);\nif (opdims(1) ~= opdims(2))\n error('first argument is no square matrix');\nend\n\n%throw an error if 'operator' is not hermitian (within a certain precision)\nif (max(max(abs(ctranspose(operator)-operator))) > 1e-12)\n error('first argument is not hermitian');\nend\n\n%throw an error if any value in 'dimensions' is smaller than two\nif (min(dimensions)<2)\n error('dimensions must be larger than 1');\nend\n\n\nif (max(dimensions)==min(dimensions))\n %if all particles have the same dimension, we can simply use another\n %numerical system, e.g. the binary system. this speeds things up when\n %compared to the case in which the systems have different dimensions\n \n %obtain the dimensionality of each system (equals the first system's\n %dimensionsality, since all are the same)\n dim = dimensions(1);\n \n %throw an error if operator dimensions do not match the length of\n %'partition'\n if (opdims(1) ~= dim^n)\n error('operator dimensions do not match the partition array');\n end\n \n %******************* this is the main part *******************\n %start with the zero matrix to build up the partially transposed\n %operator\n oppt = zeros(dim^n,dim^n);\n \n %define the identity on the space of 'operator'\n id=eye(size(operator));\n \n for rowind=1:opdims(1) %loop through rows ...\n for colind=(rowind+1):opdims(2) %... and columns of the operator\n %due to hermiticity and invariance of trace \n %under partial transpose, only loop through \n %upper right half\n col=dec2base(colind-1,dim,n); %determine current row and ...\n row=dec2base(rowind-1,dim,n); %column index in the base given by\n %'dimensions'\n \n %determine new row and column index by transposing the systems\n %indicated by 'partition'\n \n %for the new column index, take the ith digit from col if \n %partition(i) is zero. if partition(i) is one, take the ith\n %digit of row ...\n newcol=transpose((1-partition(:)).*str2num(col(:))+partition(:).*str2num(row(:)));\n %... and vice versa for the new row index\n newrow=transpose((1-partition(:)).*str2num(row(:))+partition(:).*str2num(col(:)));\n \n %note that newrow and newcol are row vectors. therefore,\n %convert them into strings and drop the white spaces\n newcol=strrep(num2str(newcol),' ','');\n newrow=strrep(num2str(newrow),' ','');\n \n %convert row and column index back into the decimal system\n newcolind=base2dec(newcol,dim)+1;\n newrowind=base2dec(newrow,dim)+1;\n \n %add the matrix element on its new place to oppt \n oppt=operator(rowind,colind)*(id(:,newrowind)*id(newcolind,:))+oppt;\n end\n end\n \n %add elements due to hermiticity\n oppt=oppt+ctranspose(oppt);\n %add diagonal elements (which did not change through the partial\n %transposition)\n oppt = oppt + diag(diag(operator));\n \nelse \n %if the system has different dimensions, the program is a bit more complex\n %and slower\n \n %throw an error if operator dimensions do not match the length of\n %'partition'\n if (opdims(1) ~= prod(dimensions))\n error('operator dimensions do not match the partition array');\n end\n \n %******************* this is the other main part *******************\n \n %start with the zero matrix to build up the partially transposed\n %operator\n oppt = zeros(size(operator));\n \n %define the identity on the space of 'operator'\n id=eye(size(operator));\n %define the n x n - identity\n idnxn=eye(n,n);\n \n %to loop through all matrix elements of 'operator', we need to create\n %the indices strings of the basis vectors in the usual notation. now, \n %however, the different digits run from zero to the corresponding \n %system's dimension (minus one), which differs from system to system.\n indices=zeros(n,1); %first index has only zeros\n \n for k=1:opdims(1) %loop through whole matrix 'operator'\n inddims=size(indices); \n last = indices(:,inddims(2)); %get the last index string\n\n for l=n:-1:1 %loop through digits of last index string\n if (last(l) < dimensions(l)-1) %the first digit from the right\n %which is still smaller than the\n %dimension (minus one) ...\n newvec=last+idnxn(:,l); %... must be increased by one ...\n newvec=newvec.*(vertcat(ones(l,1),zeros(n-l,1))); % ... and\n %all digits to the right set to zero\n indices=horzcat(indices,newvec); %append new index string\n break;\n end\n end\n end\n \n for rowind=1:opdims(1) %loop through rows ...\n for colind=(rowind+1):opdims(2) %... and columns of the operator\n %due to hermiticity and invariance of trace \n %under partial transpose, only loop through \n %upper right half\n col=indices(:,colind); %write current row and ...\n row=indices(:,rowind); %column index as index string.\n %this time, row and col are column\n %vectors\n \n %determine new row and column index by transposing the systems\n %indicated by 'partition'\n \n %for the new column index, take the ith digit from col if \n %partition(i) is zero. if partition(i) is one, take the ith\n %digit of row ...\n newcol=transpose((1-partition(:)).*col(:)+partition(:).*row(:));\n %... and vice versa for the new row index\n newrow=transpose((1-partition(:)).*row(:)+partition(:).*col(:));\n \n %since newrow and newcol are row vectors denoting an index\n %string, we need to convert them back to a decimal number that\n %denotes the element's new position\n newcolind=find(ismember(transpose(indices),newcol,'rows'));\n newrowind=find(ismember(transpose(indices),newrow,'rows'));\n \n %add the matrix element on its new place to oppt \n oppt=operator(rowind,colind)*(id(:,newrowind)*id(newcolind,:))+oppt;\n end\n end\n \n %build the partial transpose of 'operator'\n %elements that used to be in the upper right half\n %oppt=full(sparse(colarray,rowarray,valarray,dim^n,dim^n,((dim^n)^2)/2-(dim^n)/2));\n %add elements due to hermiticity\n oppt=oppt+ctranspose(oppt);\n %add diagonal elements (which did not change through the partial\n %transposition)\n oppt = oppt + diag(diag(operator));\nend\n\noperator_pt=oppt;", "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/30968-pptmixer-a-tool-to-detect-genuine-multipartite-entanglement/pt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6470000283239323}} {"text": "%[2006]-\"Ant Colony Optimization\"\n\n% (9/12/2020)\n\nfunction ACS = jAntColonySystem(feat,label,opts)\n% Parameters\ntau = 1; % pheromone value\neta = 1; % heuristic desirability\nalpha = 1; % control pheromone\nbeta = 1; % control heuristic\nrho = 0.2; % pheromone trail decay coefficient\nphi = 0.5; % pheromena coefficient\n\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'tau'), tau = opts.tau; end \nif isfield(opts,'alpha'), alpha = opts.alpha; end \nif isfield(opts,'beta'), beta = opts.beta; end \nif isfield(opts,'rho'), rho = opts.rho; end \nif isfield(opts,'eta'), eta = opts.eta; end \nif isfield(opts,'phi'), phi = opts.phi; end \n\n% Objective function\nfun = @jFitnessFunction; \n% Number of dimensions\ndim = size(feat,2); \n% Initial Tau & Eta \ntau = tau * ones(dim,dim); \neta = eta * ones(dim,dim);\n% Pre\nfitG = inf; \nfit = zeros(1,N);\ntau0 = tau;\n\ncurve = inf; \nt = 1; \n% Iterations\nwhile t <= max_Iter\n\t% Reset ant\n\tX = zeros(N,dim); \n\tfor i=1:N\n % Set number of features\n num_feat = randi([1,dim]);\n % Ant start with random position\n X(i,1) = randi([1,dim]); \n k = [];\n if num_feat > 1\n for d = 2:num_feat\n % Start with previous tour\n k = [k(1:end), X(i, d-1)];\n % Edge / Probability Selection (4)\n P = (tau(k(end),:) .^ alpha) .* (eta(k(end),:) .^ beta); \n % Set selected position = 0 probability (4)\n P(k) = 0; \n % Convert probability (4)\n prob = P ./ sum(P(:)); \n % Roulette Wheel selection\n route = jRouletteWheelSelection(prob);\n % Store selected position to be next tour\n X(i,d) = route;\n end\n end\n end\n % Binary\n X_bin = zeros(N,dim);\n for i = 1:N\n % Binary form\n ind = X(i,:); \n ind(ind == 0) = [];\n X_bin(i, ind) = 1;\n end\n % Binary version\n for i = 1:N\n % Fitness\n fit(i) = fun(feat,label,X_bin(i,:),opts);\n % Global update\n if fit(i) < fitG\n Xgb = X(i,:);\n fitG = fit(i); \n end\n end\n % Tau update \n tour = Xgb; \n tour(tour == 0) = []; \n tour = [tour(1:end), tour(1)];\n for d = 1 : length(tour) - 1\n % Feature selected\n x = tour(d);\n y = tour(d + 1);\n % Delta tau\n Dtau = 1 / fitG;\n % Update tau (10)\n tau(x,y) = (1 - phi) * tau(x,y) + phi * Dtau; \n end\n % Evaporate pheromone (9)\n tau = (1 - rho) * tau + rho * tau0;\n % Save\n curve(t) = fitG;\n fprintf('\\nIteration %d Best (ACS)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features based on selected index\nSf = unique(Xgb);\nSf(Sf == 0) = [];\nsFeat = feat(:,Sf); \n% Store results\nACS.sf = Sf;\nACS.ff = sFeat;\nACS.nf = length(Sf);\nACS.c = curve; \nACS.f = feat;\nACS.l = label;\nend\n \n\n%// Roulette Wheel Selection //\nfunction Index = jRouletteWheelSelection(prob)\n% Cummulative summation\nC = cumsum(prob);\n% Random one value, most probability value [0~1]\nP = rand();\n% Route wheel\nfor i = 1:length(C)\n\tif C(i) > P\n Index = i;\n break;\n end\nend\nend \n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jAntColonySystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6469945890519141}} {"text": "%% Weighted optimization for CP tensor decomposition with incomplete data\n% We explain how to use |cp_wopt| with the POBLANO toolbox. \n\n%% Create an example problem with missing data. \n% Here we have 25% missing data and 10% noise. \nR = 2;\ninfo = create_problem('Size', [15 10 5], 'Num_Factors', R, ...\n 'M', 0.25, 'Noise', 0.10);\nX = info.Data;\nP = info.Pattern;\nM_true= info.Soln;\n\n%% Create initial guess using 'nvecs'\nM_init = create_guess('Data', X, 'Num_Factors', R, ...\n 'Factor_Generator', 'nvecs');\n\n\n%% Set up the optimization parameters\n% It's genearlly a good idea to consider the parameters of the optimization\n% method. The default options may be either too stringent or not stringent\n% enough. The most important options to consider are detailed here. \n\n% Get the defaults\nncg_opts = ncg('defaults');\n% Tighten the stop tolerance (norm of gradient). This is often too large.\nncg_opts.StopTol = 1.0e-6;\n% Tighten relative change in function value tolearnce. This is often too large.\nncg_opts.RelFuncTol = 1.0e-20;\n% Increase the number of iterations. \nncg_opts.MaxIters = 10^4;\n% Only display every 10th iteration\nncg_opts.DisplayIters = 10;\n% Display the final set of options\nncg_opts\n\n%% Call the |cp_wopt| method\n% Here is an example call to the cp_opt method. By default, each iteration\n% prints the least squares fit function value (being minimized) and the\n% norm of the gradient. The meaning of any line search warnings\n% can be checked via .\n[M,~,output] = cp_wopt(X, P, R, 'init', M_init, ...\n 'alg', 'ncg', 'alg_options', ncg_opts);\n\n%% Check the output\n% It's important to check the output of the optimization method. In\n% particular, it's worthwhile to check the exit flag. \n% A zero (0) indicates successful termination with the gradient smaller\n% than the specified StopTol, and a three (3) indicates a successful\n% termination where the change in function value is less than RelFuncTol.\n% The meaning of any other flags can be checked via \n% . \nexitflag = output.ExitFlag\n\n\n%% Evaluate the output\n% We can \"score\" the similarity of the model computed by CP and compare\n% that with the truth. The |score| function on ktensor's gives a score in\n% [0,1] with 1 indicating a perfect match. Because we have noise, we do\n% not expect the fit to be perfect. See for more details.\nscr = score(M,M_true)\n\n%% Create a SPARSE example problem with missing data. \n% Here we have 95% missing data and 10% noise. \nR = 2;\ninfo = create_problem('Size', [150 100 50], 'Num_Factors', R, ...\n 'M', 0.95, 'Sparse_M', true, 'Noise', 0.10);\nX = info.Data;\nP = info.Pattern;\nM_true= info.Soln;\n\n%% Create initial guess using 'nvecs'\nM_init = create_guess('Data', X, 'Num_Factors', R, ...\n 'Factor_Generator', 'nvecs');\n\n\n%% Set up the optimization parameters\n% It's genearlly a good idea to consider the parameters of the optimization\n% method. The default options may be either too stringent or not stringent\n% enough. The most important options to consider are detailed here. \n\n% Get the defaults\nncg_opts = ncg('defaults');\n% Tighten the stop tolerance (norm of gradient). This is often too large.\nncg_opts.StopTol = 1.0e-6;\n% Tighten relative change in function value tolearnce. This is often too large.\nncg_opts.RelFuncTol = 1.0e-20;\n% Increase the number of iterations. \nncg_opts.MaxIters = 10^4;\n% Only display every 10th iteration\nncg_opts.DisplayIters = 10;\n% Display the final set of options\nncg_opts\n\n%% Call the |cp_wopt| method\n% Here is an example call to the cp_opt method. By default, each iteration\n% prints the least squares fit function value (being minimized) and the\n% norm of the gradient. The meaning of any line search warnings\n% can be checked via .\n[M,~,output] = cp_wopt(X, P, R, 'init', M_init, ...\n 'alg', 'ncg', 'alg_options', ncg_opts);\n\n%% Check the output\n% It's important to check the output of the optimization method. In\n% particular, it's worthwhile to check the exit flag. \n% A zero (0) indicates successful termination with the gradient smaller\n% than the specified StopTol, and a three (3) indicates a successful\n% termination where the change in function value is less than RelFuncTol.\n% The meaning of any other flags can be checked via \n% . \nexitflag = output.ExitFlag\n\n\n%% Evaluate the output\n% We can \"score\" the similarity of the model computed by CP and compare\n% that with the truth. The |score| function on ktensor's gives a score in\n% [0,1] with 1 indicating a perfect match. Because we have noise, we do\n% not expect the fit to be perfect. See for more details.\nscr = score(M,M_true)\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/doc/T3_wopt_algorithms_doc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6469945826170747}} {"text": "function [D,X,Err] = simplestNMF(Y, opts)\n [n,T] = size(Y);\n \n if nargin<2\n opts = struct();\n end\n opts = initialize_opts(Y, opts);\n D = opts.D0;\n X = opts.X0;\n \n iter = 0;\n Err = zeros(opts.max_iter, 1);\n lambda_factor = repmat(opts.lambda.*ones(opts.m,1), 1, T);\n\n\n %% ----- Preprocess [start] -----\n nmflib_in_options.metric_type = opts.metric_type; \n nmflib_in_options.verbose = opts.verbose;\n nmflib_in_options.x_init.W = D;\n nmflib_in_options.x_init.H = X; \n nmflib_in_options.d_beta = opts.d_beta;\n [D, X, ~, nmflib_infos, nmflib_options] = pre_process('simplestNMF', Y, nmflib_in_options);\n % other necessary processes should be inserted here.\n %% ----- Preprocess [end] -----\n\n while iter < opts.max_iter\n iter = iter + 1;\n\n %update D\n if ~isempty(opts.updateD)\n %DX = D(:, opts.updateD)*X(opts.updateD, :);\n DX = D*X;\n if opts.d_beta<2\n DX(DX==0) = eps;\n end\n pgradD = (DX.^(opts.d_beta-1))*X(opts.updateD, :)';\n pgradD(pgradD==0)=eps;\n ngradD = ((DX.^(opts.d_beta-2)).*Y)*X(opts.updateD, :)';\n D(:, opts.updateD) = D(:, opts.updateD) .* ngradD ./ pgradD;\n end \n \n %update X\n DX = D*X;\n if opts.d_beta<2\n DX(DX==0) = eps;\n end\n pgradX = D'*(DX.^(opts.d_beta-1));\n ngradX = D'*((DX.^(opts.d_beta-2)).*Y);\n X = X .* ngradX ./ (pgradX + lambda_factor);\n \n\n \n DX = D*X;\n DX(DX==0) = eps;\n Err(iter) = beta_divergence(Y, DX, opts.d_beta);\n %sparsy = sum(sum(lambda_factor.*X));\n delta = inf;\n if iter>1\n delta = (Err(iter-1)-Err(iter))/Err(iter-1);\n end\n\n\n %% ----- Innerprocess [start] -----\n nmflib_infos = inner_process('simplestNMF', Y, D, X, [], nmflib_options, nmflib_infos, iter); \n %% ----- Innerprocess [end] ----- \n\n %fprintf('iter = %d, Err = %f, delta = %f, sparsy = %f\\n', iter, Err(iter), delta, sparsy);\n %if delta < opts.conv_value\n % break;\n %end\n end\n Err(iter+1:end) = []; \nend\n\nfunction opts = initialize_opts(Y, opts)\n [n, T] = size(Y);\n if ~isfield(opts, 'm') opts.m = 1; end\n if ~isfield(opts, 'conv_value') opts.conv_value = 1e-3; end\n if ~isfield(opts, 'max_iter') opts.max_iter = 1000; end\n if ~isfield(opts, 'lambda') opts.lambda = eps; end\n if ~isfield(opts, 'beta') opts.d_beta = 2; end\n if ~isfield(opts, 'updateD') opts.updateD = 1:opts.m; end\n if ~isfield(opts, 'D0') opts.D0 = rand(n, opts.m); end\n if ~isfield(opts, 'X0') opts.X0 = rand(opts.m, T); end\nend\n\n\nfunction r = beta_divergence(A, B, beta)\n switch beta\n case 0\n r = sum(sum (A./B - log(A./B+eps) - 1));\n case 1\n r = sum(sum(A.*log(A./B+eps) - A + B));\n case 2\n r = .5 * norm(A - B, 'fro').^2;\n end\nend", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/applications/audio_denoise/simplestNMF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6469695772143049}} {"text": "function [output binarizedContour] = CORF(I, sigma, t)\n% CORF Contour detection based on a computational model of a simple cell.\n%\n% VERSION 22/04/2012\n% CREATED BY: George Azzopardi and Nicolai Petkov, University of Groningen,\n% Johann Bernoulli Institute for Mathematics and Computer Science, Intelligent Systems\n%\n%If you use this script please cite the following paper:\n% George Azzopardi and Nicolai Petkov, \"A CORF computational model of a\n% simple cell that relies on LGN input outperforms the Gabor function\n% model\", 2012, DOI: 10.1007/s00422-012-0486-6\n% \n% CORF achieves orientation selectivity by combining the output - at certain \n% positions with respect to the center of the CORF operator - of center-on \n% and center-off difference of Gaussians (DoG) functions by a weighted geometric mean. \n%\n% CORF takes as input:\n% I -> intensity image\n% sigma -> the standard deviation of the outer Gaussian function of the \n% DoG operator\n% t -> high threshold used for hysteresis thresholding\n%\n% CORF returns:\n% output -> maximum superposition of CORF responses that correspond to 12 orientations\n% binarizedContour -> A contour map that is obtaiend by first thinning\n% output and then performs hysteresis thresholding \n% with a high threshold t and a low threshold that \n% is a fraction 0.5 of the given t.\n%\n% Example: [o bc] = CORF(imread('rino.pgm'),2.5,0.3);\n%\n% The image rino.pgm is taken from the RuG data set of 40 images of\n% natural scenes, which can be downloaded from:\n% http://www.cs.rug.nl/~imaging/databases/contour_database/contour_database.html\n\n% configure CORF operator\noperator = configureCORF(sigma,0.5);\n\n% Set number of orientations\nnoriens = 12;\norienslist = 0:180/noriens:359;\n\n% Preprocessing\ninputImage = double(I);\nif ndims(inputImage) == 3\n inputImage = double(rgb2gray(inputImage));\nend\nif max(inputImage(:)) > 1\n inputImage = inputImage ./ 255;\nend\n\n% Apply difference of Gaussians function.\npadwidth = ceil(max(operator.params.rho));\nDoGresponse(:,:,1) = applyDoG(inputImage, 0, padwidth, operator.params.sigma, operator.params.sigmaRatio, 0); \nDoGresponse(:,:,2) = -DoGresponse(:,:,1); \nDoGresponse(:,:,1) = DoGresponse(:,:,1) .* (DoGresponse(:,:,1) > 0);\nDoGresponse(:,:,2) = DoGresponse(:,:,2) .* (DoGresponse(:,:,2) > 0);\n\n% Apply the CORF oeprator at different orientations\ndata = [];\noutput = zeros(size(DoGresponse,1),size(DoGresponse,2),noriens);\nfor rot = 1:length(orienslist)\n rotatedOperator = operator;\n rotatedOperator.tuple(4,:) = rotatedOperator.tuple(4,:) + orienslist(rot)*pi/180; \n [output(:,:,rot) data] = getCORFresponse(DoGresponse,rotatedOperator,data);\nend\noutput = output(padwidth+1:end-padwidth,padwidth+1:end-padwidth,:);\n\n% Merge output of all orientations by using maximum superposition\n[output, oriensMatrix] = calc_viewimage(output,1:size(output,3), orienslist*pi/180); \n\n% Perform thinning\nthinningOutput = thinning(output, oriensMatrix, 2); \n\n%Perform hysteresis thresholding\nt = t * max(thinningOutput(:));\nbinarizedContour = hysthresh(thinningOutput, t, 0.5*t);\n\nfunction [output data] = getCORFresponse(DoGresponse,operator,data)\n\nsz = [size(DoGresponse,1),size(DoGresponse,2)];\n\nif isempty(data)\n data.params = []; \n data.tupleOutput = cell(0);\n data.location = [];\n data.paramsindex = 1;\n data.current.tupleOutput = zeros(sz(1),sz(2),size(operator.tuple,2)); \nend\n\n% The weight vector is requried for the computation of the weighted\n% geometric mean at the bottom of the function.\nweightVector = zeros(1,size(operator.tuple,2));\nsgm = max(operator.tuple(3,:)) / 3;\n\nfor i = 1:size(operator.tuple,2) \n polarity = operator.tuple(1,i);\n rho = operator.tuple(3,i);\n phi = operator.tuple(4,i);\n \n weightVector(i) = (exp(-rho^2/(2*sgm*sgm))); \n \n mem = find(ismember(data.params,[polarity rho],'rows'),1); \n if ~isempty(mem)\n % This tuple output is obtained by appropriate shifting of another\n % tuple output that was computed for the same values of polarity,\n % sigma and rho.\n [col row] = pol2cart(phi,rho);\n shiftrow = -(data.location{mem}(1)-fix(row));\n shiftcol = data.location{mem}(2)-fix(col);\n data.current.tupleOutput(:,:,i) = circshift(data.tupleOutput{mem},[shiftrow,shiftcol]); \n else\n DoG = DoGresponse(:,:,polarity+1); \n data.params(data.paramsindex,:) = [polarity rho]; \n [col row] = pol2cart(phi,rho);\n\n r = (operator.params.d0 + operator.params.alpha*rho)/2;\n if r > 0\n smoothfilter = fspecial('gaussian',round([2*r+1,2*r+1]),r/3);\n data.current.tupleOutput(:,:,i) = conv2(DoG,smoothfilter,'same');\n data.current.tupleOutput(:,:,i) = circshift(data.current.tupleOutput(:,:,i),[fix(row),fix(-col)]);\n else\n data.current.tupleOutput(:,:,i) = DoG;\n end\n data.current.tupleOutput(:,:,i) = data.current.tupleOutput(:,:,i) .^ weightVector(i);\n \n % We use the following variables to reuse the computations obtained\n % for the same values of parameters: polarity, sigma and rho.\n data.tupleOutput{data.paramsindex} = data.current.tupleOutput(:,:,i);\n data.location{data.paramsindex} = [round(row) round(col)];\n data.paramsindex = data.paramsindex + 1;\n end \nend\n\n% compute the weighted geometric mean\noutput = prod(data.current.tupleOutput,3).^(1/sum(weightVector));\n\nfunction operator = configureCORF(sigma, sigmaRatio)\n% configureCORF: configure a CORF operator for the given parameters.\n\n% The parameters alpha and d0 are set as reported in the above mentioned paper\noperator.params.alpha = 0.9;\noperator.params.d0 = 2;\n\noperator.params.sigma = sigma;\noperator.params.sigmaRatio = sigmaRatio;\n\n% The following are the rho values that were used in the experiments\n% reported in the above mentioned paper.\nif sigma >= 1 && sigma < 2.5\n operator.params.rho = [14.38 6.9796 3.0310 1.4135];\nelseif sigma >= 2.5 && sigma < 4\n operator.params.rho = [3.0515 6.1992 12.6488 24.62];\nelseif sigma >= 4 && sigma <= 5\n operator.params.rho = [3.3021 4.7877 9.2467 18.08 34.43];\nelse\n error('The value of the parameter sigma is out of bounds');\nend\n\nmaxRadius = ceil(max(operator.params.rho))+1;\nstimulus = zeros((2*maxRadius));\nstimulus(:,1:maxRadius) = 1;\ncenter = [maxRadius maxRadius];\n\n%Obtain the output of DoG function for the synthetic edge stimulus\nDoGresponse(:,:,1) = applyDoG(stimulus, 0, maxRadius, sigma, sigmaRatio, 1);\nDoGresponse(:,:,2) = -DoGresponse(:,:,1);\nDoGresponse(:,:,1) = DoGresponse(:,:,1) .* (DoGresponse(:,:,1) > 0);\nDoGresponse(:,:,2) = DoGresponse(:,:,2) .* (DoGresponse(:,:,2) > 0);\n\noperator.tuple = [];\nfor r = 1:length(operator.params.rho)\n [polarity rho phi] = getTuple(DoGresponse,operator.params.rho(r),center); \n operator.tuple = [operator.tuple [polarity; repmat(sigma,1,length(polarity)); rho; phi]]; \nend\n\nfunction [polarity rho phi] = getTuple(DoGresponse,radius,fp) \n% Determine the values of the polar coordinates (rho,phi)\n\nif radius <= 0\n error('Parameter radius must be greater than 0');\nend\n\nphi = []; polarity = [];\nx = 1:360;\n\nfor pol = 1:size(DoGresponse,3) \n DoG = DoGresponse(:,:,pol);\n y = DoG(sub2ind(size(DoG),round(fp(1) + radius*cos(pi/2+x*pi/180)),round(fp(2) + radius*sin(pi/2+x*pi/180))));\n \n % Threshold low values\n y(y < 0.1*max(DoGresponse(:))) = 0; \n y = round(y*1000)/1000;\n \n BW = bwlabel(imregionalmax(y));\n npeaks = max(BW(:)); \n\n for i = 1:npeaks\n phi(end+1) = mean(x(BW == i)) * pi/180;\n polarity(end+1) = pol - 1; \n end \nend\nrho = repmat(radius,1,length(phi));\n\nfunction output = applyDoG(inputImage,polarity,padwidth,sigma,sigmaRatio,crop)\n\n% pad input image\npaddedInputImage = padarray(inputImage,[padwidth padwidth],'both','symmetric');\n\n% create DoG operator\nsz = size(inputImage) + padwidth + padwidth; \ng1 = fspecial('gaussian',sz,sigma);\ng2 = fspecial('gaussian',sz,sigma*sigmaRatio);\nif polarity == 1\n DoG = g2 - g1; \nelseif polarity == 0\n DoG = g1 - g2;\nelse\n error('Polarity must be either 0 (on) or 1 (off)');\nend\n\n% compute DoG\noutput = fftshift(ifft2(fft2(DoG,sz(1),sz(2)) .* fft2(paddedInputImage)));\n\nif crop == 1\n output = output(padwidth+1:end-padwidth,padwidth+1:end-padwidth);\nend\n\nfunction [result, oriensMatrix] = calc_viewimage(matrices, dispcomb, theta)\n% VERSION 14/05/04\n% CREATED BY: M.B. Wieling and N. Petkov, Groningen University,\n% Department of Computer Science, Intelligent Systems\n%\n% CALC_VIEWIMAGE: calculates the maximum-superposition of all the matrices stored\n% in MATRICES (according to the L-infinity norm). It uses only the matrices for\n% which the index is entered in DISPCOMB, e.g. if DISPCOMB contains the values\n% 1,2,4: only the first, second and fourth matrix contained in MATRICES are used\n% for the superposition. This method also calculates the orientationmatrix (ORIENSMATRIX) \n% which stores the maximum orientation response of each point in the resulting matrix\n% (RESULT) - for use in CALC_THINNING. A progressbar of the calculations is also shown. \n% CALC_VIEWIMAGE(MATRICES, DISPCOMB, THETA) \n% calculates the single viewing image according to the following parameters\n% MATRICES - the matrices which hold all the convolutions for each orientation\n% DISPCOMB - the indexes of each matrix (in MATRICES) which should be used for the\n% superposition \n% THETA - a list of all the orientations - to create ORIENSMATRIX\n\n% initialize values\noriensMatrix = 0;\ntmpMaxConv = -Inf;\nresult = -Inf;\ncnt1 = 1;\n\nif (size(dispcomb,2) == 1)\n result = matrices(:,:,dispcomb(1));\nelse\n\n % calculate the superposition (L-infinity norm)\n while (cnt1 <= size(dispcomb,2))\n % calculate the maximum orientation-response in each point (based on the absolute values)\n oriensMatrixtmp1 = (abs(matrices(:,:,dispcomb(cnt1))) > tmpMaxConv) .* theta(dispcomb(cnt1));\n oriensMatrixtmp2 = (abs(matrices(:,:,dispcomb(cnt1))) <= tmpMaxConv) .* oriensMatrix;\n oriensMatrix = oriensMatrixtmp1 + oriensMatrixtmp2;\n tmpMaxConv = max(abs(matrices(:,:,dispcomb(cnt1))), tmpMaxConv);\n \n % calculate the superposition\n result = max(result,abs(matrices(:,:,dispcomb(cnt1))));\n cnt1 = cnt1 + 1;\n end\nend\n \nfunction result = thinning(matrix, oriensMatrix, method)\n% VERSION 27/02/05\n% CREATED BY: M.B. Wieling and N. Petkov, Groningen University,\n% Department of Computer Science, Intelligent Systems\n%\n% THINNING: reduces the edges to a width of 1 pixel. This is done \n% by looking at the two pixels next to the current pixel.\n% the neighbourpixels are determined by the orientation of \n% the current point (this is stored in the exact same location\n% as in the matrix ORIENSMATRIX). A progressbar of the\n% calculations is also shown. \n% THINNING(MATRIX, ORIENSMATRIX, METHOD) thins the edge\n% MATRIX - the matrix which should be thinned\n% ORIENSMATRIX - the matrix which holds for every pixel of MATRIX the\n% orientation (in the same position)\n% METHOD - the method of thinning: METHOD == 1: simple method, just\n% take the value of the nearest pixels to compare with.\n% e.g. if the orientation = 20 degrees, the points S & N are chosen\n% to compare to, if the orientation = 25 degrees the points SW & NE\n% are chosen (see below, P = current point)\n% NW N NE\n% W P E\n% SW S SE\n% METHOD == 2: the values to compare with are calculated using\n% interpolation based on the surrounding pixels (NW, N, NE, E, SE, S, SW, W) \n%\n% corrected an error: (5/8)*pi); \n dy = ((orien > (1/8)*pi) & (orien <= (1/2)*pi)) - ((orien > (1/2)*pi) & (orien < (7/8)*pi));\n\n % normally the same pixels would be checked if (dy and dx > 0) and (dy and dx < 0). because\n % different pixels should be checked with a gabor-orientation of 45 and 135 this difference should\n % be checked\n if (dy < 0) & (dx < 0)\n result(I,J) = ((matrixB(I,J) >= matrixB(I+dy, J+dx)) & (matrixB(I,J) >= matrixB(I-dy, J-dx))) * matrixB(I,J); \n else\n result(I,J) = ((matrixB(I,J) >= matrixB(I-dy, J+dx)) & (matrixB(I,J) >= matrixB(I+dy, J-dx))) * matrixB(I,J); \n end \n end\n end\nelse % linear thinning\n %hb = waitbar(0,'Applying linear thinning, please wait ... (Step 6/7)'); % display a progressbar\n result = 0;\n for I=2:h+1 % the rows\n for J=2:w+1 % the columns\n orien = oriensMatrixB(I,J);\n % get the values of the surrounding pixels\n north = matrixB(I-1, J); \n northeast = matrixB(I-1, J+1); \n east = matrixB(I, J+1);\n southeast = matrixB(I+1, J+1);\n south = matrixB(I+1, J);\n southwest = matrixB(I+1, J-1);\n west = matrixB(I, J-1);\n northwest = matrixB(I-1, J-1);\n \n % calculate the value of the points in one line (using interpolation)\n if (orien <= (1/4)*pi)\n fraction = orien/((1/4)*pi);\n pnt1 = (1-fraction) * east + (fraction) * northeast;\n pnt2 = (1-fraction) * west + (fraction) * southwest; \n elseif (orien <= (1/2)*pi)\n fraction = (orien-(1/4)*pi)/((1/4)*pi);\n pnt1 = (1-fraction) * northeast + (fraction) * north; \n pnt2 = (1-fraction) * southwest + (fraction) * south;\n elseif (orien <= (3/4)*pi)\n fraction = (orien-(1/2)*pi)/((1/4)*pi);\n pnt1 = (1-fraction) * north + (fraction) * northwest;\n pnt2 = (1-fraction) * south + (fraction) * southeast;\n elseif (orien <= pi)\n fraction = (orien-(3/4)*pi)/((1/4)*pi);\n pnt1 = (1-fraction) * northwest + (fraction) * west;\n pnt2 = (1-fraction) * southeast + (fraction) * east;\n else\n orien\n end\n result(I,J) = ( (matrixB(I,J) >= pnt1) & (matrixB(I,J) >= pnt2) ) * matrixB(I,J);\n end\n %waitbar(I/h); % update the progressbar\n end\n %close(hb);\nend\n\n% removing the borders\nresult = result(2:h+1, 2:w+1); \n\nfunction bw = hysthresh(im, T1, T2)\n% HYSTHRESH - Hysteresis thresholding\n%\n% Usage: bw = hysthresh(im, T1, T2)\n%\n% Arguments:\n% im - image to be thresholded (assumed to be non-negative)\n% T1 - upper threshold value\n% T2 - lower threshold value\n%\n% Returns:\n% bw - the thresholded image (containing values 0 or 1)\n%\n% Function performs hysteresis thresholding of an image.\n% All pixels with values above threshold T1 are marked as edges\n% All pixels that are adjacent to points that have been marked as edges\n% and with values above threshold T2 are also marked as edges. Eight\n% connectivity is used.\n%\n% It is assumed that the input image is non-negative\n%\n% Author: Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au http://www.csse.uwa.edu.au/~pk \n%\n% December 1996 - Original version\n% March 2001 - Speed improvements made (~4x)\n\n%\n% A stack (implemented as an array) is used to keep track of all the\n% indices of pixels that need to be checked.\n% Note: For speed the number of conditional tests have been minimised\n% This results in the top and bottom edges of the image being considered to\n% be connected. This may cause some stray edges to be propagated further than \n% they should be from the top or bottom.\n%\n\nif (T2 > T1 | T2 < 0 | T1 < 0) % Check thesholds are sensible\n error('T1 must be >= T2 and both must be >= 0 ');\nend\n\n[rows, cols] = size(im); % Precompute some values for speed and convenience.\nrc = rows*cols;\nrcmr = rc - rows;\nrp1 = rows+1;\n\nbw = im(:); % Make image into a column vector\npix = find(bw > T1); % Find indices of all pixels with value > T1\nnpix = size(pix,1); % Find the number of pixels with value > T1\n\nstack = zeros(rows*cols,1); % Create a stack array (that should never\n % overflow!)\n\nstack(1:npix) = pix; % Put all the edge points on the stack\nstp = npix; % set stack pointer\nfor k = 1:npix\n bw(pix(k)) = -1; % mark points as edges\nend\n\n\n% Precompute an array, O, of index offset values that correspond to the eight \n% surrounding pixels of any point. Note that the image was transformed into\n% a column vector, so if we reshape the image back to a square the indices \n% surrounding a pixel with index, n, will be:\n% n-rows-1 n-1 n+rows-1\n%\n% n-rows n n+rows\n% \n% n-rows+1 n+1 n+rows+1\n\nO = [-1, 1, -rows-1, -rows, -rows+1, rows-1, rows, rows+1];\n\nwhile stp ~= 0 % While the stack is not empty\n v = stack(stp); % Pop next index off the stack\n stp = stp - 1;\n \n if v > rp1 & v < rcmr % Prevent us from generating illegal indices\n\t\t\t % Now look at surrounding pixels to see if they\n % should be pushed onto the stack to be\n % processed as well.\n index = O+v;\t % Calculate indices of points around this pixel.\t \n for l = 1:8\n\t ind = index(l);\n\t if bw(ind) > T2 % if value > T2,\n\t stp = stp+1; % push index onto the stack.\n\t stack(stp) = ind;\n\t bw(ind) = -1; % mark this as an edge point\n\t end\n end\n end\nend\n\nbw = (bw == -1); % Finally zero out anything that was not an edge \nbw = reshape(bw,rows,cols); % and reshape the image", "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/36304-contour-detection-by-corf-operator/CORF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6469695697766148}} {"text": "function S = matsignt(T)\n%MATSIGNT Matrix sign function of a triangular matrix.\n% S = MATSIGN(T) computes the matrix sign function S of the\n% upper triangular matrix T using a recurrence.\n\n% Called by SIGNM.\n\nif ~isequal(T,triu(T)), error('Matrix must be upper triangular.'), end\n\nn = length(T);\n\nS = diag( sign( diag(real(T)) ) );\nfor p = 1:n-1\n for i = 1:n-p\n\n j = i+p;\n d = T(j,j) - T(i,i);\n\n if S(i,i) ~= -S(j,j) % Solve via S^2 = I if we can.\n\n % Get S(i,j) from S^2 = I.\n k = i+1:j-1;\n S(i,j) = -S(i,k)*S(k,j) / (S(i,i)+S(j,j));\n\n else\n\n % Get S(i,j) from S*T = T*S.\n s = T(i,j)*(S(j,j)-S(i,i));\n if p > 1\n k = i+1:j-1;\n s = s + T(i,k)*S(k,j) - S(i,k)*T(k,j);\n end\n S(i,j) = s/d;\n\n end\n\n end\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/utilities/matrixcomp/matsignt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6469291987619811}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n% \n% \n% \n\n% problem 6 - convolution of x(t) and h(t) \n\n\nt1=0:.1:2;\nt2=2.1:.1:4;\nt3=4.1:.1:10;\nx1=t1;\nx2=4-t2;\nx3=zeros(size(t3));\nx=[x1 x2 x3];\nt=0:.1:10;\nh=t.*exp(-t);\ny=conv(x,h)*0.1;\nplot(0:.1:20,y);\ntitle('System response y(t)')\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/4/c412f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.7461390043208004, "lm_q1q2_score": 0.6469291985293204}} {"text": "function [x_world] = Robot2World(x_robot,x)\n %% Change of coordinates from robot fram to world frame\n\n x_world = zeros(size(x));\n for i = 1:size(x,2)\n x_world(1,i) = cos(x_robot(3))*(x(1,i)) - sin(x_robot(3))*(x(2,i)) + x_robot(1);\n x_world(2,i) = cos(x_robot(3))*(x(2,i)) + sin(x_robot(3))*(x(1,i)) + x_robot(2);\n end\nend\n\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/Robot2World.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.646863343694222}} {"text": "% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz\n\n\n%GEOMETRICAL PARAMETERS\n\nclear;\n\n%Length from the bearing to the hinge\nl0 = 27.5;\n\n%Length of the vertical wall that supports the hinge\nh0 = 6.5;\n\n%Lenght of the vertical support of the bearing\nhb = 4.0;\n\n%Bearing radius\nbr = 1.1;\n\n%Array of different max and min positions of the bearing\nh1a = [6.5, 7.1, 7.7, 8.3, 8.9];\nh2a = [20.5, 20.5, 20.5, 20.5, 20.5];\n\n%Number of cycles per cam turn (1 to 3).\nnc = 1;\n\n%Minimum radius of the camshaft\nrmin = 5;\n\n\n%BREATHING CYCLE PARAMETERS\n\n%Duration of the inhale cycle / duration of the whole cycle\nlambda1 = 0.500;\nlambda2 = 0.04;\n\n%Soft transition between inhale and exhale cycles\ndpsi21 = 0.05;\ndpsi12 = 0.04;\n\n%Adjust parameters of the inhale curve\nga1 = 3.1;\ngb1 = .85;\nff1 = 50;\n\n%Adjust parametes of the exhale curve\nga2 = 3.1;\ngb2 = .80;\nff2 = 50;\n\n\n%GENERATION OF THE CURVES AND THE CAMSHAFT\n\n%Generation of the geometry\n\nl = sqrt(l0^2+hb^2);\n\n\nfor i = 1:numel(h1a);\n \n ymin(i) = h1a(i);\n ymax(i) = h2a(i);\n \n alphamin(i) = acos((h0 - h1a(i)) / l);\n alphamax(i) = acos((h0 - h2a(i)) / l);\n \n xmin(i) = l*sin(alphamin(i)); \n xmax(i) = l*sin(alphamax(i));\n \n d(i) = sqrt((xmin(i)-xmax(i))^2 + (ymin(i)-ymax(i))^2);\n \n alphatan(i) = (alphamin(i) + alphamax(i)) / 2;\n \n xtan(i) = l*sin(alphatan(i)); \n ytan(i) = h0 - l*cos(alphatan(i));\n \n xsup(i) = xtan(i) + (d(i)/2)*cos(alphatan(i));\n xinf(i) = xtan(i) - (d(i)/2)*cos(alphatan(i));\n \n ysup(i) = ytan(i) + (d(i)/2)*sin(alphatan(i));\n yinf(i) = ytan(i) - (d(i)/2)*sin(alphatan(i));\n \n xcam(i) = xtan(i) + (d(i)/2 + rmin + br)*cos(alphatan(i));\n ycam(i) = ytan(i) + (d(i)/2 + rmin + br)*sin(alphatan(i));\n \nend;\n\n\n%Time increment\ndt = 0.01;\n\n%time coordinate during the whole cycle\ntheta = 0:dt:2*pi;\n\n%Generation of the soft transition between inhale and exhale curves\npsi1 = [];\npsi2 = [];\n\nfor i = 1:numel(theta);\n \n if theta(i) < (lambda2-dpsi21/2)*2*pi;\n psi1(i) = 0;\n \n elseif theta(i) < (lambda2+dpsi21/2)*2*pi;\n psi1(i) = 0.5 + 0.5*cos((theta(i)-(lambda2+dpsi21/2)*2*pi)/(2*dpsi21));\n \n else theta(i) < (lambda1-dpsi12/2)*2*pi;\n psi1(i) = 1;\n \n end;\n \n psi2(i) = 1 - psi1(i);\n \nend; \n\n\n%Generation of the complete breathing cycle rho(theta)\n\nrho = [];\nrho1 = [];\nrho2 = [];\nrho2next = [];\n\nrhomin = 1000;\nrhomax = 0;\n\nfor i = 1:numel(theta);\n \n %Inhale curve\n rho1(i) = ff1*gampdf(theta(i), ga1, gb1);\n rho1next(i) = ff1*gampdf(theta(i)+2*pi, ga1, gb1);\n \n %Exhale curve\n rho2(i) = ff2*gampdf(theta(i), ga2, gb2);\n rho2next(i) = ff2*gampdf(theta(i)+2*pi, ga2, gb2);\n \n \n rho(i) = max(rho1(i), rho1next(i));\n \n \n %Capturing min and max in order to generate the normalized curve\n if rho(i) > rhomax\n rhomax = rho(i);\n end;\n \n if rho(i) < rhomin\n rhomin = rho(i);\n end;\n\nend;\n\n\n%Generation of a normalised curve and camshaft\n\nrhonorm = [];\nrhocam = [];\n\nfor i = 1:numel(theta);\n \n rhonorm(i) = (rho(i)-rhomin)/(rhomax-rhomin);\n \n for n = 1:numel(d)\n \n rhocam(n,i) = rmin + rhonorm(i)*d(n);\n \n end;\n \nend;\n\n\n%Generation of the first derivate of the camshaft geometry to analize and\n%validate the design\n\ndrho = [];\ndrhonorm = [];\ndrhocam = [];\n\na = rmin;\nb = 1/dt;\n\nfor i = 1 : numel(rho)-1;\n \n drho(i) = b*(rho(i+1)-rho(i));\n drhonorm(i) = b*(rhonorm(i+1)-rhonorm(i));\n drhocam(i) = b*(rhocam(i+1)-rhocam(i)) + a;\n \nend;\n\ndrho(numel(rho)) = b*(rho(1)-rho(numel(rho)));\ndrhonorm(numel(rhonorm)) = b*(rhonorm(1)-rhonorm(numel(rhonorm)));\ndrhocam(numel(rhocam)) = b*(rhocam(1)-rhocam(numel(rhocam))) + a;\n\n\n%X and Y coordinates during two cycles (for 2-cycle camshaft plot)\n\ntheta2 = [theta/2, (2*pi+theta)/2];\n\nrhocam2 = [rhocam, rhocam];\ndrhocam2 = [drho, drho];\n\n\n%X and Y coordinates during three cycles (for 3-cycle camshaft plot)\n\ntheta3 = [theta/3, (2*pi+theta)/3, (4*pi+theta)/3];\n\nrhocam3 = [rhocam, rhocam, rhocam];\ndrhocam3 = [drho, drho, drho];\n\n\n\n%GENERATION OF THE PLOTS\n\n%Trying to print it out in real size (FAIL)\n%set(gcf,'PaperUnits','centimeters'); \n%set(gcf,'PaperSize',[42 29.7]);\n\n\nfpos = figure('Name', 'Dimensions', 'Units', 'centimeters', 'NumberTitle', 'off');\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 28, 20]);\nfpos = gcf;\nhold on\n\nxlim([-5 35]);\nylim([0 30]);\n\nfor i = 1:numel(xmin)\n \n plot([0, xmin(i)], [h0, ymin(i)], '-x') \n plot([0, xmax(i)], [h0, ymax(i)], '-x')\n \n plot([0, xtan(i)], [h0, ytan(i)], '--xb')\n \n plot([xsup(i), xinf(i)], [ysup(i), yinf(i)], '--xr')\n scatter(xcam(i), ycam(i))\n\nend;\n\nhold off\n\n\n\n\n%Plot of the breathing cycle interpolation by curves\n\nfcycle = figure('Name', 'Breath Cycle curves', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, psi1, '-k')\nplot(theta, psi2, '-k')\nplot(theta, rho1, '-g')\nplot(theta, rho1next, '-g')\nplot(theta, rho2, '-g')\nplot(theta, rho2next, '-g')\n%plot(theta, drho, '-r')\nplot(theta, rho, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of the normalized breathing cycle and first derivate\n\n\nfnorm = figure('Name', 'Normalized Breath Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\n%plot(theta, drhonorm, '-r')\nplot(theta, rhonorm, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 1-cycle camshaft\n\nfor n = 1:numel(d)\n\n fcam1 = figure('Name', '1-Cycle Camshaft', 'Units', 'centimeters', 'NumberTitle', 'off');\n %hold on\n \n %polarplot(theta, drhocam, '-r')\n polar(theta, rhocam(n,:), '-b')\n\n \n %rlim([0 25]);\n hold off\n\n set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n fcam3 = gcf;\n \nend\n\n\n% %Plot of a 2-cycle camshaft\n% \n% fcam2 = figure('Name', '2-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta, drhocam2, '-r')\n% polar(theta2, rhocam2, '-b')\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n% \n% \n% %Plot of a 3-cycle camshaft\n% \n% fcam3 = figure('Name', '3-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta,drhocam3)\n% polar(theta3, rhocam3)\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n\n% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz", "meta": {"author": "ProtofyTeam", "repo": "OxyGEN", "sha": "8a2870695e01928c07af2cc73ed86e5e53d8f726", "save_path": "github-repos/MATLAB/ProtofyTeam-OxyGEN", "path": "github-repos/MATLAB/ProtofyTeam-OxyGEN/OxyGEN-8a2870695e01928c07af2cc73ed86e5e53d8f726/Matlab Files/V9/Respirador_V6.1_1_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6468633416941529}} {"text": "clear all\n % Desemnarea unor variabile simbolice\nsyms x u v t\n % Generarea unei functii de o variabila\nf=sin(x)^3;\n % Deschiderea unei ferestre grafice noi\nfigure(1)\n % Reprezentarea functiei f intre limitele implicite\nezplot(f)\n % Reprezentarea functiei f intre limitele [0, 8*pi]\nfigure(2)\nezplot(f,[0,8*pi])\n % Generarea unei functii de doua variabile\ng=u^2-v^2+1;\n % Reprezentarea functiei g de doua variabile intre limitele date\nfigure(3)\nezplot(g,[-2,2,-5,5])\n % Generarea unei functii parametrice\nx=sin(t);\ny=cos(t);\n % Reprezentarea functiei parametrice intre limitele impuse\nfigure(4)\nezplot(x,y)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8416-widely-used-programming-environments-in-electrical-engineering-matlab/12/Ex_12_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6468633370580498}} {"text": "% Chemical master equation for 2H + O <-> H2O\n\nL = 7; % QTT dimension in state variables\n\nTrange = 0:0.5:5;\nd0ts = 12*ones(1,numel(Trange)-1);\n\ntol = 1e-7;\neps = 1e-12;\n\n% initial distribution\nl = [13,15,0]; % H, O, H2O\n\n% One shift z=-1 (for O)\nS1 = tt_shf(L);\nS2 = round(S1*S1, eps); % double shift z=-2 (for H)\n% z=1 for H2O will be S1'\n\nI = tt_eye(2,3*L);\ne1 = tt_tensor(num2cell([1;0]*ones(1,L), 1));\ne2 = zeros(2^L,1); e2(2)=1; e2 = tt_tensor(reshape(e2, 2*ones(1,L)),eps);\n\nx = tt_x(2,L);\no = tt_ones(2,L);\n\nw1 = 2*mtkron(o-e1-e2, o-e1, o);\nw2 = 1*mtkron(o, o, o-e1);\n% w = mtkron(x, x, o);\n\n% CME matrix\nA = -(mtkron(S2,S1,S2')*diag(w1) - diag(w1)); % forward\nA = A - (mtkron(S2',S1',S2)*diag(w2) - diag(w2)); % backward\nA = round(A, eps);\n\n% initial state\ne1 = zeros(2^L,1); e1(l(1)+1)=1;\nu0 = tt_tensor(e1);\ne1 = zeros(2^L,1); e1(l(2)+1)=1;\nu0 = tkron(u0, tt_tensor(e1));\ne1 = zeros(2^L,1); e1(l(3)+1)=1;\nu0 = tkron(u0, tt_tensor(e1));\n% make QTT\nu0 = tt_reshape(u0, 2*ones(1,3*L), eps);\n\nNt = numel(Trange)-1;\nu = u0;\nll = zeros(Nt, 3);\ntic;\nfor t=1:Nt\n d0t = d0ts(t);\n tau = (Trange(t+1)-Trange(t))/(2^d0t);\n \n Grad_t = IpaS(d0t,-1)/tau;\n% CN_term = IpaS(d0t,1)*0.5; % Crank-Nicolson\n CN_term = tt_eye(2,d0t); % Backw Euler\n e1t = tt_tensor(num2cell([1;0]*ones(1,d0t), 1));\n et = tt_ones(2, d0t);\n \n M = tkron(I, Grad_t)+tkron(A, CN_term);\n \n rhs = u/tau; %-0.5*A*u;\n rhs = tkron(rhs, e1t);\n U = tkron(u, et);\n \n U = amen_solve2(M, rhs, tol, 'x0', U);\n \n % Extract the final solution\n ext = tt_unit(2,d0t,2*ones(d0t,1));\n u = dot(ext, U, 3*L+1, U.d);\n \n mass = dot(u, tt_ones(u.n))\n u = u/mass;\n \n u2 = tt_reshape(u, 2^L*ones(1,3));\n % It should be the delta-function\n % Find the final distribution\n [v,l]=tt_stat(u2, 'lm');\n l=l-1\n ll(t,:)=l;\nend\ntoc;\n\nsp = zeros(2^L, 4);\nfor z=1:2^L\n [v,l]=tt_stat(u2(:,:,z), 'lm');\n if (v>tol)\n sp(z, 1)=l(1)-1;\n sp(z, 2)=l(2)-1;\n sp(z, 3)=z-1;\n sp(z, 4)=log2(v);\n else\n sp(z,:)=NaN;\n end\nend\nz = z-1;\nscatter3(sp(1:z,1), sp(1:z,2), sp(1:z,3), 100, sp(1:z,4), 'filled');\nxlabel('H');\nylabel('O');\nzlabel('H2O');\ntitle('log2(P)');\ncolorbar;\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tests/test_h2o.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6468633263295643}} {"text": " function [w0, phi] = adw_fan_new(sg, ig, wi)\n%function [w0, phi] = adw_fan_new(sg, ig, wi)\n%\n% Compute the angular-dependent weighting for fan-beam geometry.\n% w0(\\Phi) = w(x0, y0, \\Phi)\n% For fully corrected penalty:\n%\tw(s',\\beta') * J(s') | \\phi'=\\Phi + ...\n%\tw(s',\\beta') * J(s') | \\phi'=\\Phi-pi\n% See fessler chapter 3.5.3 (?).\n% Useful for regularization design and variance prediction.\n%\n% in:\n%\tsg\tsino_geom()\n%\tig\timage_geom()\n%\twi\t[nb,na] var(yi)\n% out:\n%\tw0\t[np,na] angular-dependent weighting, np = sum(ig.mask(:))\n%\n% Copyright 2005-4-07, Yingying Zhang & Jeff Fessler, The University of Michigan\n\nif nargin == 1 && streq(sg, 'test'), adw_fan_test, return, end\nif nargin < 3, ir_usage, end\n\n[x y] = ndgrid(ig.x, ig.y); % image domain pixel locations\n\nr0 = sqrt(x.^2 + y.^2);\nphi0 = atan2(y,x); % use it for our purpose since atan will have pi flip\n% [phi0 r0] = cart2pol(x,y);\n% image domain dummy variables for polar coordinates\n\n% dummy variables in freq. domain\nphi = sg.ar;\n\n% sinogram domain locations\nbeta = sg.ar; % angles in radians\ngamma = sg.s / sg.dsd;\n\n% loop over \\phi_i\nDcf = sg.dsd + sg.dfs;\nratio_fcf = sg.dfs / Dcf;\n% w0 = zeros(ig.nx, ig.ny, sg.na);\nw0 = zeros([size(r0(ig.mask),1) sg.na]);\n\nticker reset\nfor ia = 1:sg.na\n\tticker(mfilename, ia, sg.na)\n\n\t% -------------------------\n\t% for \\phi' = \\phi\n\t% -------------------------\n\t\n\t% compute new variables in (3.5.2)\n\tr_p = r0 .* cos(phi(ia) - phi0); % use beta, not outer_sum(gamma, beta)\n%\tsince evaluate at \\phi_p = \\phi(view angle)\n%\tr_p = x .* cos(phi(ia)) + y .* sin(phi(ia));\n\ts_p = Dcf .* (asin(r_p / sg.dso) - asin(ratio_fcf .* r_p / sg.dso));\n\tbeta_p = phi(ia) - asin(r_p / sg.dso);\n\t\n\t% compute Jacobian determinant (2.7.9)\n\tJacob_p = abs(sg.dso * cos(s_p / sg.dsd) - ...\n\tsg.offset * sin(s_p / sg.dsd)) / sg.dsd;\n\t\n\t% find corresponding wi: nearest neighbor method\n\ts_cen = sg.w;\n\t% caution: this looks wrong!!! (sg.nb + 1)/2 + ob.offset_s; % for nb = even % <-----(yy) plus:(to me account for the right index) or (hugo) minus?\n\ts_loc = round(s_p / sg.d + s_cen);\n\ts_loc = min(s_loc, sg.nb);\n\ts_loc = max(s_loc, 1);\n\tbeta_loc = round((mod(beta_p,2*pi)-deg2rad(sg.orbit_start)) / (2*pi/sg.na)) + 1;\n\tbeta_loc = min(beta_loc, sg.na);\n\tbeta_loc = max(beta_loc, 1);\n\n\t% find the corresponding index in column-stack wi\n\tloc = 1 + (s_loc(:)-1) + (beta_loc(:)-1)*sg.nb;\n\n\t% compute w0 at \\phi' = \\phi\n%\tw0(:,:,ia) = w0(:,:,ia) + reshape(wi(loc(:)), [ig.nx ig.ny]) .* (1 ./ Jacob_p);\n\twi_temp = wi(loc(:));\n\twi_p = wi_temp(ig.mask);\n\tJacob = 1 ./ Jacob_p(ig.mask);\n\tw0(:,ia) = wi_p .* Jacob;\n\t\n\tclear s_loc beta_loc loc\n\n\t% -------------------------\n\t% for \\phi' = \\phi - pi\n\t% -------------------------\n\tphi_pi = phi(ia) - pi;\n\tr_p = r0 .* cos(phi_pi - phi0);\n%\tr_p = x .* cos(phi(ia)) + y .* sin(phi(ia));\n\ts_p = Dcf .* (asin(r_p / sg.dso) - asin(ratio_fcf .* r_p / sg.dso));\n\tbeta_p = phi_pi - asin(r_p / sg.dso);\n\t\n\t% Jacob_p again: not needed since same\n%\tJacob_p = abs(sg.dso*cos(s_p / sg.dsd) - ...\n%\tsg.offset * sin(s_p / sg.dsd)) / sg.dsd;\n\t\n\t% find corresponding wi: nearest neighbor method\n\ts_loc = round(s_p / sg.d + s_cen);\n\ts_loc = min(s_loc, sg.nb);\n\ts_loc = max(s_loc, 1);\n\t\n\tbeta_loc = round((mod(beta_p,2*pi)-deg2rad(sg.orbit_start)) / (2*pi/sg.na)) + 1;\n\tbeta_loc = min(beta_loc, sg.na);\n\tbeta_loc = max(beta_loc, 1);\n\t\n\t% find the corresponding index in column-stack wi\n\tloc = 1 + (s_loc(:)-1) + (beta_loc(:)-1)*sg.nb;\n\n\t% compute w0 at \\phi' = \\phi - pi and sum with \\phi' = \\phi\n%\tw0(:,:,ia) = w0(:,:,ia) + reshape(wi(loc(:)), [ig.nx ig.ny]) .* (1 ./ Jacob_p);\n\twi_temp = wi(loc(:));\n\twi_p = wi_temp(ig.mask);\n\tw0(:,ia) = w0(:,ia) + wi_p .* Jacob;\n\n\tclear s_loc beta_loc loc\n\t\n\t% angle_dependent blur\n%\tb0(:,:,ia) = (sg.ds / Dcf) .* sqrt(sg.dso^2 + r0^2 + 2 .* sg.dso .* Dcf .* cos(phi(ia)-phi0));\nend\n\nfunction adw_fan_test\ndown = 8;\nsg = sino_geom('ge1', 'down', down);\nig = image_geom('nx', 512, 'fov', 500, 'down', down);\nwi = sg.ones;\nw0 = adw_fan_new(sg, ig, wi);\nw0 = ig.embed(w0);\nim clf, im(w0(:,:,1:10:end)), cbar\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/adw_fan_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6468391834951869}} {"text": "function value = r8_asin ( x )\n\n%*****************************************************************************80\n%\n%% R8_ASIN evaluates the arc-sine of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the arc-sine of X.\n%\n persistent asincs\n persistent nterms\n persistent sqeps\n\n if ( isempty ( nterms ) )\n asincs = [ ...\n +0.10246391753227159336573148305785E+00, ...\n +0.54946487221245833306011195902924E-01, ...\n +0.40806303925449692851307056149246E-02, ...\n +0.40789006854604435455598823905612E-03, ...\n +0.46985367432203691616048530136218E-04, ...\n +0.58809758139708058986454385552074E-05, ...\n +0.77732312462777632750557528163795E-06, ...\n +0.10677423340082039235047504956587E-06, ...\n +0.15092399536022808262386434401064E-07, ...\n +0.21809724080055385496609614713930E-08, ...\n +0.32075984262789614433261959667376E-09, ...\n +0.47855369646781034461493133918953E-10, ...\n +0.72251287362910432263848754537112E-11, ...\n +0.11018334742255783705372701334987E-11, ...\n +0.16947632539203354877423745651078E-12, ...\n +0.26261558667348224162283241502416E-13, ...\n +0.40958299813281178408828069291110E-14, ...\n +0.64244793108803655891727944887091E-15, ...\n +0.10128142198228221693973361222041E-15, ...\n +0.16039221897380787560050597464746E-16, ...\n +0.25503501355807141715298789676373E-17, ...\n +0.40701403797862382855487165672106E-18, ...\n +0.65172671712881144437889267575466E-19, ...\n +0.10467453037096796954244891716266E-19, ...\n +0.16858725563380328094989095185066E-20, ...\n +0.27221936305040227625164341247999E-21, ...\n +0.44059293900347550617126830079999E-22, ...\n +0.71466685243375937853063168000000E-23, ...\n +0.11615793343859516051798971733333E-23, ...\n +0.18915234552354685801184187733333E-24, ...\n +0.30855772044244342399827968000000E-25, ...\n +0.50416366022162453412970495999999E-26, ...\n +0.82502725502400865081753600000000E-27, ...\n +0.13520032631020947208055466666666E-27, ...\n +0.22184326876541720216644266666666E-28, ...\n +0.36442494054085079212578133333333E-29, ...\n +0.59920218558643813307733333333333E-30, ...\n +0.98584812059573785810261333333333E-31, ...\n +0.16222501166399014393173333333333E-31 ]';\n nterms = r8_inits ( asincs, 39, 0.1 * r8_mach ( 3 ) );\n sqeps = sqrt ( 6.0 * r8_mach ( 3 ) );\n end\n\n y = abs ( x );\n\n if ( x < - 1.0 - sqeps )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_ASIN - Fatal error!\\n' );\n fprintf ( 1, ' X < - 1.0\\n' );\n error ( 'R8_ASIN - Fatal error!' )\n\n elseif ( x < - 1.0 )\n\n value = - 0.5 * pi;\n\n elseif ( x < 1.0 )\n\n z = 0.0;\n if ( sqeps < y )\n z = y * y;\n end\n\n if ( z <= 0.5 )\n value = x * ( 1.0 + r8_csevl ( 4.0 * z - 1.0, asincs, nterms ) );\n else\n value = 0.5 * pi - sqrt ( 1.0 - z ) * ( 1.0 + ...\n r8_csevl ( 3.0 - 4.0 * z, asincs, nterms ) );\n end\n\n if ( x < 0.0 )\n value = - abs ( value );\n elseif ( 0.0 < x )\n value = + abs ( value );\n end\n\n elseif ( x < 1.0 + sqeps )\n\n value = 0.5 * pi;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_ASIN - Fatal error!\\n' );\n fprintf ( 1, ' 1.0 < X\\n' );\n error ( 'R8_ASIN - Fatal error!' )\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_asin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6468391713425499}} {"text": "function out = conwaylaws(nhood)\n%CONWAYLAWS Applies Conway's genetic laws to a single pixel.\n% OUT = CONWAYLAWS(NHOOD) applies Conway's genetic laws to a single\n% pixel and its 3-by-3 neighborhood, NHOOD. \n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\nnum_neighbors = sum(nhood(:)) - nhood(2, 2);\nif nhood(2, 2) == 1\n if num_neighbors <= 1\n out = 0; % Pixel dies from isolation.\n elseif num_neighbors >= 4\n out = 0; % Pixel dies from overpopulation.\n else\n out = 1; % Pixel survives.\n end\nelse\n if num_neighbors == 3\n out = 1; % Birth pixel.\n else\n out = 0; % Pixel remains empty.\n end\nend\n\n", "meta": {"author": "dipum", "repo": "dipum-toolbox", "sha": "9ce653c4c0c4b7c56e46194c24bf152db4ab6832", "save_path": "github-repos/MATLAB/dipum-dipum-toolbox", "path": "github-repos/MATLAB/dipum-dipum-toolbox/dipum-toolbox-9ce653c4c0c4b7c56e46194c24bf152db4ab6832/dipum/conwaylaws.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.646764470958718}} {"text": "function hermite_polynomial_test07 ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_POLYNOMIAL_TEST07 tests HE_QUADRATURE_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_POLYNOMIAL_TEST07:\\n' );\n fprintf ( 1, ' HE_QUADRATURE_RULE computes the quadrature rule\\n' );\n fprintf ( 1, ' associated with He(n,x);\\n' );\n\n n = 7;\n [ x, w ] = he_quadrature_rule ( n );\n\n r8vec2_print ( n, x, w, ' X W' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use the quadrature rule to estimate:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Q = Integral ( -oo < X < +00 ) X^E exp(-X^2) dx\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' E Q_Estimate Q_Exact\\n' );\n fprintf ( 1, '\\n' );\n\n for e = 0 : 2 * n - 1\n if ( e == 0 )\n f = ones ( n, 1 );\n else\n f(1:n) = x(1:n).^e;\n end\n q = w' * f;\n q_exact = he_integral ( e );\n fprintf ( 1, ' %2d %14g %14g\\n', e, q, q_exact );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_polynomial/hermite_polynomial_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.8128673133042216, "lm_q1q2_score": 0.6467644699844917}} {"text": "function M = fixedrankembeddedfactory(m, n, k)\n% Manifold struct to optimize fixed-rank matrices w/ an embedded geometry.\n%\n% function M = fixedrankembeddedfactory(m, n, k)\n%\n% Manifold of m-by-n real matrices of fixed rank k. This follows the\n% embedded geometry described in Bart Vandereycken's 2013 paper:\n% \"Low-rank matrix completion by Riemannian optimization\".\n% \n% Paper link: http://arxiv.org/pdf/1209.3834.pdf\n%\n% A point X on the manifold is represented as a structure with three\n% fields: U, S and V. The matrices U (mxk) and V (nxk) are orthonormal,\n% while the matrix S (kxk) is any /diagonal/, full rank matrix.\n% Following the SVD formalism, X = U*S*V'. Note that the diagonal entries\n% of S are not constrained to be nonnegative.\n%\n% Tangent vectors are represented as a structure with three fields: Up, M\n% and Vp. The matrices Up (mxk) and Vp (mxk) obey Up'*U = 0 and Vp'*V = 0.\n% The matrix M (kxk) is arbitrary. Such a structure corresponds to the\n% following tangent vector in the ambient space of mxn matrices:\n% Z = U*M*V' + Up*V' + U*Vp'\n% where (U, S, V) is the current point and (Up, M, Vp) is the tangent\n% vector at that point.\n%\n% Vectors in the ambient space are best represented as mxn matrices. If\n% these are low-rank, they may also be represented as structures with\n% U, S, V fields, such that Z = U*S*V'. Their are no resitrictions on what\n% U, S and V are, as long as their product as indicated yields a real, mxn\n% matrix.\n%\n% The chosen geometry yields a Riemannian submanifold of the embedding\n% space R^(mxn) equipped with the usual trace (Frobenius) inner product.\n%\n%\n% Please cite the Manopt paper as well as the research paper:\n% @Article{vandereycken2013lowrank,\n% Title = {Low-rank matrix completion by {Riemannian} optimization},\n% Author = {Vandereycken, B.},\n% Journal = {SIAM Journal on Optimization},\n% Year = {2013},\n% Number = {2},\n% Pages = {1214--1236},\n% Volume = {23},\n% Doi = {10.1137/110845768}\n% }\n%\n% See also: fixedrankfactory_2factors fixedrankfactory_3factors\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n%\n%\tFeb. 20, 2014 (NB):\n% Added function tangent to work with checkgradient.\n%\n% June 24, 2014 (NB):\n% A couple modifications following\n% Bart Vandereycken's feedback:\n% - The checksum (hash) was replaced for a faster alternative: it's a\n% bit less \"safe\" in that collisions could arise with higher\n% probability, but they're still very unlikely.\n% - The vector transport was changed.\n% The typical distance was also modified, hopefully giving the\n% trustregions method a better initial guess for the trust region\n% radius, but that should be tested for different cost functions too.\n%\n% July 11, 2014 (NB):\n% Added ehess2rhess and tangent2ambient, supplied by Bart.\n%\n% July 14, 2014 (NB):\n% Added vec, mat and vecmatareisometries so that hessianspectrum now\n% works with this geometry. Implemented the tangent function.\n% Made it clearer in the code and in the documentation in what format\n% ambient vectors may be supplied, and generalized some functions so\n% that they should now work with both accepted formats.\n% It is now clearly stated that for a point X represented as a\n% triplet (U, S, V), the matrix S needs to be diagonal.\n\n M.name = @() sprintf('Manifold of %dx%d matrices of rank %d', m, n, k);\n \n M.dim = @() (m+n-k)*k;\n \n M.inner = @(x, d1, d2) d1.M(:).'*d2.M(:) + d1.Up(:).'*d2.Up(:) ...\n + d1.Vp(:).'*d2.Vp(:);\n \n M.norm = @(x, d) sqrt(M.inner(x, d, d));\n \n M.dist = @(x, y) error('fixedrankembeddedfactory.dist not implemented yet.');\n \n M.typicaldist = @() M.dim();\n \n % Given Z in tangent vector format, projects the components Up and Vp\n % such that they satisfy the tangent space constraints up to numerical\n % errors. If Z was indeed a tangent vector at X, this should barely\n % affect Z (it would not at all if we had infinite numerical accuracy).\n M.tangent = @tangent;\n function Z = tangent(X, Z)\n Z.Up = Z.Up - X.U*(X.U'*Z.Up);\n Z.Vp = Z.Vp - X.V*(X.V'*Z.Vp);\n end\n\n % For a given ambient vector Z, applies it to a matrix W. If Z is given\n % as a matrix, this is straightfoward. If Z is given as a structure\n % with fields U, S, V such that Z = U*S*V', the product is executed\n % efficiently.\n function ZW = apply_ambient(Z, W)\n if ~isstruct(Z)\n ZW = Z*W;\n else\n ZW = Z.U*(Z.S*(Z.V'*W));\n end\n end\n\n % Same as apply_ambient, but applies Z' to W.\n function ZtW = apply_ambient_transpose(Z, W)\n if ~isstruct(Z)\n ZtW = Z'*W;\n else\n ZtW = Z.V*(Z.S'*(Z.U'*W));\n end\n end\n \n % Orthogonal projection of an ambient vector Z represented as an mxn\n % matrix or as a structure with fields U, S, V to the tangent space at\n % X, in a tangent vector structure format.\n M.proj = @projection;\n function Zproj = projection(X, Z)\n \n ZV = apply_ambient(Z, X.V);\n UtZV = X.U'*ZV;\n ZtU = apply_ambient_transpose(Z, X.U);\n\n Zproj.M = UtZV;\n Zproj.Up = ZV - X.U*UtZV;\n Zproj.Vp = ZtU - X.V*UtZV';\n\n end\n\n M.egrad2rgrad = @projection;\n \n % Code supplied by Bart.\n % Given the Euclidean gradient at X and the Euclidean Hessian at X\n % along H, where egrad and ehess are vectors in the ambient space and H\n % is a tangent vector at X, returns the Riemannian Hessian at X along\n % H, which is a tangent vector.\n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, H)\n \n % Euclidean part\n rhess = projection(X, ehess);\n \n % Curvature part\n T = apply_ambient(egrad, H.Vp)/X.S;\n rhess.Up = rhess.Up + (T - X.U*(X.U'*T));\n T = apply_ambient_transpose(egrad, H.Up)/X.S;\n rhess.Vp = rhess.Vp + (T - X.V*(X.V'*T));\n \n end\n\n % Transforms a tangent vector Z represented as a structure (Up, M, Vp)\n % into a structure with fields (U, S, V) that represents that same\n % tangent vector in the ambient space of mxn matrices, as U*S*V'.\n % This matrix is equal to X.U*Z.M*X.V' + Z.Up*X.V' + X.U*Z.Vp'. The\n % latter is an mxn matrix, which could be too large to build\n % explicitly, and this is why we return a low-rank representation\n % instead. Note that there are no guarantees on U, S and V other than\n % that USV' is the desired matrix. In particular, U and V are not (in\n % general) orthonormal and S is not (in general) diagonal.\n % (In this implementation, S is identity, but this might change.)\n M.tangent2ambient = @tangent2ambient;\n function Zambient = tangent2ambient(X, Z)\n Zambient.U = [X.U*Z.M + Z.Up, X.U];\n Zambient.S = eye(2*k);\n Zambient.V = [X.V, Z.Vp];\n end\n \n % This retraction is second order, following general results from\n % Absil, Malick, \"Projection-like retractions on matrix manifolds\",\n % SIAM J. Optim., 22 (2012), pp. 135-158.\n M.retr = @retraction;\n function Y = retraction(X, Z, t)\n if nargin < 3\n t = 1.0;\n end\n\n % See personal notes June 28, 2012 (NB)\n [Qu, Ru] = qr(Z.Up, 0);\n [Qv, Rv] = qr(Z.Vp, 0);\n \n % Calling svds or svd should yield the same result, but BV\n % advocated svd is more robust, and it doesn't change the\n % asymptotic complexity to call svd then trim rather than call\n % svds. Also, apparently Matlab calls ARPACK in a suboptimal way\n % for svds in this scenario.\n % [Ut St Vt] = svds([X.S+t*Z.M , t*Rv' ; t*Ru , zeros(k)], k);\n [Ut, St, Vt] = svd([X.S+t*Z.M , t*Rv' ; t*Ru , zeros(k)]);\n \n Y.U = [X.U Qu]*Ut(:, 1:k);\n Y.V = [X.V Qv]*Vt(:, 1:k);\n Y.S = St(1:k, 1:k) + eps*eye(k);\n \n % equivalent but very slow code\n % [U S V] = svds(X.U*X.S*X.V' + t*(X.U*Z.M*X.V' + Z.Up*X.V' + X.U*Z.Vp'), k);\n % Y.U = U; Y.V = V; Y.S = S;\n \n end\n \n M.exp = @exponential;\n function Y = exponential(X, Z, t)\n if nargin < 3\n t = 1.0;\n end\n Y = retraction(X, Z, t);\n warning('manopt:fixedrankembeddedfactory:exp', ...\n ['Exponential for fixed rank ' ...\n 'manifold not implemented yet. Used retraction instead.']);\n end\n\n % Less safe but much faster checksum, June 24, 2014.\n % Older version right below.\n M.hash = @(X) ['z' hashmd5([sum(X.U(:)) ; sum(X.S(:)); sum(X.V(:)) ])];\n %M.hash = @(X) ['z' hashmd5([X.U(:) ; X.S(:) ; X.V(:)])];\n \n M.rand = @random;\n % Factors U and V live on Stiefel manifolds, hence we will reuse\n % their random generator.\n stiefelm = stiefelfactory(m, k);\n stiefeln = stiefelfactory(n, k);\n function X = random()\n X.U = stiefelm.rand();\n X.V = stiefeln.rand();\n X.S = diag(sort(rand(k, 1), 1, 'descend'));\n end\n \n % Generate a random tangent vector at X.\n % TODO: consider a possible imbalance between the three components Up,\n % Vp and M, when m, n and k are widely different (which is typical).\n M.randvec = @randomvec;\n function Z = randomvec(X)\n Z.Up = randn(m, k);\n Z.Vp = randn(n, k);\n Z.M = randn(k);\n Z = tangent(X, Z);\n nrm = M.norm(X, Z);\n Z.Up = Z.Up / nrm;\n Z.Vp = Z.Vp / nrm;\n Z.M = Z.M / nrm;\n end\n \n M.lincomb = @lincomb;\n \n M.zerovec = @(X) struct('Up', zeros(m, k), 'M', zeros(k, k), ...\n 'Vp', zeros(n, k));\n \n % New vector transport on June 24, 2014 (as indicated by Bart)\n % Reference: Absil, Mahony, Sepulchre 2008 section 8.1.3:\n % For Riemannian submanifolds of a Euclidean space, it is acceptable to\n % transport simply by orthogonal projection of the tangent vector\n % translated in the ambient space.\n M.transp = @project_tangent;\n function Z2 = project_tangent(X1, X2, Z1)\n Z2 = projection(X2, tangent2ambient(X1, Z1));\n end\n\n\n M.vec = @vec;\n function Zvec = vec(X, Z)\n Zamb = tangent2ambient(X, Z);\n Zamb_mat = Zamb.U*Zamb.S*Zamb.V';\n Zvec = Zamb_mat(:);\n end\n M.mat = @(X, Zvec) projection(X, reshape(Zvec, [m, n]));\n M.vecmatareisometries = @() true;\n\nend\n\n% Linear combination of tangent vectors\nfunction d = lincomb(x, a1, d1, a2, d2) %#ok\n\n if nargin == 3\n d.Up = a1*d1.Up;\n d.Vp = a1*d1.Vp;\n d.M = a1*d1.M;\n elseif nargin == 5\n d.Up = a1*d1.Up + a2*d2.Up;\n d.Vp = a1*d1.Vp + a2*d2.Vp;\n d.M = a1*d1.M + a2*d2.M;\n else\n error('fixedrank.lincomb takes either 3 or 5 inputs.');\n end\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/fixedrank/fixedrankembeddedfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6467644617753685}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% function [y,dy] = affine2Dsparse(w,x,varargin)\n%\n% computes y = kron(I2,Q)*w = [w(1),w(2);w(4),w(5)] * x + w([3,6]) \n% and the derivative wrt. w.\n% Q = {[x(:,1),x(:,2),1]}, dy = Q;\n% if no argumanets are given, the parameters for the identity map are returned.\n%\n% see also transformations/contents.m, trafo.m\n%==============================================================================\n\n\nfunction [y,dy] = affine2Dsparse(w,x,varargin)\n\n% the persitent variable stores the matrix \n% Q(x) = kron( I_2 , [x(:,1),x(:,2),1] );\npersistent Q\n\nif nargin == 0, \n runMinimalExample;\n return;\nelse\n y = mfilename('fullfile'); \n dy = [1;0;0;0;1;0]; % parameterization of identity\n if ischar(w), Q = []; w = []; end; % reset Q\n if isempty(w), return; end; \nend;\n\n% test for need of updating Q\nOK = ~any(isempty(Q));\nif OK, \n m1 = size(Q{1}); \n OK = (2*m1(1) == size(x,1)) && (2*m1(2) == numel(w));\nend;\n\nif ~OK,\n n = length(x)/2; \n Q = {[reshape(x,[],2),ones(n,1)]};\n if nargout == 0, return; end;\nend;\n\nw = reshape(w,3,2);\n% mimicing Qfull*w as [Q*w(:,1),Q*w(:,2)]\ny = [Q{1}*w(:,1);Q{1}*w(:,2)];\ndy = Q;\n\n%------------------------------------------------------------------------------\nfunction runMinimalExample\nhelp(mfilename);\nfprintf('%s: minimal example\\n',mfilename)\n\nomega = [0,10,0,2]; m = [8,9];\nw = 22/pi;c = (omega(2:2:end)-omega(1:2:end))'/2;\nR = [ cos(w),-sin(w);sin(w),cos(w)];\ng = (eye(2)-R)*reshape(c,2,1);\nw = [R(1,1);R(1,2);g(1);R(2,1);R(2,2);g(2)]\nx = getNodalGrid(omega,m);\nz = feval(mfilename,w,x);\nt = affine2D(w,x);\nn = norm(z-t);\nfprintf('diff between affine2D and affine2Dsparse is %s\\n',num2str(n));\n\nassert(n<1e-13,'difference to non-sparse version too big')\nFAIRfigure(1); clf;\nplotGrid(x,omega,m,'color','r'); axis image; hold on;\nplotGrid(z,omega,m,'color','b'); axis image; hold off;\n%==============================================================================\n\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/transformations/affine2Dsparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.6467644506226653}} {"text": "function[invmat]=matinv(mat,str)\n%MATINV Fast inversion of arrays of small matrices.\n%\n% MATINV is a low-level function called by POLYSMOOTH.\n% \n% Let MAT be an array of K different M x M matrices A1,A2,...,AK.\n% INV=MATINV(MAT) then returns an array of N inverse matrices.\n% \n% If MAT has dimensions K1 x K2 x .... M x M, then MATINV returns an \n% array of the same size containing the inverses of the M x M matrices.\n%\n% For example, MAT could be 10 x 10 x 4 x 4, in which case the inverses\n% of one hundred 4 x 4 matrices are found.\n%\n% MAT can have any dimensionality so long as the matrices to be inverted\n% occupy the last two dimensions. The last dimension is interpreted as\n% \"columns\" and the second to last as \"rows.\"\n%\n% Note that MATINV only works matrices with M=2 through M=8.\n% ____________________________________________________________\n%\n% Algorithms\n%\n% MATINV can use either of two different algorithms. This is specified\n% with INV=MATINV(MAT,STR). \n% \n% MATINV(MAT,'direct') uses algebraic expressions for 2 x 2 and 3 x 3 \n% matrix inverses together with Boltz's block diagonal recursion formula.\n% For details, see the following links\n%\n% http://mathworld.wolfram.com/MatrixInverse.html\n% http://en.wikipedia.org/wiki/Invertible_matrix.\n%\n% MATINV(MAT,'loop') uses Matlab's INV function together with a \n% straightforward loop.\n%\n% The direct algorithm, which is the default, can be much faster when\n% MAT is large and the dimension to be inverted is small.\n% ____________________________________________________________\n%\n% See also MATMULT.\n%\n% 'matinv --t' runs some tests.\n%\n% Usage: inv=matinv(mat);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2008--2020 J.M. Lilly --- type 'help jlab_license' for details\n \nif strcmpi(mat, '--t')\n matinv_test,return\nend\n\nndims=lnsd(mat);\nK=size(mat,ndims);\n\nif K~=size(mat,ndims-1)\n error('The last two dimensions of MAT must be the same for it to be invertible.')\nend\n\nif nargin==1 \n str='direct';\nend\n\nif K>12\n error('MATINV number of dimensions of matrix should be no more than M=12.')\nend\n\nsizemat=size(mat);\nif length(sizemat)>2\n %[mat,index]=matinv_strip(mat); \n \n if ~isempty(strfind(str,'dir'))\n invmat=matinv_direct(mat,ndims,K);\n elseif ~isempty(strfind(str,'loo'))\n invmat=matinv_loop(mat);\n end\n\nelse\n invmat=inv(mat);\nend\n\n\nfunction[mat,index]=matinv_strip(mat)\n\nsizemat=size(mat);\nmat=reshape(mat,prod(sizemat(1:end-2)),sizemat(end-1),sizemat(end));\nbool=~isnan(sum(sum(mat,3),2));\nindex=find(bool);\nmat=mat(index,:,:);\n\nfunction[invmat]=matinv_loop(mat)\n\nsizemat=size(mat);\nmat=reshape(mat,prod(sizemat(1:end-2)),sizemat(end-1),sizemat(end));\ninvmat=0*mat;\n\n%[lastmsg,lastid]=lastwarn;\nwarning('off','MATLAB:illConditionedMatrix');\nwarning('off','MATLAB:nearlySingularMatrix');\n%warning('off','MATLAB:singularMatrix');\nfor i=1:size(mat,1)\n invmat(i,:,:)=inv(squeeze(mat(i,:,:))); \nend\n\ninvmat=reshape(invmat,sizemat);\nwarning('on','MATLAB:illConditionedMatrix');\nwarning('on','MATLAB:nearlySingularMatrix');\nwarning('on','MATLAB:singularMatrix');\n\nfunction[invmat]=matinv_direct(mat,ndims,K)\n\n%if K==1\n% invmat=1./mat;\nif K==2\n invmat=matinv_twoxtwo(mat,ndims);\nelseif K==3\n invmat=matinv_threexthree(mat,ndims);\nelse\n invmat=matinv_block(mat,ndims,K);\nend\n \nfunction[invmat]=matinv_twoxtwo(mat,ndims)\nac=vindex(mat,1,ndims);\nbd=vindex(mat,2,ndims);\n\na=vindex(ac,1,ndims-1);\nc=vindex(ac,2,ndims-1);\nb=vindex(bd,1,ndims-1);\nd=vindex(bd,2,ndims-1);\n\ndeta=a.*d-b.*c;\na=a./deta;\nb=b./deta;\nc=c./deta;\nd=d./deta;\n\nac=0*ac;\nbd=0*bd;\n\nac=vindexinto(ac,d,1,ndims-1);\nac=vindexinto(ac,-c,2,ndims-1);\n\nbd=vindexinto(bd,-b,1,ndims-1);\nbd=vindexinto(bd,a,2,ndims-1);\n\ninvmat=zeros(size(mat));\ninvmat=vindexinto(invmat,ac,1,ndims);\ninvmat=vindexinto(invmat,bd,2,ndims);\n\nfunction[mat]=matinv_threexthree(mat,ndims)\n\nc1=vindex(mat,1,ndims);\nc2=vindex(mat,2,ndims);\nc3=vindex(mat,3,ndims);\n\na11=vindex(c1,1,ndims-1);\na21=vindex(c1,2,ndims-1);\na31=vindex(c1,3,ndims-1);\n\na12=vindex(c2,1,ndims-1);\na22=vindex(c2,2,ndims-1);\na32=vindex(c2,3,ndims-1);\n\na13=vindex(c3,1,ndims-1);\na23=vindex(c3,2,ndims-1);\na33=vindex(c3,3,ndims-1);\n\nb11=a22.*a33-a23.*a32;\nb21=a23.*a31-a21.*a33;\nb31=a21.*a32-a22.*a31;\n\nb12=a13.*a32-a12.*a33;\nb22=a11.*a33-a13.*a31;\nb32=a12.*a31-a11.*a32;\n\nb13=a12.*a23-a13.*a22;\nb23=a13.*a21-a11.*a23;\nb33=a11.*a22-a12.*a21;\n\ndeta=a11.*b11+a12.*b21+a13.*b31; \n%This looks funny because b21 is minus \n\nb11=b11./deta;\nb21=b21./deta;\nb31=b31./deta;\n\nb12=b12./deta;\nb22=b22./deta;\nb32=b32./deta;\n\nb13=b13./deta;\nb23=b23./deta;\nb33=b33./deta;\n\nclear deta\n\nc1=vindexinto(c1,b11,1,ndims-1);\nc1=vindexinto(c1,b21,2,ndims-1);\nc1=vindexinto(c1,b31,3,ndims-1);\n\nc2=vindexinto(c2,b12,1,ndims-1);\nc2=vindexinto(c2,b22,2,ndims-1);\nc2=vindexinto(c2,b32,3,ndims-1);\n\nc3=vindexinto(c3,b13,1,ndims-1);\nc3=vindexinto(c3,b23,2,ndims-1);\nc3=vindexinto(c3,b33,3,ndims-1);\n\nmat=vindexinto(mat,c1,1,ndims);\nmat=vindexinto(mat,c2,2,ndims);\nmat=vindexinto(mat,c3,3,ndims);\n\nfunction[invmat]=matinv_block(mat,ndims,K)\n\n%This keeps the two matrices about the same size, which seems the \n%fastest option in tests\n\ni1=1:floor(K/2);\ni2=floor(K/2)+1:K;\n\n%i1,i2\n\nac=vindex(mat,i1,ndims);\nbd=vindex(mat,i2,ndims);\n\na=vindex(ac,i1,ndims-1);\nc=vindex(ac,i2,ndims-1);\nb=vindex(bd,i1,ndims-1);\nd=vindex(bd,i2,ndims-1);\n\n%vsize(a,b,c,d)\n\n%Recursion\nainv=matinv(a);\n\ndcab=matinv(d-matmult(matmult(c,ainv,ndims-1),b,ndims-1));\n\nbnew=-matmult(matmult(ainv,b,ndims-1),dcab,ndims-1);\nanew=ainv+matmult(matmult(-bnew,c,ndims-1),ainv,ndims-1);\ncnew=-matmult(matmult(dcab,c,ndims-1),ainv,ndims-1);\ndnew=dcab;\n\nac=vindexinto(ac,anew,i1,ndims-1);\nac=vindexinto(ac,cnew,i2,ndims-1);\n\nbd=vindexinto(bd,bnew,i1,ndims-1);\nbd=vindexinto(bd,dnew,i2,ndims-1);\n\ninvmat=zeros(size(mat));\ninvmat=vindexinto(invmat,ac,i1,ndims);\ninvmat=vindexinto(invmat,bd,i2,ndims);\n\nfunction[]=matinv_test\ndisp('Testing that direct and looping algorithms match for non-singular matrices.')\n\nrng(0);\n\nfor n=2:12\n \n mat=randn(n);\n \n invmat=inv(mat);\n invmat2=matinv(mat);\n disp(['MATINV testing case of ' int2str(n) 'x' int2str(n) ' matrices.'])\n reporttest('MATINV with single matrix',aresame(invmat,invmat2,1e-3))\n mat=randn(10000,n,n);\n tic\n invmat=matinv(mat,'loop');\n t1=toc;\n \n tic\n invmat2=matinv(mat,'direct');\n t2=toc;\n \n tol=1e-1;\n bool=false(size(mat,1),1);\n for i=1:size(mat)\n bool(i)=rcond(squeeze(mat(i,:,:)))>=tol;\n end\n \n vindex(invmat,invmat2,find(bool),1);\n \n reporttest('MATINV with 10000 random matrices',aresame(invmat,invmat2,1e-2))\n disp(['MATINV was ' num2str(t1./t2) ' times faster than INV.'])\nend\n\n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jMap/matinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6467556246144943}} {"text": "function J=calcCartRRJacob(components,xState,useHalfRange,lTx,lRx)\n%%CALCCARTRRJACOB Compute the Jacobian matrix for a Cartesian measurement\n% possibly with a bistatic range rate component in 1D, 2D or 3D\n% for a Cartesian target state. This function can be useful when\n% using an extended Kalman filter (EKF) with Cartesian-converted\n% measurements and range rate. Without the range rate component,\n% the result is just the measurement matrix, which, when\n% multiplied by the target state, extracts the position\n% components and is often designated by H in the discrete-time\n% Kalman filter.\n%\n%INPUTS: components This specified whether the output should contain a\n% range-rate component. Possible values are:\n% 0 The output contains position and range rate rows. This is\n% the default if an empty matrix is passed.\n% 1 The output just has position rows.\n% xState The xDimX1 target state vector in the global coordinate\n% system with [x;y;z;xDot;yDot;zDot] components in 3D or\n% [x;y;xDot;yDot] components in 2D.\n% useHalfRange A boolean value specifying whether the bistatic range\n% (and thus the range rate) value has been divided by two.\n% This normally comes up when operating in monostatic mode,\n% lTx The transmitter state vector in the global coordinate\n% system with [x;y;z;xDot;yDot;zDot] components in 3D or \n% [x;y;xDot;yDot] components in 2D. If omitted, then a vector\n% of zeros is used.\n% lRx The receiver state vector in the global coordinate system\n% with [x;y;z;xDot;yDot;zDot] components in 3D or\n% [x;y;xDot;yDot] components in 2D. If omitted, then a vector\n% of zeros is used.\n%\n%OUTPUTS: J The (xDim/2+1)XxDim Jacobian matrix. Each row is a component\n% of x-y-z-range rate and each column is the derivative with\n% respect to x,y,z,xDot,yDot,zDot. If range rate is not desired,\n% then the matrix is (xDim/2)XxDim in size.\n%\n%The derivatives of the position components with themselves are clear (1\n%for common components and zero for different components). The derivatives\n%of the range rate components are obtained using the rangeRateGradient\n%function.\n%\n%February 2017 David F.Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(xState,1);\nposDim=xDim/2;\nmeasDim=posDim+1;\n\nif(isempty(components))\n components=0;\nend\n\nif(components==0)\n if(nargin<3||isempty(useHalfRange))\n useHalfRange=false;\n end\n\n if(nargin<4||isempty(lTx))\n lTx=zeros(xDim,1); \n end\n\n if(nargin<5||isempty(lRx))\n lRx=zeros(xDim,1); \n end\n\n J=zeros(measDim,xDim);\n %Position components are just passed through.\n J(1:posDim,1:posDim)=eye(posDim,posDim);\n\n J(posDim+1,:)=rangeRateGradient(xState,useHalfRange,lTx,lRx);\nelse\n J=zeros(posDim,xDim);\n J(1:posDim,1:posDim)=eye(posDim,posDim);\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Jacobians/calcCartRRJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6467556180049042}} {"text": "%R2T Convert rotation matrix to a homogeneous transform\n%\n% T = R2T(R) is a homogeneous transform equivalent to an orthonormal \n% rotation matrix R with a zero translational component.\n%\n% Notes::\n% - Works for T in either SE(2) or SE(3)\n% - if R is 2x2 then T is 3x3, or\n% - if R is 3x3 then T is 4x4.\n% - Translational component is zero.\n% - For a rotation matrix sequence returns a homogeneous transform\n% sequence.\n%\n% See also T2R.\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for Matlab (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n\nfunction T = r2t(R)\n\n % check dimensions: R is SO(2) or SO(3)\n d = size(R);\n if d(1) ~= d(2)\n error('matrix must be square');\n end\n if ~any(d(1) == [2 3])\n error('argument is not a rotation matrix (sequence)');\n end\n \n Z = zeros(d(1),1);\n B = [Z' 1];\n \n if numel(d) == 2\n % single matrix case\n T = [R Z; B];\n else\n % matrix sequence case\n T = zeros(4,4,d(3));\n for i=1:d(3)\n T(:,:,i) = [R(:,:,i) Z; B];\n end\n end\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/External/MatrixUser2.2/External/Tran3D/r2t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6467556153718024}} {"text": "function determ = line_adj_determinant ( n )\n\n%*****************************************************************************80\n%\n%% LINE_ADJ_DETERM returns the determinant of the LINE_ADJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM, the determinant.\n%\n if ( mod ( n, 4 ) == 1 )\n determ = 0.0;\n elseif ( mod ( n, 4 ) == 2 )\n determ = - 1.0;\n elseif ( mod ( n, 4 ) == 3 )\n determ = 0.0;\n elseif ( mod ( n, 4 ) == 0 )\n determ = + 1.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/line_adj_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6466714690569898}} {"text": "function xEst=DopplerOnlyInit6D(rDot,lRx,algorithm,opts,AbsTol,scratchFolderPath,execPath)\n%%DOPPLERONLYINIT6D Determine the 3D position and velocity of a target\n% using six simultaneous Doppler measurements. The measurements\n% are assumed to be one-way (from a moving emitter). The receivers\n% are stationary. This function makes use of the function\n% solvePolySysWithExtProg to call an external program to solve the\n% simultaneous multivariate polynomials that define the solution.\n%\n%INPUTS: rDot A 6X1 or 1X6 vector of Doppler measurements of the emitter.\n% lRx A 3X6 set of the six Cartesian locations of the receivers\n% taking the Doppler measurements in rDot.\n% algorithm An optional parameter specifying which algorithm to use. The\n% solvers for simultaneous multivariate polynomials are external\n% programs called via solvePolySysWithExtProg. Possible values\n% are:\n% 0 (The default if omitted or an empty matrix is passed) Use\n% Bertini.\n% 1 Use PHCpack.\n% 2 Use the certified homotopy algorithm that is built into\n% Macaulay2 (in NAG4M2). This only uses the normalized solver\n% with the default options.\n% opts An optional input specifying options for the solver in the\n% function solvePolySysWithExtProg. This is described in more\n% detail in solvePolySysWithExtProg. Omitting this parameter or\n% passing am empty matrices uses the default values, except if\n% Bertini is used, then SecurityMaxNorm, EndpointFiniteThreshold\n% and PathTruncationThreshold are set to 1e9 by default.\n% AbsTol An absolute tolerance on the imaginary part of a solution to the\n% multivariate polynomials used here real. The default if this\n% parameter is omitted or an empty matrix is passed is 1e-8.\n% scratchFolderPath An optional parameter specifying the folder in which\n% temporary files will be written. This is needed, because all\n% solvers only works through files. If this parameter is omitted or\n% an empty matrix is passed, then a folder named temp in the folder\n% enclosing this function is used. Note that if an error occurs\n% while executing this function, then temporary files might be left\n% in the temp folder after this function ends.\n% execPath The command line command to use to execute the solver. The \n% default if this parameter is omitted or an empty matrix is \n% passed is just the standard name on the command line: bertini,\n% phc and M2 for each of the algorithms. The default assumes that\n% the program is already in the default search path. For example,\n% on *NIX systems, one can usually put the executable in\n% /usr/local/bin for it to be in the default search path.\n% However, for some reason, that directory is often not\n% included in Matlab's search path. Matlab 2016a's help under\n% \"Run External Commands, Scripts, and Programs\" specifically\n% says how to add that folder to the default search path.\n%\n%OUTPUTS: xEst A 6XnumEst set of solutions.\n%\n%The algorithm solves a system of simultaneous multivariate polynomials as\n%formulated in [1] (Equation numbers in the code refer to [1]). However,\n%there is a typo in [1], which is corrected in the same derivation in [2].\n%\n%EXAMPLE:\n% lRx=[1000, 500, 1100, 2500, 0, 1000;\n% 3000, 2500, 2500, 0, 0, 1000;\n% 0, 0, 0, 400, 8000, 8000];%(Stationary) sensor locations\n% xTrue=[1e3;5e3;4e3;0;300;0];\n% rDot=zeros(6,1);\n% for curMeas=1:6\n% diff=xTrue(1:3)-lRx(:,curMeas);\n% rDot(curMeas)=(diff'/norm(diff))*xTrue(4:6);\n% end\n% DopplerOnlyInit6D(rDot,lRx,0)\n%\n%REFERENCES:\n%[1] T.-L. Lee, S.-S. Lin, W.-W. Lin, S.-T. Yau, and J. Zhu, \"Polynomial\n% calculations in Doppler tracking,\" Communications in Information and\n% Systems, vol. 12, no. 2, pp. 157-184, 2012.\n%[2] Y.-C. Kuo, W.-W. Lin, and S.-T. Yau, \"A novel efficient homotopy\n% continuation method in tracking,\" Communications in Information and\n% Systems, vol. 14, no. 1, pp. 57-78, 2014.\n%\n%March 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%We subtract out the locations of the sensors and then put them back in at\n%the end. This should help with numerical sensitivity issues when\n%localizing things on the ground but using ECEF coordinates. The offset is\n%removed in the end.\ncenterOfRegion=mean(lRx,2);\nlRx=bsxfun(@minus,lRx,centerOfRegion);\n\n%Now, we scale the distances so that the farthest one is 1. This should\n%help deal with convergence problems when the scale of the probolem\n%changes. The scaling will be reversed after the estimation.\nscalFactor=sqrt(max(sum(lRx.*lRx,1)));\nlRx=lRx/scalFactor;\nrDot=rDot/scalFactor;\n\nif(nargin<3||isempty(algorithm))\n algorithm=0;\nend\n\nif(nargin<4)\n opts=[];\nend\n\nif(nargin<5||isempty(AbsTol))\n AbsTol=1e-8;\nend \n\nif(nargin<5)\n scratchFolderPath=[];\nend\n\nif(nargin<6)\n execPath=[];\nend\n\nif(algorithm==0&&isempty(opts))%If using Bertini, set default tolerances\n %Default options when using Bertini\n opts=struct('SecurityMaxNorm',1e9,'EndpointFiniteThreshold',1e9,'PathTruncationThreshold',1e9);\nelseif(algorithm==0)\n if(~isfield(opts,'SecurityMaxNorm'))\n opts.SecurityMaxNorm=1e9;\n end\n \n if(~isfield(opts,'EndpointFiniteThreshold'))\n opts.EndpointFiniteThreshold=1e9;\n end\n \n if(~isfield(opts,'PathTruncationThreshold'))\n opts.PathTruncationThreshold=1e9;\n end\nend\n\n%The following are from Equation 4.\nV0=lRx';\nn=sum(V0.*V0,2);\n\nu1=lRx(:,1);\nu2=lRx(:,2);\nu3=lRx(:,3);\nu4=lRx(:,4);\nu5=lRx(:,5);\nu6=lRx(:,6);\n\n%From Equation 5\nRDot=diag(rDot);\n\n%From Equation 6\nC=[-1, 1, 0, 0, 0, 0;\n -1, 0, 1, 0, 0, 0;\n -1, 0, 0, 1, 0, 0;\n -1, 0, 0, 0, 1, 0;\n -1, 0, 0, 0, 0, 1];\n\n%From Equation 10\nA=(V0'*(C'*C)*V0)\\(V0'*(C'*C));\n\n%From Equation 15\nCHat=[0, -1, 1, 0, 0, 0;\n 0, -1, 0, 1, 0, 0;\n 0, -1, 0, 0, 1, 0;\n 0, -1, 0, 0, 0, 1];\n\n%From Equation 16 --Note that the RDot matrix has been removed. This is\n%because including RDot makes the solution inconsistent with Equation 22.\n%However, the RDot term needs to be included in the QR decomposition.\nAHat=([(u2-u3)';\n (u2-u4)';\n (u2-u5)';\n (u2-u6)']*A+CHat);\n \n%Equation 18\nu1Hat=(1/2)*A*n-u1;\n\n%Get the T values used in Equation 17 (needs the RDot term with AHat.\n[~,R]=qr(AHat*RDot);\nT1=R(1:2,1:2);\nT2=R(1:2,3:end);\n\n%This is from Equation 17\nr12Transform=-T1\\T2;\n%Extract the elements of the transformation\nat11=r12Transform(1,1);\nat12=r12Transform(1,2);\nat13=r12Transform(1,3);\nat14=r12Transform(1,4);\nat21=r12Transform(2,1);\nat22=r12Transform(2,2);\nat23=r12Transform(2,3);\nat24=r12Transform(2,4);\n\n%A term in the first formula in Equation 23.\nM=(1/2)*(A'*A)*RDot;\n%Extract the elements\nm1=M(1);\nm2=M(2);\nm3=M(3);\nm4=M(4);\nm5=M(5);\nm6=M(6);\nm7=M(7);\nm8=M(8);\nm9=M(9);\nm10=M(10);\nm11=M(11);\nm12=M(12);\nm13=M(13);\nm14=M(14);\nm15=M(15);\nm16=M(16);\nm17=M(17);\nm18=M(18);\nm19=M(19);\nm20=M(20);\nm21=M(21);\nm22=M(22);\nm23=M(23);\nm24=M(24);\nm25=M(25);\nm26=M(26);\nm27=M(27);\nm28=M(28);\nm29=M(29);\nm30=M(30);\nm31=M(31);\nm32=M(32);\nm33=M(33);\nm34=M(34);\nm35=M(35);\nm36=M(36);\n\n%A vector term in the first formula in Equation 23.\nmVec=u1Hat'*A*RDot;\n%Extract the elements\nmv1=mVec(1);\nmv2=mVec(2);\nmv3=mVec(3);\nmv4=mVec(4);\nmv5=mVec(5);\nmv6=mVec(6);\n\n%The first polynomial in Equation 23. The components are ordered\n%[r3;r4;r5;r6].\nterms1=zeros(5,24);%Allocate space for the terms.\n\nterms1(1,1)=(-at11*(rDot(1)+mv1)-at21*mv2-mv3);\nterms1(2:end,1)=[1;0;0;0];%r3\n\nterms1(1,2)=(at11^3*m1+m15+at11*(at21^2*m2+m3)+at11^2*(m13+at21*m7)+at21*(at21*(m14+at21*m8)+m9));\nterms1(2:end,2)=[3;0;0;0];%r3^3\n\nterms1(1,3)=(-at12*(rDot(1)+mv1)-at22*mv2-mv4);\nterms1(2:end,3)=[0;1;0;0];%r4\n\nterms1(1,4)=(2*at21*at22*m14+m21+at12*m3+at11^2*(3*at12*m1+m19+at22*m7)+2*at11*(at21*at22*m2+at12*(m13+at21*m7))+at21^2*(at12*m2+m20+3*at22*m8)+at22*m9);\nterms1(2:end,4)=[2;1;0;0];%r3^2*r4\n\nterms1(1,5)=(at12^2*m13+at22^2*m14+m16+at11*(3*at12^2*m1+at22^2*m2+m4+2*at12*(m19+at22*m7))+at21*(m10+2*at12*at22*m2+2*at22*m20+at12^2*m7+3*at22^2*m8));\nterms1(2:end,5)=[1;2;0;0];%r3*r4^2\n\nterms1(1,6)=(at12^3*m1+m22+at12*(at22^2*m2+m4)+at12^2*(m19+at22*m7)+at22*(m10+at22*(m20+at22*m8)));\nterms1(2:end,6)=[0;3;0;0];%r4^3\n\nterms1(1,7)=(-at13*(rDot(1)+mv1)-at23*mv2-mv5);\nterms1(2:end,7)=[0;0;1;0];%r5\n\nterms1(1,8)=(2*at21*at23*m14+m27+at13*m3+at11^2*(3*at13*m1+m25+at23*m7)+2*at11*(at21*at23*m2+at13*(m13+at21*m7))+at21^2*(at13*m2+m26+3*at23*m8)+at23*m9);\nterms1(2:end,8)=[2;0;1;0];%r3^2*r5\n\nterms1(1,9)=2*(at22*at23*m14+at12*(at21*at23*m2+at13*(m13+at21*m7))+at11*(at13*m19+at22*at23*m2+at13*at22*m7+at12*(3*at13*m1+m25+at23*m7))+at21*(at23*m20+at22*(at13*m2+m26+3*at23*m8)));\nterms1(2:end,9)=[1;1;1;0];%r3*r4*r5\n\nterms1(1,10)=(at22^2*(at13*m2+m26)+m28+at13*m4+at12^2*(3*at13*m1+m25+at23*m7)+2*at12*(at22*at23*m2+at13*(m19+at22*m7))+at23*(m10+2*at22*m20+3*at22^2*m8));\nterms1(2:end,10)=[0;2;1;0];%r4^2*r5\n\nterms1(1,11)=(at13^2*m13+at23^2*m14+m17+at11*(3*at13^2*m1+at23^2*m2+m5+2*at13*(m25+at23*m7))+at21*(m11+2*at13*at23*m2+2*at23*m26+at13^2*m7+3*at23^2*m8));\nterms1(2:end,11)=[1;0;2;0];%r3*r5^2\n\nterms1(1,12)=(at22*m11+2*at13*at22*at23*m2+m23+at13^2*(m19+at22*m7)+at12*(3*at13^2*m1+at23^2*m2+m5+2*at13*(m25+at23*m7))+at23*(2*at22*m26+at23*(m20+3*at22*m8)));\nterms1(2:end,12)=[0;1;2;0];%r4*r5^2;\n\nterms1(1,13)=(at13^3*m1+m29+at13*(at23^2*m2+m5)+at13^2*(m25+at23*m7)+at23*(m11+at23*(m26+at23*m8)));\nterms1(2:end,13)=[0;0;3;0];%r5^3\n\nterms1(1,14)=(-at14*(rDot(1)+mv1)-at24*mv2-mv6);\nterms1(2:end,14)=[0;0;0;1];%r6\n\nterms1(1,15)=(2*at21*at24*m14+at14*m3+m33+at11^2*(3*at14*m1+m31+at24*m7)+2*at11*(at21*at24*m2+at14*(m13+at21*m7))+at21^2*(at14*m2+m32+3*at24*m8)+at24*m9);\nterms1(2:end,15)=[2;0;0;1];%r3^2*r6\n\nterms1(1,16)=2*(at22*at24*m14+at12*(at21*at24*m2+at14*(m13+at21*m7))+at11*(at14*m19+at22*at24*m2+at14*at22*m7+at12*(3*at14*m1+m31+at24*m7))+at21*(at24*m20+at22*(at14*m2+m32+3*at24*m8)));\nterms1(2:end,16)=[1;1;0;1];%r3*r4*r6\n\nterms1(1,17)=(at22^2*(at14*m2+m32)+m34+at14*m4+at12^2*(3*at14*m1+m31+at24*m7)+2*at12*(at22*at24*m2+at14*(m19+at22*m7))+at24*(m10+2*at22*m20+3*at22^2*m8));\nterms1(2:end,17)=[0;2;0;1];%r4^2*r6\n\nterms1(1,18)=2*(at23*at24*m14+at13*(at21*at24*m2+at14*(m13+at21*m7))+at11*(at23*at24*m2+at14*m25+at14*at23*m7+at13*(3*at14*m1+m31+at24*m7))+at21*(at24*m26+at23*(at14*m2+m32+3*at24*m8)));\nterms1(2:end,18)=[1;0;1;1];%r3*r5*r6\n\nterms1(1,19)=2*(at14*at22*at23*m2+at23*at24*m20+at22*at24*m26+at22*at23*m32+at13*(at14*m19+at22*at24*m2+at14*at22*m7)+at12*(at23*at24*m2+at14*m25+at14*at23*m7+at13*(3*at14*m1+m31+at24*m7))+3*at22*at23*at24*m8);\nterms1(2:end,19)=[0;1;1;1];%r4*r5*r6\n\nterms1(1,20)=(at23^2*(at14*m2+m32)+m35+at14*m5+2*at13*(at23*at24*m2+at14*m25+at14*at23*m7)+at13^2*(3*at14*m1+m31+at24*m7)+at24*(m11+2*at23*m26+3*at23^2*m8));\nterms1(2:end,20)=[0;0;2;1];%r5^2*r6\n\nterms1(1,21)=(at14^2*m13+at24^2*m14+m18+at11*(3*at14^2*m1+at24^2*m2+m6+2*at14*(m31+at24*m7))+at21*(m12+2*at14*at24*m2+2*at24*m32+at14^2*m7+3*at24^2*m8));\nterms1(2:end,21)=[1;0;0;2];%r3*r6^2\n\nterms1(1,22)=(at22*m12+2*at14*at22*at24*m2+m24+at14^2*(m19+at22*m7)+at12*(3*at14^2*m1+at24^2*m2+m6+2*at14*(m31+at24*m7))+at24*(2*at22*m32+at24*(m20+3*at22*m8))) ;\nterms1(2:end,22)=[0;1;0;2];%r4*r6^2\n\nterms1(1,23)=(at23*m12+2*at14*at23*at24*m2+m30+at14^2*(m25+at23*m7)+at13*(3*at14^2*m1+at24^2*m2+m6+2*at14*(m31+at24*m7))+at24*(2*at23*m32+at24*(m26+3*at23*m8)));\nterms1(2:end,23)=[0;0;1;2];%r5*r6^2\n\nterms1(1,24)=(at14^3*m1+m36+at14*(at24^2*m2+m6)+at14^2*(m31+at24*m7)+at24*(m12+at24*(m32+at24*m8)));\nterms1(2:end,24)=[0;0;0;3];%r6^3\n\n%Scale the coefficients\nterms1(1,:)=terms1(1,:)/max(abs(terms1(1,:)));\n\n%cHat is defined after Equation 20.\ncHat=(1/4)*n'*(A'*A)*n-u1'*A*n+u1'*u1;\n\n%A term in the second formula in Equation 23.\nMt=(1/4)*(A'*A);\n%Extract the elements\nmt1=Mt(1);\nmt2=Mt(2);\nmt3=Mt(3);\nmt4=Mt(4);\nmt5=Mt(5);\nmt6=Mt(6);\nmt7=Mt(7);\nmt8=Mt(8);\nmt9=Mt(9);\nmt10=Mt(10);\nmt11=Mt(11);\nmt12=Mt(12);\nmt13=Mt(13);\nmt14=Mt(14);\nmt15=Mt(15);\nmt16=Mt(16);\nmt17=Mt(17);\nmt18=Mt(18);\nmt19=Mt(19);\nmt20=Mt(20);\nmt21=Mt(21);\nmt22=Mt(22);\nmt23=Mt(23);\nmt24=Mt(24);\nmt25=Mt(25);\nmt26=Mt(26);\nmt27=Mt(27);\nmt28=Mt(28);\nmt29=Mt(29);\nmt30=Mt(30);\nmt31=Mt(31);\nmt32=Mt(32);\nmt33=Mt(33);\nmt34=Mt(34);\nmt35=Mt(35);\nmt36=Mt(36);\n\n%A vector term in the second formula in Equation 23.\nmVec2=u1Hat'*A;\n%Extract the elements\nmvt1=mVec2(1);\nmvt2=mVec2(2);\nmvt3=mVec2(3);\nmvt4=mVec2(4);\nmvt5=mVec2(5);\nmvt6=mVec2(6);\n\n%The second polynomial in Equation 23. The components are ordered\n%[r3;r4;r5;r6].\nterms2=zeros(5,46);%Allocate space for the terms.\n\nterms2(1,1)=cHat;\nterms2(2:end,1)=[0;0;0;0];%Constant term\n\nterms2(1,2)=(at11^4*mt1+mt15+at11^2*(mt13+mt3+at21^2*(mt2+mt7))+at21^4*mt8+at21^2*(mt14+mt9));\nterms2(2:end,2)=[4;0;0;0];%r3^4\n\nterms2(1,3)=2*(2*at11^3*at12*mt1+at11^2*at21*at22*(mt2+mt7)+at11*at12*(mt13+mt3+at21^2*(mt2+mt7))+at21*at22*(mt14+2*at21^2*mt8+mt9));\nterms2(2:end,3)=[3;1;0;0];%r3^3*r4\n\nterms2(1,4)=(mt16+mt21+at12^2*(mt13+mt3)+4*at11*at12*at21*at22*(mt2+mt7)+at11^2*(6*at12^2*mt1+mt19+mt4+at22^2*(mt2+mt7))+at21^2*(mt10+mt20+at12^2*(mt2+mt7)+6*at22^2*mt8)+at22^2*(mt14+mt9));\nterms2(2:end,4)=[2;2;0;0];%r3^2*r4^2\n\nterms2(1,5)=2*(at11*at12*(2*at12^2*mt1+mt19+mt4+at22^2*(mt2+mt7))+at21*at22*(mt10+mt20+at12^2*(mt2+mt7)+2*at22^2*mt8));\nterms2(2:end,5)=[1;3;0;0];%r3*r4^3\n\nterms2(1,6)=(at12^4*mt1+at22^2*(mt10+mt20)+mt22+at12^2*(mt19+mt4+at22^2*(mt2+mt7))+at22^4*mt8);\nterms2(2:end,6)=[0;4;0;0];%r4^4\n\nterms2(1,7)=2*(2*at11^3*at13*mt1+at11^2*at21*at23*(mt2+mt7)+at11*at13*(mt13+mt3+at21^2*(mt2+mt7))+at21*at23*(mt14+2*at21^2*mt8+mt9));\nterms2(2:end,7)=[3;0;1;0];%r3^3*r5\n\nterms2(1,8)=2*(2*at12^3*at13*mt1+at12^2*at22*at23*(mt2+mt7)+at12*at13*(mt19+mt4+at22^2*(mt2+mt7))+at22*at23*(mt10+mt20+2*at22^2*mt8));\nterms2(2:end,8)=[0;3;1;0];%r4^3*r5\n\nterms2(1,9)=(mt17+mt27+at13^2*(mt13+mt3)+4*at11*at13*at21*at23*(mt2+mt7)+at11^2*(6*at13^2*mt1+mt25+mt5+at23^2*(mt2+mt7))+at21^2*(mt11+mt26+at13^2*(mt2+mt7)+6*at23^2*mt8)+at23^2*(mt14+mt9));\nterms2(2:end,9)=[2;0;2;0];%r3^2*r5^2\n\nterms2(1,10)=(mt23+mt28+at13^2*(mt19+mt4)+4*at12*at13*at22*at23*(mt2+mt7)+at22^2*(mt11+mt26+at13^2*(mt2+mt7))+at12^2*(6*at13^2*mt1+mt25+mt5+at23^2*(mt2+mt7))+at23^2*(mt10+mt20+6*at22^2*mt8));\nterms2(2:end,10)=[0;2;2;0];%r4^2*r5^2\n\nterms2(1,11)=2*(at11*at13*(2*at13^2*mt1+mt25+mt5+at23^2*(mt2+mt7))+at21*at23*(mt11+mt26+at13^2*(mt2+mt7)+2*at23^2*mt8));\nterms2(2:end,11)=[1;0;3;0];%r3*r5^3\n\nterms2(1,12)=2*(at12*at13*(2*at13^2*mt1+mt25+mt5+at23^2*(mt2+mt7))+at22*at23*(mt11+mt26+at13^2*(mt2+mt7)+2*at23^2*mt8));\nterms2(2:end,12)=[0;1;3;0];%r4*r5^3\n\nterms2(1,13)=(at13^4*mt1+at23^2*(mt11+mt26)+mt29+at13^2*(mt25+mt5+at23^2*(mt2+mt7))+at23^4*mt8);\nterms2(2:end,13)=[0;0;4;0];%r5^4\n\nterms2(1,14)=-2*(at11*at14*(1+mvt1)+at21*at24*mvt2);\nterms2(2:end,14)=[1;0;0;1];%r3*r6\n\nterms2(1,15)=2*(2*at11^3*at14*mt1+at11^2*at21*at24*(mt2+mt7)+at11*at14*(mt13+mt3+at21^2*(mt2+mt7))+at21*at24*(mt14+2*at21^2*mt8+mt9));\nterms2(2:end,15)=[3;0;0;1];%r3^3*r6\n\nterms2(1,16)=-2*(at12*at14*(1+mvt1)+at22*at24*mvt2);\nterms2(2:end,16)=[0;1;0;1];%r4*r6\n\nterms2(1,17)=2*(2*at12^3*at14*mt1+at12^2*at22*at24*(mt2+mt7)+at12*at14*(mt19+mt4+at22^2*(mt2+mt7))+at22*at24*(mt10+mt20+2*at22^2*mt8));\nterms2(2:end,17)=[0;3;0;1];%r4^3*r6\n\nterms2(1,18)=-2*(at13*at14*(1+mvt1)+at23*at24*mvt2);\nterms2(2:end,18)=[0;0;1;1];%r5*r6\n\nterms2(1,19)=2*(2*at13^3*at14*mt1+at13^2*at23*at24*(mt2+mt7)+at13*at14*(mt25+mt5+at23^2*(mt2+mt7))+at23*at24*(mt11+mt26+2*at23^2*mt8));\nterms2(2:end,19)=[0;0;3;1];%r5^3*r6\n\nterms2(1,20)=(-at14^2*(1+mvt1)-at24^2*mvt2-mvt6);\nterms2(2:end,20)=[0;0;0;2];%r6^2\n\nterms2(1,21)=(mt18+at14^2*(mt13+mt3)+mt33+4*at11*at14*at21*at24*(mt2+mt7)+at11^2*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at21^2*(mt12+mt32+at14^2*(mt2+mt7)+6*at24^2*mt8)+at24^2*(mt14+mt9));\nterms2(2:end,21)=[2;0;0;2];%r3^2*r6^2\n\nterms2(1,22)=(mt24+mt34+at14^2*(mt19+mt4)+4*at12*at14*at22*at24*(mt2+mt7)+at22^2*(mt12+mt32+at14^2*(mt2+mt7))+at12^2*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at24^2*(mt10+mt20+6*at22^2*mt8));\nterms2(2:end,22)=[0;2;0;2];%r4^2*r6^2\n\nterms2(1,23)=(mt30+mt35+at14^2*(mt25+mt5)+4*at13*at14*at23*at24*(mt2+mt7)+at23^2*(mt12+mt32+at14^2*(mt2+mt7))+at13^2*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at24^2*(mt11+mt26+6*at23^2*mt8));\nterms2(2:end,23)=[0;0;2;2];%r5^2*r6^2\n\nterms2(1,24)=2*(at11*at14*(2*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at21*at24*(mt12+mt32+at14^2*(mt2+mt7)+2*at24^2*mt8));\nterms2(2:end,24)=[1;0;0;3];%r3*r6^3\n\nterms2(1,25)=2*(at12*at14*(2*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at22*at24*(mt12+mt32+at14^2*(mt2+mt7)+2*at24^2*mt8));\nterms2(2:end,25)=[0;1;0;3];%r4*r6^3\n\nterms2(1,26)=2*(at13*at14*(2*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7))+at23*at24*(mt12+mt32+at14^2*(mt2+mt7)+2*at24^2*mt8));\nterms2(2:end,26)=[0;0;1;3];%r5*r6^3\n\nterms2(1,27)=(at14^4*mt1+at24^2*(mt12+mt32)+mt36+at14^2*(mt31+mt6+at24^2*(mt2+mt7))+at24^4*mt8);\nterms2(2:end,27)=[0;0;0;4];%r6^4\n\nterms2(1,28)=(-at13^2*(1+mvt1)-at23^2*mvt2-mvt5);\nterms2(2:end,28)=[0;0;2;0];%r5^2\n\nterms2(1,29)=2*(at11*(6*at13^2*at14*mt1+2*at13*at23*at24*(mt2+mt7)+at14*(mt25+mt5+at23^2*(mt2+mt7)))+at21*(2*at13*at14*at23*(mt2+mt7)+at24*(mt11+mt26+at13^2*(mt2+mt7)+6*at23^2*mt8)));\nterms2(2:end,29)=[1;0;2;1];%r3*r5^2*r6\n\nterms2(1,30)=2*(at12*(6*at13^2*at14*mt1+2*at13*at23*at24*(mt2+mt7)+at14*(mt25+mt5+at23^2*(mt2+mt7)))+at22*(2*at13*at14*at23*(mt2+mt7)+at24*(mt11+mt26+at13^2*(mt2+mt7)+6*at23^2*mt8)));\nterms2(2:end,30)=[0;1;2;1];%r4*r5^2*r6\n\nterms2(1,31)=(-at12^2*(1+mvt1)-at22^2*mvt2-mvt4);\nterms2(2:end,31)=[0;2;0;0];%r4^2\n\nterms2(1,32)=2*(at11*(6*at12^2*at13*mt1+2*at12*at22*at23*(mt2+mt7)+at13*(mt19+mt4+at22^2*(mt2+mt7)))+at21*(2*at12*at13*at22*(mt2+mt7)+at23*(mt10+mt20+at12^2*(mt2+mt7)+6*at22^2*mt8)));\nterms2(2:end,32)=[1;2;1;0];%r3*r4^2*r5\n\nterms2(1,33)=2*(at11*(6*at12^2*at14*mt1+2*at12*at22*at24*(mt2+mt7)+at14*(mt19+mt4+at22^2*(mt2+mt7)))+at21*(2*at12*at14*at22*(mt2+mt7)+at24*(mt10+mt20+at12^2*(mt2+mt7)+6*at22^2*mt8)));\nterms2(2:end,33)=[1;2;0;1];%r3*r4^2*r6\n\nterms2(1,34)=2*(2*at12*at22*(at14*at23+at13*at24)*(mt2+mt7)+at13*at14*(mt19+mt4+at22^2*(mt2+mt7))+at12^2*(6*at13*at14*mt1+at23*at24*(mt2+mt7))+at23*at24*(mt10+mt20+6*at22^2*mt8));\nterms2(2:end,34)=[0;2;1;1];%r4^2*r5*r6\n\nterms2(1,35)=(-at11^2*(1+mvt1)-at21^2*mvt2-mvt3);\nterms2(2:end,35)=[2;0;0;0];%r3^2\n\nterms2(1,36)=2*(2*at11*at21*(at13*at22+at12*at23)*(mt2+mt7)+at12*at13*(mt13+mt3+at21^2*(mt2+mt7))+at11^2*(6*at12*at13*mt1+at22*at23*(mt2+mt7))+at22*at23*(mt14+6*at21^2*mt8+mt9));\nterms2(2:end,36)=[2;1;1;0];%r3^2*r4*r5\n\nterms2(1,37)=2*(2*at11*at21*(at14*at22+at12*at24)*(mt2+mt7)+at12*at14*(mt13+mt3+at21^2*(mt2+mt7))+at11^2*(6*at12*at14*mt1+at22*at24*(mt2+mt7))+at22*at24*(mt14+6*at21^2*mt8+mt9));\nterms2(2:end,37)=[2;1;0;1];%r3^2*r4*r6\n\nterms2(1,38)=2*(2*at11*at21*(at14*at23+at13*at24)*(mt2+mt7)+at13*at14*(mt13+mt3+at21^2*(mt2+mt7))+at11^2*(6*at13*at14*mt1+at23*at24*(mt2+mt7))+at23*at24*(mt14+6*at21^2*mt8+mt9));\nterms2(2:end,38)=[2;0;1;1];%r3^2*r5*r6\n\nterms2(1,39)=-2*(at11*at12*(1+mvt1)+at21*at22*mvt2);\nterms2(2:end,39)=[1;1;0;0];%r3*r4\n\nterms2(1,40)=2*(at11*(2*at13*at22*at23*(mt2+mt7)+at12*(6*at13^2*mt1+mt25+mt5+at23^2*(mt2+mt7)))+at21*(2*at12*at13*at23*(mt2+mt7)+at22*(mt11+mt26+at13^2*(mt2+mt7)+6*at23^2*mt8)));\nterms2(2:end,40)=[1;1;2;0];%r3*r4*r5^2\n\nterms2(1,41)=4*(at21*(at13*at14*at22+at12*at14*at23+at12*at13*at24)*(mt2+mt7)+at11*(at22*(at14*at23+at13*at24)*(mt2+mt7)+at12*(6*at13*at14*mt1+at23*at24*(mt2+mt7)))+6*at21*at22*at23*at24*mt8);\nterms2(2:end,41)=[1;1;1;1];%r3*r4*r5*r6\n\nterms2(1,42)=2*(at11*(2*at14*at22*at24*(mt2+mt7)+at12*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7)))+at21*(2*at12*at14*at24*(mt2+mt7)+at22*(mt12+mt32+at14^2*(mt2+mt7)+6*at24^2*mt8)));\nterms2(2:end,42)=[1;1;0;2];%r3*r4*r6^2\n\nterms2(1,43)=-2*(at11*at13*(1+mvt1)+at21*at23*mvt2);\nterms2(2:end,43)=[1;0;1;0];%r3*r5\n\nterms2(1,44)=2*(at11*(2*at14*at23*at24*(mt2+mt7)+at13*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7)))+at21*(2*at13*at14*at24*(mt2+mt7)+at23*(mt12+mt32+at14^2*(mt2+mt7)+6*at24^2*mt8)));\nterms2(2:end,44)=[1;0;1;2];%r3*r5*r6^2\n\nterms2(1,45)=-2*(at12*at13*(1+mvt1)+at22*at23*mvt2);\nterms2(2:end,45)=[0;1;1;0];%r4*r5\n\nterms2(1,46)=2*(at12*(2*at14*at23*at24*(mt2+mt7)+at13*(6*at14^2*mt1+mt31+mt6+at24^2*(mt2+mt7)))+at22*(2*at13*at14*at24*(mt2+mt7)+at23*(mt12+mt32+at14^2*(mt2+mt7)+6*at24^2*mt8)));\nterms2(2:end,46)=[0;1;1;2];%r4*r5*r6^2\n\n%Scale the coefficients\nterms2(1,:)=terms2(1,:)/max(abs(terms2(1,:)));\n\n%The third polynomial in Equation 23:\n%A vector term in the third formula in Equation 23.\nmVec3=(u2-u3)'*A;\n\n%Extract the elements\nmvtt1=mVec3(1);\nmvtt2=mVec3(2);\nmvtt3=mVec3(3);\nmvtt4=mVec3(4);\nmvtt5=mVec3(5);\nmvtt6=mVec3(6);\n\nterms3=zeros(5,11);\n\nterms3(1,1)=(-u3'*u3+u2'*u2-(u2-u3)'*A*n);\nterms3(2:end,1)=[0;0;0;0];%Constant term\n\nterms3(1,2)=1+at11^2*mvtt1+at21^2*(-1+mvtt2)+mvtt3;\nterms3(2:end,2)=[2;0;0;0];%r3^2\n\nterms3(1,3)=2*(at11*at12*mvtt1+at21*at22*(-1+mvtt2));\nterms3(2:end,3)=[1;1;0;0];%r3*r4\n\nterms3(1,4)=(at12^2*mvtt1+at22^2*(-1+mvtt2)+mvtt4);\nterms3(2:end,4)=[0;2;0;0];%r4^2\n\nterms3(1,5)=2*(at11*at13*mvtt1+at21*at23*(-1+mvtt2));\nterms3(2:end,5)=[1;0;1;0];%r3*r5\n\nterms3(1,6)=2*(at12*at13*mvtt1+at22*at23*(-1+mvtt2));\nterms3(2:end,6)=[0;1;1;0];%r4*r5\n\nterms3(1,7)=(at13^2*mvtt1+at23^2*(-1+mvtt2)+mvtt5);\nterms3(2:end,7)=[0;0;2;0];%r5^2\n\nterms3(1,8)=2*(at11*at14*mvtt1+at21*at24*(-1+mvtt2));\nterms3(2:end,8)=[1;0;0;1];%r3*r6\n\nterms3(1,9)=2*(at12*at14*mvtt1+at22*at24*(-1+mvtt2));\nterms3(2:end,9)=[0;1;0;1];%r4*r6\n\nterms3(1,10)=2*(at13*at14*mvtt1+at23*at24*(-1+mvtt2));\nterms3(2:end,10)=[0;0;1;1];%r5*r6\n\nterms3(1,11)=(at14^2*mvtt1+at24^2*(-1+mvtt2)+mvtt6);\nterms3(2:end,11)=[0;0;0;2];%r6^2\n\n%Scale the coefficients\nterms3(1,:)=terms3(1,:)/max(abs(terms3(1,:)));\n\n%The fourth polynomial in Equation 23:\nmVec4=(u2-u4)'*A;\n%Extract the elements\nmvtt1=mVec4(1);\nmvtt2=mVec4(2);\nmvtt3=mVec4(3);\nmvtt4=mVec4(4);\nmvtt5=mVec4(5);\nmvtt6=mVec4(6);\n\nterms4=zeros(5,11);\n\nterms4(1,1)=(-u4'*u4+u2'*u2-(u2-u4)'*A*n);\nterms4(2:end,1)=[0;0;0;0];%Constant term\n\nterms4(1,2)=(at11^2*mvtt1 + at21^2*(-1 + mvtt2) + mvtt3) ;\nterms4(2:end,2)=[2;0;0;0];%r3^2\n\nterms4(1,3)=2*(at11*at12*mvtt1 + at21*at22*(-1 + mvtt2)) ;\nterms4(2:end,3)=[1;1;0;0];%r3*r4\n\nterms4(1,4)=(1 + at12^2*mvtt1 + at22^2*(-1 + mvtt2) + mvtt4);\nterms4(2:end,4)=[0;2;0;0];%r4^2\n\nterms4(1,5)=2*(at11*at13*mvtt1 + at21*at23*(-1 + mvtt2));\nterms4(2:end,5)=[1;0;1;0];%r3*r5\n\nterms4(1,6)=2*(at12*at13*mvtt1 + at22*at23*(-1 + mvtt2));\nterms4(2:end,6)=[0;1;1;0];%r4*r5\n\nterms4(1,7)=(at13^2*mvtt1 + at23^2*(-1 + mvtt2) + mvtt5);\nterms4(2:end,7)=[0;0;2;0];%r5^2\n\nterms4(1,8)=2*(at11*at14*mvtt1 + at21*at24*(-1 + mvtt2));\nterms4(2:end,8)=[1;0;0;1];%r3*r6\n\nterms4(1,9)=2*(at12*at14*mvtt1 + at22*at24*(-1 + mvtt2));\nterms4(2:end,9)=[0;1;0;1];%r4*r6\n\nterms4(1,10)=2*(at13*at14*mvtt1 + at23*at24*(-1 + mvtt2));\nterms4(2:end,10)=[0;0;1;1];%r5*r6\n\nterms4(1,11)=(at14^2*mvtt1 + at24^2*(-1 + mvtt2) + mvtt6);\nterms4(2:end,11)=[0;0;0;2];%r6^2\n\n%Scale the coefficients\nterms4(1,:)=terms4(1,:)/max(abs(terms4(1,:)));\n\n%Now, put the term matrices into formats that can be used by the\n%multivariate polynomial solvers.\nxPolys=cell(4,1);\nxPolys{1}=terms1;\nxPolys{2}=terms2;\nxPolys{3}=terms3;\nxPolys{4}=terms4;\n\nvarNames={'rc','rd','re','rf'};\n\nfor curPoly=1:4\n termMat=xPolys{curPoly};\n\n numTerms=size(termMat,2);\n\n thePoly=[];\n\n for curTerm=1:numTerms\n curCoeff=num2str(termMat(1,curTerm),16);\n\n curMonomial=[];\n\n for curVar=1:4\n if(termMat(curVar+1,curTerm)~=0)\n if(~isempty(curMonomial))\n curMonomial=[curMonomial,'*']; \n end\n\n if(termMat(curVar+1,curTerm)==1)\n curMonomial=[curMonomial,varNames{curVar}];\n else\n curMonomial=[curMonomial,varNames{curVar},'^',num2str(termMat(curVar+1,curTerm))];\n end\n end\n end\n\n if(isempty(curMonomial))%If it is a constant term.\n %The constant term (if there is one) should be the first\n %term, so we can just set thePoly to it.\n thePoly=curCoeff;\n elseif(~isempty(thePoly))\n thePoly=[thePoly,'+(',curCoeff,')*',curMonomial];\n else%If there is no constant term.\n thePoly=['(',curCoeff,')*',curMonomial];\n end\n end\n\n xPolys{curPoly}=thePoly;\nend\n\nrEst=solvePolySysWithExtProg(xPolys,varNames,algorithm,opts,scratchFolderPath,execPath);\n\nif(isempty(rEst))\n %The solver failed.\n xEst=[];\n return;\nend\n%Throw out complex solutions. Solutions are deemed complex if the\n%imaginary part exceeds AbsTol in magnitude.\nsel=all(abs(imag(rEst))0,1);\nrEst=rEst(:,sel);\n\nnumSol=size(rEst,2);\nxEst=zeros(6,numSol);\n\n%Given solutions to the r variables, we need to extract the state.\nnumAdded=0;\nfor curSol=1:numSol\n %From Equation 17\n r1r2=r12Transform*rEst(:,curSol);\n \n %Only positive ranges are valid.\n if(all(r1r2)>0) \n r=[r1r2;rEst(:,curSol)];\n\n %Equation 8\n uDot=A*(-RDot*r);\n\n %Equation 9\n u=(1/2)*A*(n-r.*r);\n\n numAdded=numAdded+1;\n xEst(:,numAdded)=[u;uDot];\n end\nend\n\n%Shrink to fit the actual number of solutions added.\nxEst=xEst(:,1:numAdded);\n\n%Undo the effects of scaling:\nxEst=scalFactor*xEst;\n\n%Add back in the offset that was present due to centering the coordinate\n%system around the sensors.\nxEst(1:3,:)=bsxfun(@plus,xEst(1:3,:),centerOfRegion);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Static_Estimation/Uses_External_Solver/DopplerOnlyInit6D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6466714585359242}} {"text": "function cheby_u_poly_values_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBY_U_POLY_VALUES_TEST demonstrates the use of CHEBY_U_POLY_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBY_U_POLY_VALUES_TEST:\\n' );\n fprintf ( 1, ' CHEBY_U_POLY_VALUES returns values of\\n' );\n fprintf ( 1, ' the Chebyshev U polynomials.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N X U(N)(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, x, fx ] = cheby_u_poly_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %4d %8f %24.16f\\n', n, x, fx );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/cheby_u_poly_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.6466714510146689}} {"text": "function bd = blk_diag(A,n)\n%BLK_DIAG Make or extract a sparse block diagonal matrix\n% function bd = blk_diag(A,n);\n% If A is not sparse, then\n% returns a sparse block diagonal \"bd\", diagonalized from the\n% elements in \"A\".\n% \"A\" is ma x na, comprising bdn=(na/\"n\") blocks of submatrices.\n% Each submatrix is ma x \"n\", and these submatrices are\n% placed down the diagonal of the matrix.\n%\n% If A is already sparse, then the operation is reversed, yielding a block\n% row matrix, where each set of n columns corresponds to a block element\n% from the block diagonal.\n%\n% Routine uses NO for-loops for speed considerations.\n\n% Copyright (c) 1993-1995, The Regents of the University of California.\n% This software was produced under a U.S. Government contract\n% (W-7405-ENG-36) by Los Alamos National Laboratory, which is operated\n% by the University of California for the U.S. Department of Energy,\n% and was funded in part by NIH grant R01-MH53213 through the University\n% of Southern California to Los Alamos National Laboratory, \n% and was funded in part by NIH grant R01-EY08610 to Los Alamos\n% National Laboratory.\n% The U.S. Government is licensed to use, reproduce, and distribute this\n% software. Permission is granted to the public to copy and use this\n% software without charge, provided that this Notice and any statement\n% of authorship are reproduced on all copies. Neither the Government\n% nor the University makes any warranty, express or implied, or assumes\n% any liability or responsibility for the use of this software.\n%\n% Author: John C. Mosher, Ph.D.\n% Los Alamos National Laboratory\n% Group ESA-MT, MS J580\n% Los Alamos, NM 87545\n% email: mosher@LANL.Gov\n\n% July 29, 1993 Author\n% September 28, 1993 JCM Conversion to sparse\n% July 27, 1995 JCM inverse block diagonal added\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n\nif(~issparse(A)),\t\t% then make block sparse\n [ma,na] = size(A);\n bdn = na/n; \t\t\t% number of submatrices\n \n if(bdn - fix(bdn)),\n error('Width of matrix must be even multiple of n');\n end\n \n if(0)\n i = [1:ma]';\n i = i(:,ones(1,n));\n i = i(:); \t\t\t% row indices first submatrix\n \n ml = length(i); \t\t% ma*n\n \n % ndx = [0:(bdn-1)]*ma; \t% row offsets per submatrix\n ndx = [0:ma:(ma*(bdn-1))]; \t% row offsets per submatrix\n \n i = i(:,ones(1,bdn)) + ndx(ones(ml,1),:);\n else\n tmp = reshape([1:(ma*bdn)]',ma,bdn);\n i = zeros(ma*n,bdn);\n for iblock = 1:n,\n i((iblock-1)*ma+[1:ma],:) = tmp;\n end\n end\n \n i = i(:); \t\t\t% row indices foreach sparse bd\n \n \n j = [1:na];\n j = j(ones(ma,1),:);\n j = j(:); \t\t\t% column indices foreach sparse bd\n \n bd = sparse(i,j,A(:));\n \nelse \t\t\t\t% already is sparse, unblock it\n \n [mA,na] = size(A);\t\t% matrix always has na columns\n % how many entries in the first column?\n bdn = na/n;\t\t\t% number of blocks\n ma = mA/bdn;\t\t\t% rows in first block\n \n % blocks may themselves contain zero entries. Build indexing as above\n if(0)\n i = [1:ma]';\n i = i(:,ones(1,n));\n i = i(:); \t\t\t% row indices first submatrix\n \n ml = length(i); \t\t% ma*n\n \n % ndx = [0:(bdn-1)]*ma; \t% row offsets per submatrix\n ndx = [0:ma:(ma*(bdn-1))]; \t% row offsets per submatrix\n \n i = i(:,ones(1,bdn)) + ndx(ones(ml,1),:);\n else\n tmp = reshape([1:(ma*bdn)]',ma,bdn);\n i = zeros(ma*n,bdn);\n for iblock = 1:n,\n i((iblock-1)*ma+[1:ma],:) = tmp;\n end\n end\n \n i = i(:); \t\t\t% row indices foreach sparse bd\n \n \n if(0)\n j = [1:na];\n j = j(ones(ma,1),:);\n j = j(:); \t\t\t% column indices foreach sparse bd\n \n % so now we have the complete two dimensional indexing. Convert to\n % one dimensional\n \n i = i + (j-1)*mA;\n else\n j = [0:mA:(mA*(na-1))];\n j = j(ones(ma,1),:);\n j = j(:);\n \n i = i + j;\n end\n \n bd = full(A(i)); \t% column vector\n bd = reshape(bd,ma,na);\t% full matrix\nend\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/forward/private/blk_diag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6466714434934133}} {"text": "function [ cdf ] = gsp_erdos_renyi_warp( ss , N , p )\n\n\ncutoff=4; % parameter to approximate the non-compactly supported distribution (the free convolution) by a compactly supported one, just for numerical purposes\n% To do: pass a parameter\n\nnum_pts=length(ss);\nif num_pts > 2\n delta=min(ss(2:num_pts)-ss(1:(num_pts-1)));\nelse\n delta=.1;\nend\n\ncdf=zeros(size(ss));\n\nfor k=1:num_pts\n if ss(k) > (p*N-cutoff*sqrt(p*(1-p)*N)-delta)\n if ss(k) <= (p*N+cutoff*sqrt(p*(1-p)*N)+delta)\n xx=(p*N-cutoff*sqrt(p*(1-p)*N)-2*delta):delta:ss(k);\n cdf(k)=trapz(xx,sqrt(1/((1-p)*N*p))*gsp_free_conv_norm_semi((xx-p*N)/(sqrt(p*(1-p)*N))));\n else\n cdf(k)=1;\n end\n end\nend\n\nend\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/filters/utils/gsp_erdos_renyi_warp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.646576448332235}} {"text": "function [movie_frame] = show_s2_partition(N,varargin)\n%SHOW_S2_PARTITION 3D illustration of an EQ partition of S^2\n%\n%Syntax\n% [movie_frame] = show_s2_partition(N,options);\n%\n%Description\n% SHOW_S2_PARTITION(N) uses a 3d plot to illustrate the partition of\n% the unit sphere S^2 into N regions.\n%\n% MOVIE_FRAME = SHOW_S2_PARTITION(N) sets MOVIE_FRAME to be an array of\n% movie frames for use with MOVIE. The movie frames will contain the region by\n% region build-up of the illustration.\n%\n% SHOW_S2_PARTITION(N,'offset','extra') uses experimental extra offsets.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% SHOW_S2_PARTITION(N,options) also recognizes a number of illustration\n% options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% SHOW_S2_PARTITION(N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% SHOW_S2_PARTITION(N,'title','show')\n% SHOW_S2_PARTITION(N,'title','hide')\n% Show or hide title (default 'show').\n%\n% SHOW_S2_PARTITION(N,'points','show')\n% SHOW_S2_PARTITION(N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% SHOW_S2_PARTITION(N,'sphere','show')\n% SHOW_S2_PARTITION(N,'sphere','hide')\n% Show or hide the unit sphere S^2 (default 'show').\n%\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Examples\n% > show_s2_partition(10)\n% > frames=show_s2_partition(9,'offset','extra')\n% frames =\n% 1x10 struct array with fields:\n% cdata\n% colormap\n% > show_s2_partition(99,'points','hide')\n%\n%See also\n% MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Function changed name from s2x to polar2cart\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.show_title = true;\ngdefault.show_points = true;\ngdefault.show_sphere = true;\ngopt = illustration_options(gdefault, varargin{:});\n\ndim = 2;\n\nsurf_jet;\n\nif gopt.show_title\n if gopt.show_points\n pointstr = ', showing the center point of each region';\n else\n pointstr = '';\n end\n titlestr = sprintf(...\n '\\nRecursive zonal equal area partition of {S^2} \\n into %d regions%s.',...\n N,pointstr);\n title(titlestr,'FontWeight','bold','FontUnits','normalized',...\n 'FontSize',gopt.fontsize/512);\nend\n\nframe_no = 1;\nif nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\nend\n\nif gopt.show_sphere\n show_s2_sphere;\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nR = eq_regions(dim,N,popt.extra_offset);\ntop_colat = 0;\nfor i = N:-1:2\n if top_colat ~= R(2,1,i)\n top_colat = R(2,1,i);\n pause(0);\n end\n show_s2_region(R(:,:,i),N);\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nif gopt.show_points\n x = eq_point_set(dim,N,popt.extra_offset);\n show_r3_point_set(x,'sphere','hide','title','hide');\n hold on\n if nargout > 0\n movie_frame(frame_no) = getframe(gcf);\n frame_no = frame_no + 1;\n end\nend\n\nhold off\n%\n% end function\n\nfunction show_s2_region(region,N)\n%SHOW_S2_REGION Illustrate a region of S^2\n%\n%Syntax\n% show_s2_region(region,N);\n%\n%Description\n% SHOW_S2_REGION(REGION,N) uses 3D surface plots to illustrate a region of S^2.\n% The region is given as a 2 x 2 matrix in spherical polar coordinates\n\ntol = eps*2^5;\n\ndim = size(region,1);\nt = region(:,1);\nb = region(:,2);\n\nif abs(b(1)) < tol\n b(1) = 2*pi;\nend\npseudo = 0;\nif abs(t(1)) < tol && abs(b(1)-2*pi) < tol\n pseudo = 1;\nend\nn = 21;\ndelta = 1/(n-1);\nh = 0:delta:1;\nt_to_b = zeros(dim,n);\nb_to_t = t_to_b;\nr = sqrt(1/N)/12;\nfor k = 1:dim\n if ~pseudo || k < 2\n L = 1:dim;\n j(L) = mod(k+L,dim)+1;\n t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h;\n t_to_b(j(2),:) = t(j(2))*ones(1,n);\n t_to_b_x = polar2cart(t_to_b);\n [X,Y,Z] = fatcurve(t_to_b_x,r);\n surface(X,Y,Z,-ones(size(Z)),...\n 'FaceColor','interp','FaceLighting','phong','EdgeColor','none')\n axis equal\n hold on\n end\nend\ngrid off\naxis off\n%\n% end function\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/eq_sphere_partitions/eq_illustrations/show_s2_partition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6465663918282217}} {"text": "function prob_test162 ( )\n\n%*****************************************************************************80\n%\n%% TEST162 tests ZIPF_SAMPLE.\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 nsample = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST162\\n' );\n fprintf ( 1, ' For the Zipf PDF:\\n' );\n fprintf ( 1, ' ZIPF_SAMPLE samples.\\n' );\n\n a = 4.0;\n\n check = zipf_check ( a );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST162 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n mean = zipf_mean ( a );\n variance = zipf_variance ( a );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF mean = %14f\\n', mean );\n fprintf ( 1, ' PDF variance = %14f\\n', variance );\n\n for i = 1 : nsample\n [ x(i), seed ] = zipf_sample ( a, seed );\n end\n\n mean = i4vec_mean ( nsample, x );\n variance = i4vec_variance ( nsample, x );\n xmax = max ( x(1:nsample) );\n xmin = min ( x(1:nsample) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sample size = %6d\\n', nsample );\n fprintf ( 1, ' Sample mean = %14f\\n', mean );\n fprintf ( 1, ' Sample variance = %14f\\n', variance );\n fprintf ( 1, ' Sample maximum = %6d\\n', xmax );\n fprintf ( 1, ' Sample minimum = %6d\\n', xmin );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/prob_test162.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928797973181, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.6465663682783781}} {"text": " function sn = nufft_scale(Nd, Kd, alpha, beta, Nmid)\n%function sn = nufft_scale(Nd, Kd, alpha, beta, Nmid)\n%|\n%| Compute scaling factors for NUFFT\n%|\n%| in\n%|\tNd,Kd\n%|\talpha\t{d}\n%|\tbeta\t{d}\n%|\n%| option\n%|\tNmid\t[d]\t\tmidpoint: floor(Nd/2) or default (Nd-1)/2\n%|\n%| out\n%|\tsn\t[[Nd]]\t\tscaling factors\n%|\n%| Copyright 2004-7-8, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(Nd, 'test'), nufft_scale_test, return, end\nif nargin < 4, ir_usage, end\n\nif nargin < 5, Nmid = (Nd-1)/2; end\n\ndd = length(Nd);\nif dd == 1 && ~iscell(alpha) % 1D case\n\tsn = nufft_scale1(Nd(1), Kd(1), alpha, beta, Nmid(1));\nreturn\nend\n\n\n% scaling factors: \"outer product\" of 1D vectors\nsn = 1;\nfor id=1:dd\n\ttmp = nufft_scale1(Nd(id), Kd(id), alpha{id}, beta{id}, Nmid(id));\n\tsn = sn(:) * tmp';\nend\nif length(Nd) > 1\n\tsn = reshape(sn, Nd);\t% [(Nd)]\nelse\n\tsn = sn(:);\t% [(Nd)]\nend\n\n\n% Compute scaling factors for 1D NUFFT (from Fourier series coefficients)\n% in:\n%\tN,K\n%\talpha\n%\tbeta\n% out:\n%\tsn\t[N]\t\tscaling factors\n%\n% Copyright 2001-10-4, Jeff Fessler, The University of Michigan\n\nfunction sn = nufft_scale1(N, K, alpha, beta, Nmid)\n\nif ~isreal(alpha(1)), error 'need real alpha_0', end\nL = length(alpha) - 1;\n\n%\n% compute scaling factors from Fourier coefficients\n%\nif L > 0\n\tsn = zeros(N,1);\n\tn = [0:(N-1)]';\n\ti_gam_n_n0 = 1i * (2*pi/K) * (n - Nmid) * beta;\n\n\tfor l1=-L:L\n\t\talf = alpha(abs(l1)+1);\n\t\tif l1 < 0, alf = conj(alf); end\n\t\tsn = sn + alf * exp(i_gam_n_n0 * l1);\n\tend\n\nelse\n\tsn = alpha * ones(N,1);\nend\n\n\n% self test\nfunction nufft_scale_test\n\nN = 100;\nK = 2*N;\nalpha = [1.0 -0.0 -0.2];\nsn = nufft_scale(N, K, alpha, 1);\nif im\n\tn = [0:(N-1)]';\n\tclf, plot(n, real(sn), 'r-', n, imag(sn), 'b-')\n\tir_legend({'$s[n]$ real', '$s[n]$ imag'})\n\tylabelf('$s[n]$')\n\txlabelf('$n$')\nend\n\npr minmax(real(sn))\npr minmax(imag(sn))\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/nufft_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6465657389037092}} {"text": "function coeffs = alias(coeffs, m)\n%ALIAS Alias Chebyshev coefficients on the 1st kind Chebyshev grid.\n% ALIAS(C, M) aliases the Chebyshev coefficients stored in the column vector C\n% to have length M. If M > LENGTH(C), the coefficients are padded with zeros.\n% If C is a matrix of coefficients, each of the columns is aliased to length\n% M.\n%\n% See also PROLONG.\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% Note that the formula for aliasing on the 1st-kind Chebyshev grid is\n% different from that for the 2nd-kind grid, even though the coefficients \n% being aliased are for 1st-kind Chebyshev polynomials in both cases. \n%\n% Useful References:\n% Fox, L. and Parker, I. B., Chebyshev polynomials in Numerical Analysis,\n% Oxford University Press, 1972. (pp. 67)\n%\n% Mason, J. C. and Handscomb, D. C., Chebyshev polynomials, Chapman &\n% Hall/CRC, Boca Raton, FL, 2003. (pp. 153)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nn = size(coeffs, 1);\n\n% Pad with zeros:\nif ( m > n )\n coeffs = [ coeffs ; zeros(m-n, size(coeffs, 2)) ];\n return\nend\n\n% Alias coefficients:\nif ( m == 1 )\n % Reduce to a single point:\n e = ones(1, ceil(n/2)); \n e(2:2:end) = -1;\n coeffs = e*coeffs(1:2:end,:);\nelseif ( m > n/2 )\n % If m > n/2, only single coefficients are aliased, and we can vectorise.\n j = ((m + 1):n).';\n k = abs(mod(j + m - 2, 2*m) - m + 1) + 1;\n p = floor((j-1+m)/(2*m));\n t = (-1).^p;\n coeffs(k,:) = coeffs(k,:) + bsxfun(@times, t, coeffs(j,:));\nelse\n % Otherwise we must do everything in a tight loop. (Which is slower!)\n for j = (m + 1):n\n k = abs(mod(j + m - 2, 2*m) - m + 1) + 1;\n sgn = 1 - 2*mod(floor((j - 1 + m)/(2*m)), 2);\n coeffs(k,:) = coeffs(k,:) + sgn*coeffs(j,:);\n end\nend\n\n% Truncate:\ncoeffs = coeffs(1:m,:);\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/@chebtech1/alias.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6465657238097302}} {"text": "function element_neighbor = triangulation_neighbor_elements ( ...\n element_order, element_num, element_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_NEIGHBOR_ELEMENTS determines element neighbors.\n%\n% Discussion:\n%\n% A triangulation of a set of nodes can be completely described by\n% the coordinates of the nodes, and the list of nodes that make up\n% each element. However, in some cases, it is necessary to know\n% element adjacency information, that is, which element, if any,\n% is adjacent to a given element on a particular side.\n%\n% This routine creates a data structure recording this information.\n%\n% The primary amount of work occurs in sorting a list of 3 * ELEMENT_NUM\n% data items.\n%\n% This routine was modified to use columns instead of rows.\n%\n% Example:\n%\n% The input information from ELEMENT_NODE:\n%\n% Element Nodes\n% -------- ---------------\n% 1 3 4 1\n% 2 3 1 2\n% 3 3 2 8\n% 4 2 1 5\n% 5 8 2 13\n% 6 8 13 9\n% 7 3 8 9\n% 8 13 2 5\n% 9 9 13 7\n% 10 7 13 5\n% 11 6 7 5\n% 12 9 7 6\n% 13 10 9 6\n% 14 6 5 12\n% 15 11 6 12\n% 16 10 6 11\n%\n% The output information in ELEMENT_NEIGHBOR:\n%\n% Element Neighboring Elements\n% -------- ---------------------\n%\n% 1 -1 -1 2\n% 2 1 4 3\n% 3 2 5 7\n% 4 2 -1 8\n% 5 3 8 6\n% 6 5 9 7\n% 7 3 6 -1\n% 8 5 4 10\n% 9 6 10 12\n% 10 9 8 11\n% 11 12 10 14\n% 12 9 11 13\n% 13 -1 12 16\n% 14 11 -1 15\n% 15 16 14 -1\n% 16 13 15 -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ELEMENT_ORDER, the order of the element.\n%\n% Input, integer ELEMENT_NUM, the number of element.\n%\n% Input, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM), the nodes that \n% make up each element.\n%\n% Output, integer ELEMENT_NEIGHBOR(3,ELEMENT_NUM), the three elements that are direct\n% neighbors of a given element. ELEMENT_NEIGHBOR(1,I) is the index of the element\n% which touches side 1, defined by nodes 2 and 3, and so on. ELEMENT_NEIGHBOR(1,I)\n% is negative if there is no neighbor on that side. In this case, that\n% side of the element lies on the boundary of the triangulation.\n%\n\n%\n% Step 1.\n% From the list of nodes for element E, of the form: (I,J,K)\n% construct the three neighbor relations:\n%\n% (I,J,3,E) or (J,I,3,E),\n% (J,K,1,E) or (K,J,1,E),\n% (K,I,2,E) or (I,K,2,E)\n%\n% where we choose (I,J,3,E) if I < J, or else (J,I,3,E)\n%\n col = zeros ( 4, 3 * element_num );\n\n for element = 1 : element_num\n\n i = element_node(1,element);\n j = element_node(2,element);\n k = element_node(3,element);\n\n if ( i < j )\n col(1:4,1+3*(element-1)) = [ i, j, 3, element ]';\n else\n col(1:4,1+3*(element-1)) = [ j, i, 3, element ]';\n end\n\n if ( j < k )\n col(1:4,2+3*(element-1)) = [ j, k, 1, element ]';\n else\n col(1:4,2+3*(element-1)) = [ k, j, 1, element ]';\n end\n\n if ( k < i )\n col(1:4,3+3*(element-1)) = [ k, i, 2, element ]';\n else\n col(1:4,3+3*(element-1)) = [ i, k, 2, element ]';\n end\n\n end\n%\n% Step 2. Perform an ascending dictionary sort on the neighbor relations.\n% We only intend to sort on rows 1 and 2; the routine we call here\n% sorts on rows 1 through 4 but that won't hurt us.\n%\n% What we need is to find cases where two elements share an edge.\n% Say they share an edge defined by the nodes I and J. Then there are\n% two columns of COL that start out ( I, J, ?, ? ). By sorting COL,\n% we make sure that these two columns occur consecutively. That will\n% make it easy to notice that the elements are neighbors.\n%\n col = i4col_sort_a ( 4, 3*element_num, col );\n%\n% Step 3. Neighboring elements show up as consecutive columns with\n% identical first two entries. Whenever you spot this happening,\n% make the appropriate entries in ELEMENT_NEIGHBOR.\n%\n element_neighbor(1:3,1:element_num) = -1;\n\n icol = 1;\n\n while ( 1 )\n\n if ( 3 * element_num <= icol )\n break\n end\n\n if ( col(1,icol) ~= col(1,icol+1) || col(2,icol) ~= col(2,icol+1) )\n icol = icol + 1;\n continue\n end\n\n side1 = col(3,icol);\n element1 = col(4,icol);\n side2 = col(3,icol+1);\n element2 = col(4,icol+1);\n\n element_neighbor(side1,element1) = element2;\n element_neighbor(side2,element2) = element1;\n\n icol = icol + 2;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangulation/triangulation_neighbor_elements.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.6465311344082822}} {"text": "% Small technical example.\n% Performs a check on the computation of certain central moments\n% on a quincunx grid.\n%\ndisp('Small technical example.');\ndisp('Performs a check on the computation of certain central moments');\ndisp('on a quincunx grid.');\ndisp('FOR MORE INFORMATION: help Q0011mupq');\ndisp(' ');\ndisp('See also the report http://repository.cwi.nl:8888/cwi_repository/docs/IV/04/04178D.pdf');\ndisp('Dr. Paul M. de Zeeuw ');\ndisp(' (C) 1998-2006 Stichting CWI, Amsterdam, The Netherlands');\ndisp(' ');\n%---INSERT YOUR IMAGE HERE-----------------------------------------------------\nif exist('imread','file') == 2\n Orig = double(imread('zenithgray.TIF','tiff'));\nelse\n load zenithgray; Orig = zenithgray; clear zenithgray;\nend\n%\ndisp([' Dimensions ' int2str( size(Orig) )]);\n%---EXTRACT A QUINCUNX GRIDFUNCTION-----\nF00 = getcolor00(Orig);\nF11 = getcolor11(Orig);\ndisp('The dimensions of the extracted quincunx gridfunction read as follows');\ndisp([int2str(size(F00)) ' and ' int2str(size(F11))]);\n%\n%---COMPUTE MASS------------------------\nmu00 = Q0011mupq(F00, F11, 0, 0);\ndisp([' Mass ' num2str( mu00, '%+12.4e')]);\n%---NICE CHECK: OUTCOME SHOULD VANISH---\nmu10 = Q0011mupq(F00, F11, 1, 0);\ndisp(' NICE CHECK: First order central moment (x-dir) should vanish');\ndisp([' reads ' num2str( mu10, '%+12.4e')]);\n%---NICE CHECK: OUTCOME SHOULD VANISH---\nmu01 = Q0011mupq(F00, F11, 0, 1);\ndisp(' NICE CHECK: First order central moment (y-dir) should vanish');\ndisp([' reads ' num2str( mu01, '%+12.4e')]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13507-lisq-a-toolbox-for-the-lifting-scheme-on-2d-quincunx-grids/LISQ/example09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6464779624782069}} {"text": "function [y] = temporal_agg_p(z,op1,sc)\n% PURPOSE: Temporal aggregation of a time series preserving its dimension\n% ------------------------------------------------------------\n% SYNTAX: y = temporal_agg_p(z,op1,sc);\n% ------------------------------------------------------------\n% OUTPUT: y: nx1 temporally aggregated series, missing=0\n% ------------------------------------------------------------\n% INPUT: z: nx1 ---> vector of high frequency data\n% op1: type of temporal aggregation \n% op1=1 ---> sum (flow)\n% op1=2 ---> average (index)\n% op1=3 ---> last element (stock) ---> interpolation\n% op1=4 ---> first element (stock) ---> interpolation\n% sc: number of high frequency data points \n% for each low frequency data points\n% Note: n = sc x N\n% ------------------------------------------------------------\n% LIBRARY: aggreg\n% ------------------------------------------------------------\n\n% written by:\n% Enrique M. Quilis\n% Macroeconomic Research Department\n% Ministry of Economy and Competitiveness\n% \n% Version 1.0 [October 2010]\n\n[n,m] = size(z);\n\n% ------------------------------------------------------------\n% Computes the number of low frequency points. \n% Low frequency periods should be complete\n\nN = fix(n/sc);\nC = aggreg_p(op1,n,sc);\n\n% -----------------------------------------------------------\n% Expanding the aggregation matrix to perform\n% extrapolation if needed.\n\nif (n > sc * N)\n pred = n - sc*N; % Number of required extrapolations \n C=[C zeros(N,pred)];\nelse\n pred = 0;\nend\n\ny = C*z;\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/39770-temporal-disaggregation-library/temporal_agg_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6464473082030391}} {"text": "function [t,s]=zerocros(x,m)\n%ZEROCROS finds the zeros crossings in a signal [T,S]=(X,M)% find zero crossings in a signal\n% Inputs: x = input waveform\n% m = mode string containing:\n% 'p' - positive crossings only\n% 'n' - negative crossings only\n% 'b' - both (default)\n% 'r' - round to integer values\n%\n% Outputs: t = sample positions of zero crossings (not necessarily integers)\n% s = estimated slope of x at the zero crossing\n%\n% This routine uses linear interpolation to estimate the position of a zero crossing\n% A zero crossing occurs between x(n) and x(n+1) iff (x(n)>=0) ~= (x(n+1)>=0)\n\n% Example: x=sin(2*pi*(0:1000)/200); x(1:100:1001)=0; zerocros(x);\n% Note that we get a zero crossing at the end but not at the start.\n\n%\t Copyright (C) Mike Brookes 2003-2015\n% Version: $Id: zerocros.m 6077 2015-04-20 07:08:39Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<2\n m='b';\nend\ns=x>=0;\nk=s(2:end)-s(1:end-1);\nif any(m=='p')\n f=find(k>0);\nelseif any(m=='n')\n f=find(k<0);\nelse\n f=find(k~=0);\nend\ns=x(f+1)-x(f);\nt=f-x(f)./s;\nif any(m=='r')\n t=round(t);\nend\nif ~nargout\n n=length(x);\n plot(1:n,x,'-',t,zeros(length(t),1),'o');\nend\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/voicebox/zerocros.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6463174082086348}} {"text": "function [im_x, im_y] = project( camera, world_X, world_Y, world_Z )\n%PROJECT: project a 3D point into an image\n%\n% [IM_X,IM_Y] = PROJECT(CAMERA,WORLD_X,WORLD_Y,WORLD_Z) projects one or\n% more 3D point in the world coordinate frame into image coordinates\n\n% Copyright 2005-2009 The MathWorks, Inc.\n% $Revision: 1.0 $ $Date: 2006/06/30 00:00:00 $\n\nz = camera.rawP(3,1) * world_X ...\n + camera.rawP(3,2) * world_Y ...\n + camera.rawP(3,3) * world_Z ...\n + camera.rawP(3,4);\nim_y = round( (camera.rawP(2,1) * world_X ...\n + camera.rawP(2,2) * world_Y ...\n + camera.rawP(2,3) * world_Z ...\n + camera.rawP(2,4)) ./ z);\nim_x = round( (camera.rawP(1,1) * world_X ...\n + camera.rawP(1,2) * world_Y ...\n + camera.rawP(1,3) * world_Z ...\n + camera.rawP(1,4)) ./ z);\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/26160-carving-a-dinosaur/SpaceCarving/+spacecarving/project.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6462383452473871}} {"text": "% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction EU = SimpleCalcExpectedUtility(I)\n\n % Inputs: An influence diagram, I (as described in the writeup).\n % I.RandomFactors = list of factors for each random variable. These are CPDs, with\n % the child variable = D.var(1)\n % I.DecisionFactors = factor for the decision node.\n % I.UtilityFactors = list of factors representing conditional utilities.\n % Return Value: the expected utility of I\n % Given a fully instantiated influence diagram with a single utility node and decision node,\n % calculate and return the expected utility. Note - assumes that the decision rule for the \n % decision node is fully assigned.\n\n % In this function, we assume there is only one utility node.\n F = [I.RandomFactors I.DecisionFactors];\n U = I.UtilityFactors(1);\n EU = [];\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % YOUR CODE HERE\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n Fnew = VariableElimination(F,setdiff(unique([F.var]),U.var));\n %Fnew = F;\n out = Fnew(1);\n for i = 2:length(Fnew)\n\t out = FactorProduct(out,Fnew(i));\n end\n \n hha = U;\n hha.val = ones(1,length(U.val));\n out = FactorProduct(hha,out);\n U = FactorProduct(hha,U);\n %out = FactorMarginalization(out,setdiff(unique([F.var]),U.var));\n\nEU = [sum(out.val.*U.val)];\n \n \n \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/6.Decision Making/SimpleCalcExpectedUtility.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6461035857741372}} {"text": "function lik = lik_multinom(varargin)\n%LIK_MULTINOM Create a multinomial likelihood structure \n%\n% Description\n% LIK = LIK_MULTINOM creates multinomial likelihood for multi-class\n% count data. The observed numbers in each class with C classes is\n% given as 1xC vector.\n%\n% The likelihood is defined as follows:\n% __ n __ C \n% p(y|f^1, ..., f^C, z) = || i=1 [ gamma(N+1) || c=1 p_i^c^(y_i^c)/gamma(y_i^c+1)]\n%\n% where p_i^c = exp(f_i^c)/ (sum_c=1^C exp(f_i^c)) is the succes \n% probability for class c, which is a function of the latent variable \n% f_i^c for the corresponding class and N=sum(y) is the number of trials.\n%\n% See also\n% GP_SET, LIK_*\n%\n% Copyright (c) 2010 Jaakko Riihimäki, Pasi Jylänki\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2010 Jarno Vanhatalo\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_MULTINOM';\n ip.addOptional('lik', [], @isstruct);\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'Multinom';\n lik.nondiagW = true;\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Multinom')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n\n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_multinom_pak;\n lik.fh.unpak = @lik_multinom_unpak;\n lik.fh.ll = @lik_multinom_ll;\n lik.fh.llg = @lik_multinom_llg; \n lik.fh.llg2 = @lik_multinom_llg2;\n lik.fh.llg3 = @lik_multinom_llg3;\n lik.fh.tiltedMoments = @lik_multinom_tiltedMoments;\n lik.fh.predy = @lik_multinom_predy;\n lik.fh.invlink = @lik_multinom_invlink;\n lik.fh.recappend = @lik_multinom_recappend;\n end\n\nend \n\nfunction [w,s,h] = lik_multinom_pak(lik)\n%LIK_MULTINOM_PAK Combine likelihood parameters into one vector.\n%\n% Description \n% W = LIK_MULTINOM_PAK(LIK) takes a likelihood structure LIK and\n% returns an empty verctor W. If Multinom likelihood had\n% parameters this would combine them into a single row vector\n% W (see e.g. lik_negbin). This is a mandatory subfunction used \n% for example in energy and gradient computations.\n% \n%\n% See also\n% LIK_MULTINOM_UNPAK, GP_PAK\n \n w = []; s = {};h=[];\nend\n\n\nfunction [lik, w] = lik_multinom_unpak(lik, w)\n%LIK_MULTINOM_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_MULTINOM_UNPAK(W, LIK) Doesn't do anything.\n% \n% If Multinom likelihood had parameters this would extracts them\n% parameters from the vector W to the LIK structure. This is a \n% mandatory subfunction used for example in energy and gradient \n% computations.\n% \n%\n% See also\n% LIK_MULTINOM_PAK, GP_UNPAK\n\n lik=lik;\n w=w;\nend\n\n\nfunction ll = lik_multinom_ll(lik, y, f, z)\n%LIK_MULTINOM_LL Log likelihood\n%\n% Description\n% LL = LIK_MULTINOM_LL(LIK, Y, F) takes a likelihood structure\n% LIK, class counts Y (NxC matrix), and latent values F (NxC\n% matrix). Returns the log likelihood, log p(y|f,z). This \n% subfunction is needed when using Laplace approximation or \n% MCMC for inference with non-Gaussian likelihoods. This \n% subfunction is also used in information criteria \n% (DIC, WAIC) computations.\n%\n% See also\n% LIK_MULTINOM_LLG, LIK_MULTINOM_LLG3, LIK_MULTINOM_LLG2, GPLA_E\n \n f=reshape(f,size(y));\n expf = exp(f);\n p = expf ./ repmat(sum(expf,2),1,size(expf,2));\n N = sum(y,2);\n \n ll = sum(gammaln(N+1) - sum(gammaln(y+1),2) + sum(y.*log(p),2) );\n \nend\n\n\nfunction llg = lik_multinom_llg(lik, y, f, param, z)\n%LIK_MULTINOM_LLG Gradient of the log likelihood\n%\n% Description\n% LLG = LIK_MULTINOM_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F. Returns\n% the gradient of the log likelihood with respect to PARAM. At\n% the moment PARAM can be 'param' or 'latent'. This subfunction \n% is needed when using Laplace approximation or MCMC for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG2, LIK_MULTINOM_LLG3, GPLA_E\n \n f=reshape(f,size(y));\n C = size(y,2);\n expf2 = exp(f);\n N=sum(y, 2);\n pi2 = (N*ones(1,C)).*expf2./(sum(expf2, 2)*ones(1,C));\n pi_vec=pi2(:);\n llg = y(:)-pi_vec;\n \nend\n\n\nfunction [pi_vec, pi_mat] = lik_multinom_llg2(lik, y, f, param, z)\n%LIK_MULTINOM_LLG2 Second gradients of the log likelihood\n%\n% Description \n% LLG2 = LIK_MULTINOM_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F. Returns\n% the Hessian of the log likelihood with respect to PARAM. At\n% the moment PARAM can be only 'latent'. LLG2 is a vector with\n% diagonal elements of the Hessian matrix (off diagonals are\n% zero). This subfunction is needed when using Laplace \n% approximation or EP for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG, LIK_MULTINOM_LLG3, GPLA_E\n \n% multinom:\n [n,nout]=size(y);\n N = sum(y,2)*ones(1,nout);\n f=reshape(f,n,nout);\n \n expf2 = exp(f);\n pi2 = expf2./(sum(expf2, 2)*ones(1,nout));\n pi_vec=pi2(:).*N(:);\n \n pi_mat=zeros(nout*n, n);\n for i1=1:nout\n pi_mat((1+(i1-1)*n):(nout*n+1):end)=pi2(:,i1).*sqrt(N(:,i1)); \n end\n % D = diag(pi_vec);\n % llg2 = -D + pi_mat*pi_mat';\n \nend \n\nfunction [dw_mat] = lik_multinom_llg3(lik, y, f, param, z)\n%LIK_MULTINOM_LLG3 Third gradients of the log likelihood\n%\n% Description\n% LLG3 = LIK_MULTINOM_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F and\n% returns the third gradients of the log likelihood with\n% respect to PARAM. At the moment PARAM can be only 'latent'. \n% LLG3 is a vector with third gradients. This subfunction is \n% needed when using Laplace approximation for inference with \n% non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG, LIK_MULTINOM_LLG2, GPLA_E, GPLA_G\n \n [n,nout] = size(y);\n f2 = reshape(f,n,nout);\n \n N=sum(y, 2);\n expf2 = exp(f2);\n pi2 = expf2./(sum(expf2, 2)*ones(1,nout));\n pi_vec=pi2(:);\n \n dw_mat=zeros(nout,nout,nout,n);\n \n for cc3=1:nout\n for ii1=1:n\n \n pic=pi_vec(ii1:n:(nout*n));\n for cc1=1:nout\n for cc2=1:nout\n \n % multinom third derivatives\n cc_sum_tmp=0;\n if cc1==cc2 && cc1==cc3 && cc2==cc3\n cc_sum_tmp=cc_sum_tmp+pic(cc1);\n end\n if cc1==cc2\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc3);\n end\n if cc2==cc3\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc2);\n end\n if cc1==cc3\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc2);\n end\n cc_sum_tmp=cc_sum_tmp+2*pic(cc1)*pic(cc2)*pic(cc3);\n \n dw_mat(cc1,cc2,cc3,ii1)=cc_sum_tmp.*N(ii1);\n end\n end\n end\n end\n \n \nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_multinom_tiltedMoments(lik, y, i1, S2_i, M_i, z)\n %LIK_COXPH_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n %\n % Description\n % [M_0, M_1, M2] = LIK_COXPH_TILTEDMOMENTS(LIK, Y, I, S2,\n % MYY, Z) takes a likelihood structure LIK, class labels\n % Y, index I and cavity variance S2 and\n % mean MYY. Returns the zeroth moment M_0, mean M_1 and\n % variance M_2 of the posterior marginal (see Rasmussen and\n % Williams (2006): Gaussian processes for Machine Learning,\n % page 55). This subfunction is needed when using EP for \n % inference with non-Gaussian likelihoods.\n %\n % See also\n % GPEP_E\n \n error('tiltedMoment has not been implemented for multinom likelihood');\n \nend\n\nfunction [lpy, Ey, Vary] = lik_multinom_predy(lik, Ef, Varf, yt, zt)\n%LIK_MULTINOM_PREDY Returns the predictive mean, variance and density of y\n%\n% Description\n% LPY = LIK_MULTINOM_PREDY(LIK, EF, VARF YT)\n% Returns logarithm of the predictive density PY of YT, that is\n% p(yt | y) = \\int p(yt | f) p(f|y) df.\n% This requires also the incedence counts YT. This subfunction \n% is needed when computing posterior predictive distributions for \n% future observations.\n%\n% [LPY, EY, VARY] = LIK_MULTINOM_PREDY(LIK, EF, VARF, YT) takes a\n% likelihood structure LIK, posterior mean EF and posterior\n% Variance VARF of the latent variable and returns the\n% posterior predictive mean EY and variance VARY of the\n% observations related to the latent variables. This subfunction\n% is needed when computing posterior predictive distributions for\n% future observations.\n%\n\n%\n% See also\n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n \n N=sum(yt,2);\n S=10000;\n [ntest, nout]=size(yt);\n pi=zeros(ntest,nout);\n lpy=zeros(ntest,nout);\n Ey=zeros(ntest,nout);\n Vary=zeros(size(Varf));\n Ef=reshape(Ef(:),ntest,nout);\n [notused,notused,c] =size(Varf);\n if c>1\n mcmc=false;\n else\n mcmc=true;\n Varf=reshape(Varf(:), ntest, nout);\n end\n for i1=1:ntest\n if mcmc\n Sigm_tmp = (Varf(i1,:));\n f_star=bsxfun(@plus, Ef(i1,:), bsxfun(@times, sqrt(Sigm_tmp), ...\n randn(S,nout)));\n else\n Sigm_tmp=(Varf(:,:,i1)'+Varf(:,:,i1))./2;\n f_star=mvnrnd(Ef(i1,:), Sigm_tmp, S);\n end\n \n tmp = exp(f_star);\n tmp = tmp./(sum(tmp, 2)*ones(1,size(tmp,2)));\n \n if nargout > 1\n Ey(i1,:) = N(i1).*mean(tmp);\n for z1 = 1:nout;\n for z2 = 1:nout\n for z3=1:S\n Var_tmp(:,:,z3) = (diag(tmp(z3,:)) - tmp(z3,:)'*tmp(z3,:));\n end\n if mcmc\n Vary(i1+(0:nout-1)*ntest,:) = diag(N(i1).*mean(Var_tmp,3));\n else\n Vary(:,:,i1) = N(i1).*mean(Var_tmp,3);\n end\n end\n end\n end\n lpy=[];\n if ~isempty(yt)\n ytmp = repmat(yt(i1,:),S,1);\n lpy(i1,:) = log(mean( mnpdf(ytmp,tmp) ));\n end\n end\n lpy=lpy(:);\n Ey=Ey(:);\n Vary=Vary(:);\nend\n\nfunction p = lik_multinom_invlink(lik, f, z)\n%LIK_MULTINOM_INVLINK Returns values of inverse link function\n% \n% Description \n% P = LIK_MULTINOM_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values of inverse link function P.\n% This subfunction is needed when using function gp_predprctmu.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_PREDY\np = multinominv(f).*z;\nend\n\nfunction reclik = lik_multinom_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = LIK_MULTINOM_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood record structure RECLIK, record index RI and\n% likelihood structure LIK with the current MCMC samples of\n% the parameters. Returns RECLIK which contains all the old\n% samples and the current samples from LIK. This subfunction \n% is needed when using MCMC sampling (gp_mc).\n% \n% See also\n% GP_MC\n\n if nargin == 2\n reclik.type = 'Multinom';\n reclik.nondiagW = true;\n\n % Set the function handles\n reclik.fh.pak = @lik_multinom_pak;\n reclik.fh.unpak = @lik_multinom_unpak;\n reclik.fh.ll = @lik_multinom_ll;\n reclik.fh.llg = @lik_multinom_llg; \n reclik.fh.llg2 = @lik_multinom_llg2;\n reclik.fh.llg3 = @lik_multinom_llg3;\n reclik.fh.tiltedMoments = @lik_multinom_tiltedMoments;\n reclik.fh.predy = @lik_multinom_predy;\n reclik.fh.invlink = @lik_multinom_invlink;\n reclik.fh.recappend = @lik_multinom_recappend;\n end\n \nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/lik_multinom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6461035838316804}} {"text": "function err = getL2error(node,elem,uexact,uh,quadOrder,varargin)\n%% GETL2ERROR L2 norm of the approximation error.\n%\n% err = getL2error(node,elem,@uexact,uh) computes the L2 norm of the error\n% between the exact solution uexact and a finite element approximation uh\n% on a mesh described by node and elem.\n%\n% The input parameter uexact is a function handle and uh is a column array\n% which could be:\n% - P0 element i.e. discontinuous and piecewise constant\n% - P1 element i.e. continuous and piecewise linear\n% - CR element i.e. piecewise linear and continuous at mid pts of edges\n% - P2 element i.e. continuous and piecewise quadratic\n% - P1+P0 element which could happen in the fluid application\n%\n% err = getL2error(node,elem,@uexact,uh,quadOrder) computes error\n% using the quadrature rule with order quadOrder (up to 5). The default\n% order is 3.\n% \n% Example: compute L2 error of piecewise linear interpolation\n%\n% [node,elem] = squaremesh([0,1,0,1],0.25);\n% for k = 1:4\n% exactu = inline('sin(pi*pxy(:,1)).*sin(pi*pxy(:,2))','pxy');\n% uI = exactu(node);\n% N(k) = size(node,1);\n% err(k) = getL2error(node,elem,exactu,uI);\n% [node,elem] = uniformrefine(node,elem);\n% end\n% showrate(N,err);\n%\n% The cubic element is added by Jie Zhou.\n%\n% See also getH1error, getL2error3, getH1error3, quadpts.\n% \n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nNu = length(uh); N = size(node,1); NT = size(elem,1); \n% Euler formula N-NE+NT = c % rough estimateus using Euler formula\nNE = N + NT; NP2 = N + NE; NP3 = N + 2*NE + NT; \n%% Default quadrature orders for different elements\nif Nu > N+NT-5\n elem2dof = dofP2(elem);\n NP2 = max(elem2dof(:));\n NE = NP2 - N;\n NP3 = N+2*NE+NT; \nend\n\n%% Default quadrature orders for different elements\nif ~exist('quadOrder','var')\n switch Nu\n case NT % piecewise constant function P0\n quadOrder = 2;\n case N % piecewise linear function P1 element\n quadOrder = 3; \n case NE % piecewise linear function CR element\n quadOrder = 3; \n case N+NT % piecewise linear function + constant function\n quadOrder = 3; \n case NP2 % piecewise quadratic function\n quadOrder = 4;\n case NE+NT % weak Galerkin element\n quadOrder = 3;\n case NP3 % P3 element\n quadOrder = 5; \n end\nend\n\n%% compute L2 error element-wise using quadrature rule with order quadOrder\nerr = zeros(NT,1);\n[lambda,weight] = quadpts(quadOrder);\n% basis function at quadrature points\nswitch Nu\n case N % P1 piecewise linear function\n phi = lambda; % linear bases\n case N+NT % P1+P0\n phi = lambda; % linear bases\n case NE % CR nonconforming P1 element\n phi = 1-2*lambda;\n elem2edge = elem2dof(:,4:6) - N;\n case NP2 % P2 piecewise quadratic elements\n phi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\n phi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\n phi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\n phi(:,4) = 4*lambda(:,2).*lambda(:,3);\n phi(:,5) = 4*lambda(:,1).*lambda(:,3);\n phi(:,6) = 4*lambda(:,2).*lambda(:,1);\n case NE+NT % weak Galerkin element\n% uhp = uh(1:NT); % only count the interior part\n phi = 1-2*lambda;\n elem2edge = elem2dof(:,4:6) - N + NT; \n case 2*NE+NT+N % P3 piecewise cubic elements \n phi(:,1) = 0.5*(3*lambda(:,1)-1).*(3*lambda(:,1)-2).*lambda(:,1); \n phi(:,2) = 0.5*(3*lambda(:,2)-1).*(3*lambda(:,2)-2).*lambda(:,2); \n phi(:,3) = 0.5*(3*lambda(:,3)-1).*(3*lambda(:,3)-2).*lambda(:,3);\n phi(:,4) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,5) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,3)-1); \n phi(:,6) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,3)-1); \n phi(:,7) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,1)-1); \n phi(:,8) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,1)-1);\n phi(:,9) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,10) = 27*lambda(:,1).*lambda(:,2).*lambda(:,3); \n elem2dof = dofP3(elem); \nend\nnQuad = size(lambda,1);\nfor p = 1:nQuad\n % evaluate uh at quadrature point\n switch Nu\n case NT % P0 piecewise constant function\n uhp = uh;\n case N % P1 piecewise linear function\n uhp = uh(elem(:,1))*phi(p,1) + ...\n uh(elem(:,2))*phi(p,2) + ...\n uh(elem(:,3))*phi(p,3);\n case N+NT % P1+P0\n uhp = uh(elem(:,1))*phi(p,1) + ...\n uh(elem(:,2))*phi(p,2) + ...\n uh(elem(:,3))*phi(p,3);\n uhp = uhp + uh(N+1:end);\n case NE % CR nonconforming P1 element\n uhp = uh(elem2edge(:,1))*phi(p,1) + ...\n uh(elem2edge(:,2))*phi(p,2) + ...\n uh(elem2edge(:,3))*phi(p,3);\n case NP2 % P2 piecewise quadratic function\n uhp = uh(elem2dof(:,1)).*phi(p,1) + ...\n uh(elem2dof(:,2)).*phi(p,2) + ...\n uh(elem2dof(:,3)).*phi(p,3) + ... \n uh(elem2dof(:,4)).*phi(p,4) + ...\n uh(elem2dof(:,5)).*phi(p,5) + ...\n uh(elem2dof(:,6)).*phi(p,6);\n case NP3\n uhp = uh(elem2dof(:,1)).*phi(p,1) + ...\n uh(elem2dof(:,2)).*phi(p,2) + ...\n uh(elem2dof(:,3)).*phi(p,3) + ...\n uh(elem2dof(:,4)).*phi(p,4) + ...\n uh(elem2dof(:,5)).*phi(p,5) + ...\n uh(elem2dof(:,6)).*phi(p,6) + ...\n uh(elem2dof(:,7)).*phi(p,7) + ...\n uh(elem2dof(:,8)).*phi(p,8) + ...\n uh(elem2dof(:,9)).*phi(p,9) + ...\n uh(elem2dof(:,10)).*phi(p,10);\n case NE+NT % weak Galerkin element\n% uhp = uh(1:NT); % only count the interior part\n uhp = uh(elem2edge(:,1))*phi(p,1) + ...\n uh(elem2edge(:,2))*phi(p,2) + ...\n uh(elem2edge(:,3))*phi(p,3);\n end\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n err = err + weight(p)*(uexact(pxy) - uhp).^2;\nend\n%% Modification\n% area of triangles\nve2 = node(elem(:,1),:)-node(elem(:,3),:);\nve3 = node(elem(:,2),:)-node(elem(:,1),:);\narea = 0.5*abs(-ve3(:,1).*ve2(:,2)+ve3(:,2).*ve2(:,1));\nerr = area.*err;\nerr(isnan(err)) = 0; % singular values, i.e. uexact(p) = infty, are excluded\nerr = sqrt(sum(err));", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/afem/getL2error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6460948684758508}} {"text": "function [A,E,Y] = singular_value_rpca( D, lambda, tau, delta, svdMethod, A0)\n\n% Solves the Robust PCA relaxation\n%\n% min \\tau ( |A|_* + \\lambda |E|_1 ) + 1/2 |(A,E)|_F^2\n% subj A+E = D\n%\n% by iterative thresholding.\n%\n% Inputs:\n% D -- the data matrix, m x n.\n% lambda -- relative weight of sparsity of error\n%\n% Optional:\n% tau -- magnitude of L2 relaxation of the pure robust PCA SDP,\n% higher value is desirable.\n% delta -- stepsize, should be in (0,1).\n% svdMethod -- SVD routine to be used in each iteration, must be one\n% of 'svdlibc', 'propack', or 'svds'. If not any of\n% these, default option is MATLAB's svd command. (May\n% require additional library dependencies if custom routine is used.)\n% A0 -- true low-rank solution, if known, to enable better display of\n% progress in each iteration.\n%\n% Outputs:\n% A -- estimate of the low-rank generating matrix\n% E -- estimate of the error or corruption\n%\n% Winter '08, John Wright, Shankar Rao. Questions? jnwright@uiuc.edu\n%\n% Copyright: Perception and Decision Laboratory\n%\t\t\tUniversity of Illinois, Urbana-Champaign \n\nVERBOSE = 2;\nEPSILON_PRIMAL = 5e-4;\n\nif nargin < 5, svdMethod = 'svd'; end\n\nif nargin < 4, delta = 0.9; end;\n\nif nargin < 3, tau = 1e4; end;\n\n\nMAX_ITER = 25000;\nDISPLAY_EVERY = 100;\n\n[m,n] = size(D);\n\nY = zeros(m,n); % Lagrange multiplier\nA = zeros(m,n); % Structure\nE = zeros(m,n); % Error\n\nrankA = 0;\n\niter = 0;\nconverged = false;\n\nwhile ~converged\n iter = iter + 1;\n \n switch lower(svdMethod)\n case 'svdlibc'\n [U,diagS,V] = svdlibc(Y, rankA+1);\n case 'propack'\n [U,S,V] = lansvd(Y,rankA+1,'L');\n diagS = diag(S);\n case 'svds'\n [U,S,V] = svds(Y, rankA+1, 'L');\n diagS = diag(S);\n otherwise \n [U,S,V] = svd(Y,0); \n diagS = diag(S); \n end\n \n \n A = U * diag(pos(diagS-tau)) * V';\n E = sign(Y) .* pos( abs(Y) - lambda*tau );\n M = D - A - E;\n \n rankA = sum(diagS>tau);\n cardE = sum(sum(double(abs(E)>0)));\n \n Y = Y + delta * M;\n \n% if VERBOSE > 1 && mod(iter, DISPLAY_EVERY)==0 && nargin>=6,\n% disp([' Iteration ' num2str(iter) ...\n% ' |A|_F ' num2str(norm(A,'fro')) ...\n% ' rank(A) ' num2str(rankA) ...\n% ' |E|_F ' num2str(norm(E,'fro')) ...\n% ' |E|_0 ' num2str(cardE) ...\n% ' |D-A-E|_F ' num2str(norm(M,'fro')) ...\n% ' |A-A0|_F / |A0|_F ' num2str(norm(A-A0,'fro')/norm(A0,'fro')) ...\n% ' |D-A-E|_1,inf ' num2str(max(max(abs(M)))) ]);\n% elseif VERBOSE > 0 && mod(iter, DISPLAY_EVERY)==0,\n% disp([' Iteration ' num2str(iter) ...\n% ' rank(A) ' num2str(rankA) ...\n% ' ||E||_0 ' num2str(cardE) ]);\n% end\n \n if ( norm(D-A-E,'fro')/norm(D,'fro') < EPSILON_PRIMAL || iter >= MAX_ITER )\n converged = true;\n end\n \n% if ( iter >= MAX_ITER )\n% disp('Maximum number of iterations reached.') ;\n% end\n \nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/SVT/singular_value_rpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6460948676437852}} {"text": "function [p,ellipse]=phantom3d(varargin)\n\n%PHANTOM3D Three-dimensional analogue of MATLAB Shepp-Logan phantom\n% P = PHANTOM3D(DEF,N) generates a 3D head phantom that can \n% be used to test 3-D reconstruction algorithms.\n%\n% DEF is a string that specifies the type of head phantom to generate.\n% Valid values are: \n% \n% 'Shepp-Logan' A test image used widely by researchers in\n% tomography\n% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom\n% in which the contrast is improved for better \n% visual perception.\n%\n% N is a scalar that specifies the grid size of P.\n% If you omit the argument, N defaults to 64.\n% \n% P = PHANTOM3D(E,N) generates a user-defined phantom, where each row\n% of the matrix E specifies an ellipsoid in the image. E has ten columns,\n% with each column containing a different parameter for the ellipsoids:\n% \n% Column 1: A the additive intensity value of the ellipsoid\n% Column 2: a the length of the x semi-axis of the ellipsoid \n% Column 3: b the length of the y semi-axis of the ellipsoid\n% Column 4: c the length of the z semi-axis of the ellipsoid\n% Column 5: x0 the x-coordinate of the center of the ellipsoid\n% Column 6: y0 the y-coordinate of the center of the ellipsoid\n% Column 7: z0 the z-coordinate of the center of the ellipsoid\n% Column 8: phi phi Euler angle (in degrees) (rotation about z-axis)\n% Column 9: theta theta Euler angle (in degrees) (rotation about x-axis)\n% Column 10: psi psi Euler angle (in degrees) (rotation about z-axis)\n%\n% For purposes of generating the phantom, the domains for the x-, y-, and \n% z-axes span [-1,1]. Columns 2 through 7 must be specified in terms\n% of this range.\n%\n% [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom.\n%\n% Class Support\n% -------------\n% All inputs must be of class double. All outputs are of class double.\n%\n% Remarks\n% -------\n% For any given voxel in the output image, the voxel's value is equal to the\n% sum of the additive intensity values of all ellipsoids that the voxel is a \n% part of. If a voxel is not part of any ellipsoid, its value is 0. \n%\n% The additive intensity value A for an ellipsoid can be positive or negative;\n% if it is negative, the ellipsoid will be darker than the surrounding pixels.\n% Note that, depending on the values of A, some voxels may have values outside\n% the range [0,1].\n% \n% Example\n% -------\n% ph = phantom3d(128);\n% figure, imshow(squeeze(ph(64,:,:)))\n%\n% Copyright 2005 Matthias Christian Schabel (matthias @ stanfordalumni . org)\n% University of Utah Department of Radiology\n% Utah Center for Advanced Imaging Research\n% 729 Arapeen Drive\n% Salt Lake City, UT 84108-1218\n% \n% This code is released under the Gnu Public License (GPL). For more information, \n% see : http://www.gnu.org/copyleft/gpl.html\n%\n% Portions of this code are based on phantom.m, copyrighted by the Mathworks\n%\n\n[ellipse,n] = parse_inputs(varargin{:});\n\np = zeros([n n n]);\n\nrng = ( (0:n-1)-(n-1)/2 ) / ((n-1)/2); \n\n[x,y,z] = meshgrid(rng,rng,rng);\n\ncoord = [flatten(x); flatten(y); flatten(z)];\n\np = flatten(p);\n\nfor k = 1:size(ellipse,1) \n A = ellipse(k,1); % Amplitude change for this ellipsoid\n asq = ellipse(k,2)^2; % a^2\n bsq = ellipse(k,3)^2; % b^2\n csq = ellipse(k,4)^2; % c^2\n x0 = ellipse(k,5); % x offset\n y0 = ellipse(k,6); % y offset\n z0 = ellipse(k,7); % z offset\n phi = ellipse(k,8)*pi/180; % first Euler angle in radians\n theta = ellipse(k,9)*pi/180; % second Euler angle in radians\n psi = ellipse(k,10)*pi/180; % third Euler angle in radians\n \n cphi = cos(phi);\n sphi = sin(phi);\n ctheta = cos(theta);\n stheta = sin(theta);\n cpsi = cos(psi);\n spsi = sin(psi);\n \n % Euler rotation matrix\n alpha = [cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta;\n -spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta;\n stheta*sphi -stheta*cphi ctheta]; \n \n % rotated ellipsoid coordinates\n coordp = alpha*coord;\n \n idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1);\n p(idx) = p(idx) + A;\nend\n\np = reshape(p,[n n n]);\n\nreturn;\n\n\nfunction out = flatten(in)\n\nout = reshape(in,[1 prod(size(in))]);\n\nreturn;\n \n \nfunction [e,n] = parse_inputs(varargin)\n% e is the m-by-10 array which defines ellipsoids\n% n is the size of the phantom brain image\n\nn = 128; % The default size\ne = [];\ndefaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'};\n\nfor i=1:nargin\n if ischar(varargin{i}) % Look for a default phantom\n def = lower(varargin{i});\n idx = strmatch(def, defaults);\n if isempty(idx)\n eid = sprintf('Images:%s:unknownPhantom',mfilename);\n msg = 'Unknown default phantom selected.';\n error(eid,'%s',msg);\n end\n switch defaults{idx}\n case 'shepp-logan'\n e = shepp_logan;\n case 'modified shepp-logan'\n e = modified_shepp_logan;\n case 'yu-ye-wang'\n e = yu_ye_wang;\n end\n elseif numel(varargin{i})==1 \n n = varargin{i}; % a scalar is the image size\n elseif ndims(varargin{i})==2 && size(varargin{i},2)==10 \n e = varargin{i}; % user specified phantom\n else\n eid = sprintf('Images:%s:invalidInputArgs',mfilename);\n msg = 'Invalid input arguments.';\n error(eid,'%s',msg);\n end\nend\n\n% ellipse is not yet defined\nif isempty(e) \n e = modified_shepp_logan;\nend\n\nreturn;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Default head phantoms: %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction e = shepp_logan\n\ne = modified_shepp_logan;\ne(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01];\n\nreturn;\n\n \nfunction e = modified_shepp_logan\n%\n% This head phantom is the same as the Shepp-Logan except \n% the intensities are changed to yield higher contrast in\n% the image. Taken from Toft, 199-200.\n% \n% A a b c x0 y0 z0 phi theta psi\n% -----------------------------------------------------------------\ne = [ 1 .6900 .920 .810 0 0 0 0 0 0\n -.8 .6624 .874 .780 0 -.0184 0 0 0 0\n -.2 .1100 .310 .220 .22 0 0 -18 0 10\n -.2 .1600 .410 .280 -.22 0 0 18 0 10\n .1 .2100 .250 .410 0 .35 -.15 0 0 0\n .1 .0460 .046 .050 0 .1 .25 0 0 0\n .1 .0460 .046 .050 0 -.1 .25 0 0 0\n .1 .0460 .023 .050 -.08 -.605 0 0 0 0\n .1 .0230 .023 .020 0 -.606 0 0 0 0\n .1 .0230 .046 .020 .06 -.605 0 0 0 0 ];\n \nreturn;\n \n\nfunction e = yu_ye_wang\n%\n% Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT\n% \n% A a b c x0 y0 z0 phi theta psi\n% -----------------------------------------------------------------\ne = [ 1 .6900 .920 .900 0 0 0 0 0 0\n -.8 .6624 .874 .880 0 0 0 0 0 0\n -.2 .4100 .160 .210 -.22 0 -.25 108 0 0\n -.2 .3100 .110 .220 .22 0 -.25 72 0 0\n .2 .2100 .250 .500 0 .35 -.25 0 0 0\n .2 .0460 .046 .046 0 .1 -.25 0 0 0\n .1 .0460 .023 .020 -.08 -.65 -.25 0 0 0\n .1 .0460 .023 .020 .06 -.65 -.25 90 0 0\n .2 .0560 .040 .100 .06 -.105 .625 90 0 0\n -.2 .0560 .056 .100 0 .100 .625 0 0 0 ];\n \nreturn;\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/28496-tomobox/tomobox/phantom3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6460948462710148}} {"text": " function cost = qpwls_cost(xs, G, W, yy, C, mask)\n%function cost = qpwls_cost(xs, G, W, yy, C, mask)\n% compute QPWLS cost for each column of x\n%\n% Copyright Apr 1999, Jeff Fessler\n\nif nargin < 3, ir_usage, end\n\nif nargin == 6\n\txs = reshape(xs, size(xs,1)*size(xs,2), size(xs,3));\n\txs = xs(find(mask(:)), :);\nend\n\ncost = zeros(ncol(xs),1);\nfor kk=1:ncol(xs)\n\tx = xs(:,kk);\n\tresid = yy - G * x;\t% predicted measurements\n\tcost(kk) = resid' * W * resid / 2 + norm(C * x).^2 / 2;\nend\n\ncost = reale(cost);\t% trick: x'*x is not real for complex values\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/wls/arch/qpwls_cost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6460765243918163}} {"text": "function out = SY_RangeEvolve(y)\n% SY_RangeEvolve How the time-series range changes across time.\n%\n% Measures of the range of the time series as a function of time,\n% i.e., range(x_{1:i}) for i = 1, 2, ..., N, where N is the length of the time\n% series.\n%\n%---INPUT:\n% y, the time series\n%\n%---OUTPUTS: based on the dynamics of how new extreme events occur with time.\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\ndoPlot = false; % whether to plot outputs\nN = length(y); % length of the time series\ncums = zeros(N,1);\n\nfor i = 1:N\n cums(i) = range(y(1:i));\nend\n% cums = cums/range(y);\n\nif doPlot\n figure('color','w');\n plot(cums);\nend\n\nfullr = range(y);\n\n% Define an anonymous function for the number of unique entries in a vector, x:\nlunique = @(x) length(unique(x));\n\nout.totnuq = lunique(cums);\n\n% How many of the unique extrema are in first of time series?\ncumtox = @(x) lunique(cums(1:floor(N*x)))/out.totnuq;\nout.nuqp1 = cumtox(0.01);\nout.nuqp10 = cumtox(0.1);\nout.nuqp20 = cumtox(0.2);\nout.nuqp50 = cumtox(0.5);\n\n% (**1**) how many unique extrema are in first of time series\n\nNs = [10, 50, 100, 1000];\nfor i = 1:length(Ns)\n if N >= Ns(i)\n out.(sprintf('nuql%u',Ns(i))) = lunique(cums(1:Ns(i)))/out.totnuq;\n else\n out.(sprintf('nuql%u',Ns(i))) = NaN;\n end\nend\n\n% (**2**) Actual proportion of full range captured at different points\n\nout.p1 = cums(ceil(N*0.01))/fullr;\nout.p10 = cums(ceil(N*0.1))/fullr;\nout.p20 = cums(ceil(N*0.2))/fullr;\nout.p50 = cums(ceil(N*0.5))/fullr;\n\n\nNs = [10, 50, 100, 1000];\nfor i = 1:length(Ns)\n if N >= Ns(i)\n out.(sprintf('l%u',Ns(i))) = cums(Ns(i))/fullr;\n else\n out.(sprintf('l%u',Ns(i))) = NaN;\n end\nend\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/SY_RangeEvolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6460473930088759}} {"text": "function [Z,A,B,rss] = arch2(X, na, mode, sil)\n\n% [Z,A,B,rss] = arch2(X, na, mode, silent )\n%\n% archetypal analysis of column orientated data set \n%\n% input arguments :\n%\n% - each column of data is one 'observation', e.g. the sample values of\n% all channels in a multichannel measurement at one point in time\n%\n% - na : number of generated archetypes\n%\n% - mode can be one of the following : 'normalized' (default),\n% 'mean', 'raw'\n% - in mode 'normalized' each column of data is centered by removing its mean\n% and then normalized by dividing through its standard deviation before\n% the covariance matrix is calculated\n% - in mode 'mean' only the mean of every column of data is removed\n% - in mode 'raw' no preprocessing is applied to data\n% - in mode 'scale' is divided by max(abs(X))\n%\n% - silent is an optional flag which supresses output of text and plot on the matlab\n% screen. Returned values (see below) are in no way affected\n%\n%\n% output arguments :\n%\n% - Z : each column of Z is an archetype\n%\n% - A : the columns of A are the coefficients of the archetypes to\n% the constrains ||X-Z*A|| -> min\n%\n% - B : the columns of B create the X-mixtures (the archtypes)\n% Z=X*B\n%\n% - rss : the residual sum of squares for each iteration\n%\n% Christian Merkwirth & Joerg Wichard\n% Februar 1998\n\n\nglobal silent\n\nnarginchk(2,3);\n\nif nargin < 3\n mode = 'normalized';\nend\n\nif nargin < 4\n silent = 0;\nelse\n silent = 1;\nend\n\n[m,n] = size(X);\n\nprintline('archetypal analysis')\nprintline(['on data set of size ' num2str(n) 'x' num2str(m)]);\n\nif (na < 1)\n printline('number of archetypes must be greater than zero');\nend\n\nif strncmp(mode, 'r',1)\n mode = 'raw';\n printline('no data preprocessing');\nelseif strncmp(mode, 'm',1)\n mode = 'mean';\n printline('removing mean from data set');\n mn = mean(X,2);\n X = X - repmat(mn, 1, n);\nelseif strncmp(mode, 's',1)\n mode = 'scale';\n printline('scaling data set');\n xm = max(max(abs(X)));\n X = (1/xm)*X;\nelse\n mode = 'normalized';\n printline('removing mean and normalizing data');\n mn = mean(X,2);\n X = X - repmat(mn, 1, n);\n dv = std(X,0,2);\n X = X ./ repmat(dv, 1, n);\nend\n\ngew1=20*m; % Gewichtung der Convexit�tsbedingung\ngew2=5*m; % Gewichtung der Convexit�tsbedingung\ntol=0.01; %%Toleranz f�r die Abbruchbedingung\nnumb = 20; %% Max. Anzahl der Iterationen\n\n%% x zuf�llig ausw�len\nB=eye(n);\nrp=randperm(na);\nB=B(:,rp);\nZ=X*B;\n\n%% Hier beginnt die Alternierende Optimierung\nrss(1,:)=[ 0 sum(sum(X .* X))]\ncount=0;\n\nfor c=1:numb;\n\n for l=1:na;\n\n %% Maximum an Z anf�gen\n MX=max(max(Z));\n Z(m+1,:)=gew1*MX;\n X(m+1,:)=gew1*MX;\n\n %% A suchen bei konstantem Z\n for i=1:n;\n A(:,i)= lsqnonneg(Z,X(:,i));\n end;\n\n %% Gewichtung entfernen\n X=X(1:m,:);\n Z=Z(1:m,:);\n\n %% Z suchen bei konstantem A\n for i=1:n;\n V(:,i)=A(l,i)*(X(:,i) - Z*A(:,i) + A(l,i)*Z(:,l));\n end;\n\n %% Singul�re Archetypen durch max ||X-Z*A|| ersetzen\n if ( (sum(A(l,:)) .* sum(A(l,:))) ==0)\n VT=sum((X-Z*A).*(X-Z*A));\n [VTC,VTI]=max(VT);\n B(:,l)=0;\n B(VTI,l)=1;\n\n else\n VS=(sum(A(l,:).*A(l,:)))*sum(V,2);\n MV=max(max(X));\n X(m+1,:)=gew2*MV;\n VS(m+1)=gew2*MV;\n\n B(:,l)=nnls(X,VS, 4 * max(size(X)) * norm(X,1) * eps);\n\n %% Gewichtung entfernen\n X=X(1:m,:);\n VS=VS(1:m);\n end;\n end;\n\n Z=X*B;\n\n %% norm RSS berechnen\n rss((c+1),:)=[ c sum(sum((X-Z*A).*(X-Z*A))) ];\n\n if (abs(rss(c+1,2)-rss(c,2)) < tol*rss(c,2) )\n break;\n end;\n\n count=count+1;\nend;\n\n\n%% Ergebnis auf Konsistenz �berpr�fen\n[C,I]=max(rss);\nif( (I < count) & (rss(I) < rss(count)) )\n printline('Minimum not reached')\nend\n\nif( count == numb )\n printline('Maximum Number of Iterations')\nend\n\nif silent\n figure(1)\n subplot(4,1,1)\n plot(rss(:,1), rss(:,2))\n title('Residual Sum of Squares')\n\n subplot(4,1,2)\n plot(X)\n title('Input Data');\n\n subplot(4,1,3)\n plot((Z),'k')\n title('Archetypes');\n\n subplot(4,1,4)\n plot((Z),'k')\n hold on;\n plot(X)\n hold off;\n title('Archetypes & Input Data');\nend\n\n\nfunction printline(string)\nglobal silent\nif silent~=1\n disp(string)\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/utils/arch2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.646047384292188}} {"text": "%% Copyright (C) 2014, 2016, 2019 Colin B. Macdonald\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @defmethod @@sym trace (@var{A})\n%% Trace of symbolic matrix.\n%%\n%% Example:\n%% @example\n%% @group\n%% syms x\n%% A = [1 2 x; 3 sym(pi) 4; 13 5 2*x]\n%% @result{} A = (sym 3×3 matrix)\n%% ⎡1 2 x ⎤\n%% ⎢ ⎥\n%% ⎢3 π 4 ⎥\n%% ⎢ ⎥\n%% ⎣13 5 2⋅x⎦\n%% trace(A)\n%% @result{} ans = (sym) 2⋅x + 1 + π\n%% @end group\n%% @end example\n%%\n%% As an example, we can check that the trace of the product is @emph{not}\n%% the product of the traces:\n%% @example\n%% @group\n%% A = sym([1 2; 3 4]);\n%% B = sym([pi 3; 1 8]);\n%% trace(A*B)\n%% @result{} ans = (sym) π + 43\n%% trace(A) * trace(B)\n%% @result{} ans = (sym) 5⋅π + 40\n%% @end group\n%% @end example\n%% However, such a property does hold if we use the Kronecker tensor product\n%% (@pxref{@@sym/trace}):\n%% @example\n%% @group\n%% kron(A, B)\n%% @result{} ans = (sym 4×4 matrix)\n%% ⎡ π 3 2⋅π 6 ⎤\n%% ⎢ ⎥\n%% ⎢ 1 8 2 16⎥\n%% ⎢ ⎥\n%% ⎢3⋅π 9 4⋅π 12⎥\n%% ⎢ ⎥\n%% ⎣ 3 24 4 32⎦\n%% trace(kron(A, B))\n%% @result{} ans = (sym) 5⋅π + 40\n%% trace(A) * trace(B)\n%% @result{} ans = (sym) 5⋅π + 40\n%% @end group\n%% @end example\n%%\n%% @seealso{@@sym/det}\n%% @end defmethod\n\n\nfunction z = trace(x)\n\n cmd = { 'x, = _ins'\n 'if not x.is_Matrix:'\n ' x = sp.Matrix([[x]])'\n 'return sp.trace(x),' };\n\n z = pycall_sympy__ (cmd, x);\n\nend\n\n\n%!test\n%! % scalar\n%! syms x\n%! assert (isequal (trace(x), x))\n\n%!test\n%! syms x\n%! A = [x 3; 2*x 5];\n%! assert (isequal (trace(A), x + 5))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/trace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6460195295308491}} {"text": "%% Configurable Simulink Model for DC-DC Converters\n%\n\n%% DC-DC Converters\n% There are three kinds of switching mode DC-DC converters, buck, boost and\n% buck-boost. The buck mode is used to reduce output voltage, whilst the\n% boost mode can increase the output voltage. In the buck-boost mode, the\n% output voltage can be maintained either higher or lower than the source\n% but in the opposite polarity. The simplest forms of these converters are\n% schematically represented in Figure 1.\n\n%%\n% \n% \n% \n% \n% Figure 1. Buck (left), Boost (middle) and Buck-Boost (right) converters.\n\n%%\n% These converters consist of the same components, an inductor, $L$, a\n% capacitor, $C$ and a switch, which has two states $u=1$ and $u=0$. All \n% converters connect to a DC power source with a voltage (unregulated),\n% $V_\\mathrm{in}$ and provide a regulated voltage, $v_\\mathrm{o}$ to the\n% load resistor, $R$ by controlling the state of the switch. In some\n% situations, the load also could be inductive, for example a DC motor, or\n% approximately, a current load, for example in a cascade configuration.\n% For simplicity, here, only current and resistive loads are to be\n% considered.\n%\n\n%% Principles \n% The working principles of the these DC-DC converters can be explained as\n% follows. In the buck mode, when the switch is on position 1, the DC\n% source supplies power to the circuit which results an output voltage\n% across the resistor. When the switch changes its position to 0, the\n% energy stored in the inductor and capacitor will discharge through the\n% resistor. Appropriately controlling the switching position can maintain\n% the output voltage at a desired level lower than the source. \n%\n% In the boost mode, when the switch is on position 1, the circuit is\n% separated into two parts: on the left, the source is charging the\n% inductor, meanwhile the capacitor on the right maintains the output\n% voltage using previously stored energy. When the switch changes its\n% position to 0, both the DC source and energy stored in the inductor will\n% supply power to the circuit on the right, hence boost the output voltage.\n% Again, the output voltage can be maintain at desired level by controlling\n% the switching sequence.\n%\n% Finally, for the buck-boost mode, switch positions 1 and 0 represents\n% charging and discharging modes of the inductor. Appropriately controlling\n% the switching sequence can result in output voltage higher or lower than\n% the DC source. Since the inductor cannot change the direction of current,\n% the output voltage is opposite to the DC source.\n\n%% Model under ideal assumptions\n% Under ideal assumptions: ideal switch, ideal capacitor and ideal\n% inductor, these converters can be described using ordinary\n% differentiation equations as follows:\n%\n%% Buck converter:\n% $C{dv_{c} \\over dt} = i_{L} - v_{c}/R - i_{o}$\n%\n% $L{di_{L} \\over dt} = uv_{in} - v_{c}$\n%\n% where, $i_\\mathrm{o}$ is the load current.\n%\n%% Boost converter:\n% $C{dv_\\mathrm{c}\\over dt}=(1-u)i_\\mathrm{L}-v_\\mathrm{c}/R-i_\\mathrm{o}$\n%\n% $L{di_\\mathrm{L}\\over dt}=v_\\mathrm{in} - (1-u) v_\\mathrm{c}$\n%\n%% Buck-boost converter:\n% $C{dv_\\mathrm{c}\\over dt}=(1-u)i_\\mathrm{L}-v_\\mathrm{c}/R-i_\\mathrm{o}$\n%\n% $L{di_\\mathrm{L}\\over dt}=uv_\\mathrm{in} - (1-u) v_\\mathrm{c}$\n%\n% Introduce the following state, time and load normalization:\n% \n% $x_1={v_\\mathrm{c}\\over v_\\mathrm{in}}$, \n%\n% $x_2={i_\\mathrm{L}\\over v_\\mathrm{in}}\\sqrt{{L}\\over{C}}$, \n%\n% $\\tau = {t \\over \\sqrt{LC}}$, \n%\n% $\\gamma = {\\sqrt{LC}\\over R}$, \n%\n% $d = {i_\\mathrm o \\over v_\\mathrm{in}}\\sqrt{{L}\\over {C}}$\n% \n% Then the normalized state equations of three converters are as follows:\n%\n%% Normalized buck model\n% $\\dot{x_1} = -\\gamma x_1 + x_2 - d$\n%\n% $\\dot{x_2}= -x_1 + u $\n%\n% where, with an abuse of notation, `.' represents the derivation with\n% respect to the normalized time, $\\tau$. \n%\n%% Normalized boost model\n% $\\dot{x_1} = -\\gamma x_1 + (1-u)x_2 - d$\n%\n% $\\dot{x_2} = -(1-u)x_1 + 1$\n%\n%% Normalized buck-boost model\n% $\\dot{x_1} = -\\gamma x_1 + (1-u)x_2 -d$\n%\n% $\\dot{x_2} = -(1-u)x_1 + u$\n%\n\n%% Model with body resistors\n% In more general cases, a body resistor of the inductor, $R_\\mathrm{L}$\n% and an equivalent series resistor (ESR) of the capacitor, $R_\\mathrm{c}$\n% can be added to the above models. \n%\n%% Buck model with $R_\\mathrm{L}$ and $R_\\mathrm{c}$\n% Since,\n%\n% $C{dv_\\mathrm{c}\\over dt} = i_\\mathrm{L} - v_\\mathrm{o}/R - i_\\mathrm{o}$\n%\n% $v_\\mathrm{o} = v_\\mathrm{c} + R_\\mathrm{c}C{dv_\\mathrm{c}\\over dt}$\n%\n% $L{di_\\mathrm{L}\\over dt} = uv_\\mathrm{in} - v_\\mathrm{o} -\n% R_\\mathrm{L}i_\\mathrm{L}$\n%\n% Inserting the second equation into the first leads to:\n%\n% $C{dv_\\mathrm{c}\\over dt} = i_\\mathrm{L} - v_\\mathrm{c}/R -\n% {R_\\mathrm{c}\\over R}C{dv_\\mathrm{c}\\over dt}- i_\\mathrm{o}$\n%\n% $\\left(1+{R_\\mathrm{c}\\over R}\\right)C{dv_\\mathrm{c}\\over\n% dt}=i_\\mathrm{L} - v_\\mathrm{c}/R - i_\\mathrm{o}$\n%\n% Hence,\n%\n% $v_\\mathrm{o}={Rv_\\mathrm{c}\\over R+R_\\mathrm{c}}+{RR_\\mathrm{c}\\over\n% R+R_\\mathrm{c}}(i_\\mathrm{L}-i_\\mathrm{o})$\n%\n% and the overall model is\n%\n% $C{dv_\\mathrm{c}\\over dt}={R\\over R+R_\\mathrm{c}}\\left(i_\\mathrm{L} - {v_\\mathrm{c}\\over R} - i_\\mathrm{o}\\right)$\n%\n% $L{di_\\mathrm{L}\\over dt} = uv_\\mathrm{in} - {Rv_\\mathrm{c}\\over\n% R+R_\\mathrm{c}} - \\left(R_\\mathrm{L}+{RR_\\mathrm{c}\\over R+R_\\mathrm{c}}\\right) i_\\mathrm{L} + {RR_\\mathrm{c}i_\\mathrm{o}\\over R+R_\\mathrm{c}}$\n% \n% $v_\\mathrm{o}={Rv_\\mathrm{c}\\over R+R_\\mathrm{c}}+{RR_\\mathrm{c}\\over\n% R+R_\\mathrm{c}}(i_\\mathrm{L}-i_\\mathrm{o})$\n%\n%% Boost model with $R_\\mathrm{L}$ and $R_\\mathrm{c}$\n% $C{dv_\\mathrm{c}\\over dt} = (1-u)i_\\mathrm{L} - v_\\mathrm{o}/R - i_\\mathrm{o}$\n%\n% $L{di_\\mathrm{L}\\over dt} = v_\\mathrm{in} - (1-u) v_\\mathrm{o} - R_\\mathrm{L}i_\\mathrm{L}$\n%\n% $v_\\mathrm{o} = {Rv_\\mathrm{c}\\over R+R_\\mathrm{c}}+{RR_\\mathrm{c}\\over\n% R+R_\\mathrm{c}}((1-u)i_\\mathrm{L}-i_\\mathrm{o})$\n%\n%% Buck-boost model with $R_\\mathrm{L}$ and $R_\\mathrm{c}$\n% $C{dv_\\mathrm{c}\\over dt} = (1-u)i_\\mathrm{L} - v_\\mathrm{o}/R-i_\\mathrm{o}$\n%\n% $L{di_\\mathrm{L}\\over dt}=uv_\\mathrm{in}-(1-u) v_\\mathrm{o}-R_\\mathrm{L}i_\\mathrm{L}$\n%\n% $v_\\mathrm{o}={Rv_\\mathrm{c}\\over R+R_\\mathrm{c}}+{RR_\\mathrm{c}\\over R+R_\\mathrm{c}}((1-u)i_\\mathrm{L}-i_\\mathrm{o})$\n%\n%% Simulink Model\n% These three modes of DC-DC converters have been uniformly implemented in\n% the MATLAB/Simulink as show in Figure~\\ref{fig:simulinkmodel}. \n% \n% <>\n%\n% Figure 2. A uniform Simulink model of DC-DC converters.\n%\n% The input-output connections of the model is shown in Figure 3.\n% \n% <>\n%\n% Figure 3. Input and output connections of the DC-DC converter model.\n%\n% The first input to the model is the switch signal eight 1 or 0. The\n% second one defines the DC source voltage and internal resistance. The\n% third input is used to define the output current. The model has two\n% outputs, the output voltage and the inductor current, which are the\n% states of the system.\n%\n% The model can be configure with a number of parameters as shown in\n% Figure~\\ref{fig:simulinkmodelparameters}. These parameters are: the\n% capacitance, $C$, inductance, $L$, the internal resistance of the\n% capacitor and the inductor, $R_C$ and $R_L$ respectively. Three converter\n% modes can be selected through the pull-down menu. One can also define\n% either zero or non-zero value to the initial capacitor voltage by\n% selecting or de-selecting the ``zero capacitor voltage'' option. Finally,\n% the option ``Positive Inductor Current'' defines whether the condition\n% $i_L\\ge 0$ should be enforced or not.\n%\n% <>\n%\n% Figure 4. Parameters of the DC-DC converter model.\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/18833-configurable-simulink-model-for-dc-dc-converters-with-pwm-pi-control/ConfigurableDCConverter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311906630568, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.6460195271816994}} {"text": "function [y, dsdx, dsdp] = VBA_sigmoid(x, varargin)\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [y, dsdx, dsdp] = VBA_sigmoid(x, [name, value, ...])\n% Apply a sigmoid transformation to x\n%\n% By default, the canonical sigmoid is used:\n%\n% y = 1 / (1 + exp(- x))\n%\n% However, this function can be parametrized using name/value pairs of\n% arguments to get, using all options:\n%\n% y = offset + scale * 1 / (1 + exp(- slope * (x - center))\n%\n% IN:\n% - x: values to be transformed\n% - optional key/value pairs or structure (or both) that parametrize the \n% sigmoid transformation:\n% * 'slope' : inverse-temperature parameter (default = 1)\n% * 'center' : absissa of the inflexion point (default = 0)\n% * 'scale' : multiplicative gain of the transformation (default = 1)\n% * 'offset' : additive gain (default = 0)\n% * 'lapseRate' : shotcut for offset = lapseRate and scale = 1 - 2 * lapseRate\n% this option is incompatible with offset or scale\n% - other optional key/value pairs or structure (or both)\n% * 'inverse' : reversed transformation, ie. x = VBA_sigmoid(y, opt) \n% (default = false)\n% * 'finite' : boundaries that enforce precision to be finite and \n% derivative to stay numerically non zero (default = 1e-9)\n% Set to 0 to deactivate\n% * 'derivatives' : cell array of parameter names wrt which dsdp must be\n% computed (in given order). \n% \n% \n% Note that if the 'inverse' flag is set to true, the derivatives will\n% not be computed and dsdx = dsdp = [] will be returned instead.\n%\n% OUT:\n% - y: transformed values, with the same dimension as x.\n% - dsdx: derivative of the transformation wrt. x, taken at each point x.\n% Has the same dimension as x.\n% - dsdp: derivative of the transformation wrt. the parameters specified\n% as arguments. Derivatives are for parameters taken in alphabetical\n% order and aggregated along the first dimension. For example, calling\n% VBA_sigmoid([x1; x2], 'slope', 2, 'center', 3) will return dsdp as:\n% [ d_s/d_center(x1) d_s/d_center(x2) ;\n% d_s/d_slope(x1) d_s/d_slope(x2) ]\n% If x is multidimensional, size(dsdp) = [nb_params, size(x,1), size(x,2), ...]\n%\n% /////////////////////////////////////////////////////////////////////////\n\n\n%% Globals\n% =========================================================================\n% truncature for finite sigmoid\nepsilon = 1e-9;\n\n%% Shrtcut\n% =========================================================================\n% quick version!\nif nargin == 1 && nargout == 1\n y = epsilon + (1 - 2 * epsilon) ./ (1 + exp (- x));\n return\nend\n\n%% Parse arguments\n% =========================================================================\n\n% define inputParser\n% -------------------------------------------------------------------------\npersistent parser;\n\nif isempty (parser)\n parser = getParser ();\nend\n\n% parse arguments\n% -------------------------------------------------------------------------\n\nparser.parse (varargin{:});\nparams = parser.Results ;\n\n% apply shortcuts if needed\n% -------------------------------------------------------------------------\n\nif ~ ismember ('lapseRate', parser.UsingDefaults)\n % lapseRate is mutually ex\n if any (~ ismember ({'offset', 'scale'}, parser.UsingDefaults))\n error('*** VBA_sigmoid: you can not specify lapseRate and offset or scale at the same time');\n end\n params.offset = params.lapseRate;\n params.scale = 1 - 2 * params.lapseRate;\nend\n\n%% Compute transformation\n% =========================================================================\n\n%% Inversed case\nif params.inverse\n % check that values are valid\n if ~ VBA_isInRange(x, [0 1])\n error('*** VBA_sigmoid: inverse sigmoid inputs must be between 0 and 1');\n end\n \n % inverse sigmoid transformation\n lx = params.scale * (x - params.offset) .^-1 - 1;\n y = params.center - params.slope ^-1 * log (lx) ;\n \n % skip derivatives, they are generally not used in inverse case\n dsdx = [];\n dsdp = [];\n \n%% Normal case\nelse\n % evaluate sigmoid\n % ---------------------------------------------------------------------\n sx = 1 ./ (1 + exp(- params.slope * (x - params.center)));\n y = params.offset + params.scale * sx;\n \n % ensure finite precision ('finite' flag)\n % ---------------------------------------------------------------------\n if params.finite > 0\n minY = params.offset + epsilon;\n y = max(y,minY);\n maxY = params.offset + params.scale - epsilon;\n y = min(y,maxY);\n end\n \n % compute derivatives with respect to value\n % ---------------------------------------------------------------------\n\n % skip if not not required\n if nargout < 2\n return\n end\n \n % actual computation\n dsdx = params.slope * (y - params.offset) .* (1 - (y - params.offset) ./ params.scale);\n \n % compute derivatives with respect to parameters\n % ---------------------------------------------------------------------\n\n % skip if not not required\n if nargout < 3\n return\n end\n\n % concatenate derivatives for all parameters\n dims = size(x);\n \n dsdp = cat (2, ...\n - VBA_vec (dsdx), ... % d_center\n 1 - 2 * VBA_vec (sx), ... d_lapseRate\n ones(numel(sx),1), ... d_offset\n VBA_vec (sx), ... d_scale\n ((VBA_vec (x) - VBA_vec(params.center)) / params.slope) .* VBA_vec (dsdx) ... d_slope\n );\n\n % keep only those passed s parameter\n derivables = {'center','lapseRate','offset','scale','slope'};\n if isempty(params.derivatives)\n params.derivatives = setdiff(derivables, parser.UsingDefaults);\n end\n dIdx = cellfun(@(l) find(strcmp (derivables, l)), params.derivatives);\n \n dsdp = dsdp(:,dIdx);\n \n % set derived parameter as first dimension\n if all(dims == 1)\n dsdp = dsdp';\n else\n dims(dims==1) = [];\n dsdp = reshape(dsdp', [size(dsdp,2) dims]);\n end\n\n\nend\n\nend\n\nfunction parser = getParser()\n\nparser = inputParser;\nparser.PartialMatching = false;\nparser.KeepUnmatched = true;\n\n% define parameters\n% -------------------------------------------------------------------------\n\n% flags\nparser.addParameter ('inverse', false, @islogical);\nparser.addParameter ('finite', true, @(z) VBA_isInRange(z, [0 1e-2]));\nparser.addParameter ('derivatives', {}, @iscellstr);\n\n% x transfomations\nparser.addParameter ('slope', 1, @isnumeric);\nparser.addParameter ('center', 0, @isnumeric);\n\n% sig transformation\nparser.addParameter ('offset', 0, @isnumeric);\nparser.addParameter ('scale', 1, @(z) VBA_isInRange(z, [eps Inf]));\n\n% shortcut for lapse rate model\nparser.addParameter ('lapseRate', 0, @(z) VBA_isInRange(z, [0 0.5]));\nend\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/utils/VBA_sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6458633126122288}} {"text": "function [ a, det ] = spodi ( a, lda, n, job )\n\n%*****************************************************************************80\n%\n%% SPODI computes the determinant and inverse of a certain matrix.\n%\n% Discussion:\n%\n% The matrix is real symmetric positive definite.\n% SPODI uses the factors computed by SPOCO, SPOFA or SQRDC.\n%\n% A division by zero will occur if the input factor contains\n% a zero on the diagonal and the inverse is requested.\n% It will not occur if the subroutines are called correctly\n% and if SPOCO or SPOFA has set INFO == 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the output A from SPOCO or SPOFA, or the output \n% X from SQRDC. \n%\n% Input, integer LDA, the leading dimension of the array A.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, integer JOB, specifies the task.\n% 11, both determinant and inverse.\n% 01, inverse only.\n% 10, determinant only.\n%\n% Output, real A(LDA,N), if SPOCO or SPOFA was used to factor A then \n% SPODI produces the upper half of inverse(A). If SQRDC was used to \n% decompose X then SPODI produces the upper half of inverse(X'*X) \n% where X' is the transpose. Elements of A below the diagonal are \n% unchanged. If the units digit of JOB is zero, A is unchanged.\n%\n% Output, real DET(2), the determinant of A or of X'*X\n% if requested.\n% determinant = DET(1) * 10.0**DET(2)\n% with 1.0 <= DET(1) < 10.0 or DET(1) == 0.0.\n%\n\n%\n% Compute the determinant.\n%\n if ( job / 10 ~= 0 )\n\n det(1) = 1.0;\n det(2) = 0.0;\n s = 10.0;\n\n for i = 1 : n\n\n det(1) = a(i,i) * a(i,i) * det(1);\n\n if ( det(1) == 0.0 )\n break\n end\n\n while ( det(1) < 1.0 )\n det(1) = s * det(1);\n det(2) = det(2) - 1.0;\n end\n\n while ( s <= det(1) )\n det(1) = det(1) / s;\n det(2) = det(2) + 1.0;\n end\n\n end\n\n end\n%\n% Compute inverse(R).\n%\n if ( mod ( job, 10 ) ~= 0 )\n\n for k = 1 : n\n\n a(k,k) = 1.0 / a(k,k);\n t = -a(k,k);\n a(1:k-1,k) = sscal ( k-1, t, a(1:k-1,k), 1 );\n\n for j = k+1 : n\n t = a(k,j);\n a(k,j) = 0.0;\n a(1:k,j) = saxpy ( k, t, a(1:k,k), 1, a(1:k,j), 1 );\n end\n\n end\n%\n% Form inverse(R) * (inverse(R))'.\n%\n for j = 1 : n\n for k = 1 : j-1\n t = a(k,j);\n a(1:k,k) = saxpy ( k, t, a(1:k,j), 1, a(1:k,k), 1 );\n end\n t = a(j,j);\n a(1:j,j) = sscal ( j, t, a(1:j,j), 1 );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_s/spodi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6458633084777737}} {"text": "function [Bdraw,statOK]=sampleB(yData,Psi,SV_H,A,p,priorValues)\n% This function uses the method proposed by Carriero Clark and Marcellino\n% to draw from the conditional posterior distribution of B.\n%sampleB(yData,PsiDraw_prop,HvarsDraw_prop,Adraw_prop,p,priorValues)\n%Psi = PsiDraw_prop; %local mean\n%SV_H = HvarsDraw_prop; %draw for the time varrying diagonal elements of the VCV\n%A = Adraw_prop; %the time invariant component of the VCV\n\n%% Initialize\n[T,M] = size(yData);\nTp=T-p; \n\n% expand prior data\nvarsH=priorValues.vars;\nlambda=priorValues.lambda; %overall tightness\ntheta=priorValues.theta; %extra shrinkage for off diagonal elements\n\n%% set up prior variance and mean of B\n% Prior mean of B\npriorMeanBeta=zeros(M*p,1); %means are equal to zero\n\n% Prior variance of B\npriorVarVectors=zeros(M*p,p);\n\n% lag shrinkage\npVector=zeros(p,1);\nfor j=1:p\n pVector(j)=1/(j^2);\nend\n\nvarsH=reshape(varsH,M,1);\n\nfor i=1:M\n % scale by variance estimates\n vector_iTemp=(varsH(i)*ones(M,1))./varsH;\n vector_iTemp=vector_iTemp*lambda*theta;\n vector_iTemp(i)=vector_iTemp(i)/theta;\n \n % calculate the prior variances\n vector_i=kron(pVector,vector_iTemp); \n priorVarVectors(:,i)=vector_i;\nend\n\n\n%% Now sample B row-by-row\nAinv=A\\eye(M);\n\nY_Psi=yData-Psi;\nY_Psi(1:p,:)=yData(1:p,:)-ones(p,1)*mean(yData(1:p,:));\nX_Psi = lagmatrix(Y_Psi,1:p);\nX_Psi = X_Psi(p+1:end,:);\nY_Psi=Y_Psi(p+1:end,:);\n\n\nOK=0; % to control for unstable draws\n\nrejections=0;\nstatOK=1;\n% start drawing B\nwhile OK==0 \n \n % initialize\n scaledEpsilon=zeros(Tp,M);\n Bdraw=zeros(p*M,M);\n \n % prepare data for column 1\n y1=Y_Psi(:,1);\n y1Scaled=y1./(SV_H(p+1:T,1).^0.5);\n hScaling1=(SV_H(p+1:T,1).^0.5)*ones(1,p*M);\n X1Scaled=X_Psi./hScaling1;\n\n % calculate posterior distribution\n postVarBinv=diag(priorVarVectors(:,1).^(-1))+X1Scaled'*X1Scaled;\n postVarB=postVarBinv\\eye(M*p);\n postMeanB=postVarB*(diag(priorVarVectors(:,1).^(-1))*priorMeanBeta+X1Scaled'*y1Scaled);\n \n % obtain cholvar\n [cholPostVarBi,testPD]=chol(postVarB);\n if testPD>0\n cholPostVarBi= cholred(postVarB);\n disp('NPD!')\n end\n cholPostVarBi=cholPostVarBi'; % transpose to obtain lower triangular matrix\n \n % sample the column of Bdraw\n Bi_draw=postMeanB+cholPostVarBi*randn(p*M,1);\n Bdraw(:,1)=Bi_draw;\n \n % prepare residuals\n resids_1=y1Scaled-X1Scaled*Bi_draw;\n scaledEpsilon(:,1)=resids_1;\n \n for i=2:M \n \n % prepare data for column i\n a_vector=Ainv(i,:)';\n yi=Y_Psi(:,i)-scaledEpsilon*a_vector;\n yiScaled=yi./(SV_H(p+1:T,i).^0.5);\n \n hScaling_i=(SV_H(p+1:T,i).^0.5)*ones(1,p*M);\n XiScaled=X_Psi./hScaling_i;\n \n % calculate posterior distribution\n postVarBinv=diag(priorVarVectors(:,i).^(-1))+XiScaled'*XiScaled;\n postVarB=postVarBinv\\eye(M*p);\n postMeanB=postVarB*(diag(priorVarVectors(:,i).^(-1))*priorMeanBeta+XiScaled'*yiScaled);\n \n % obtain cholvar\n [cholPostVarBi,testPD]=chol(postVarB);\n if testPD>0\n cholPostVarBi= cholred(postVarB);\n disp('NPD!')\n end\n cholPostVarBi=cholPostVarBi'; % transpose to obtain lower triangular matrix\n\n % sample the column of Bdraw\n Bi_draw=postMeanB+cholPostVarBi*randn(p*M,1);\n Bdraw(:,i)=Bi_draw;\n \n % prepare residuals\n resids_i=yiScaled-XiScaled*Bi_draw;\n scaledEpsilon(:,i)=resids_i; \n end\n \n % check stability \n [ max_vTemp ] = determineEV(Bdraw,M,p);\n max_v=abs(max_vTemp);\n\n if max_v <0.999\n OK=1; % accept the draw\n else\n rejections=rejections+1;\n %disp([max_v rejections])\n if rejections>1000\n% disp('Redo This round')\n statOK=0;\n OK=1;\n end\n\n end\n \n \nend\n\nend", "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/unreachableCode_ToRemove/sampleB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.645863161488889}} {"text": "%% Axes and Antipodal Symmetry\n%\n%% Directions vs. Axes\n%\n% In MTEX it is possible to consider three dimensional vectors either as\n% directions or as axes. The key option to distinguish between both\n% interpretations is *antipodal*.\n%\n% Consider a pair of vectors\n\nv1 = vector3d(1,1,2);\nv2 = vector3d(1,1,-2);\n\n%%\n% and plots them in a spherical projection\n\nplot([v1,v2],'label',{'v_1','v_2'})\n\n%%\n% These vectors will appear either on the upper or on the lower hemisphere.\n% In order to treat these vectors as axes, i.e. in order to assume\n% antipodal symmetry - one has to use the keyword *antipodal*.\n\nplot([v1,v2],'label',{'v_1','v_2'},'antipodal')\n\n%%\n% Now the direction *v_2* is identified with the direction *-v_2* which\n% plots at the upper hemisphere.\n\n%% The Angle between Directions and Axes\n%\n% As a consequence the angle between two axes *v1*, *v2* will always be the\n% smallest angle between the directions *v1*, *v2* and *v1*, *-v2*, i.e. it\n% will always be smaller than 90 degree. In the absence of antipodal\n% symmetry we obtain\n\nangle(v1,v2) / degree\n\n%%\n% whereas, if antipodal symmetry is assumed we obtain\n\nangle(v1,v2,'antipodal') / degree\n\n%% Antipodal Symmetry in Density Estimation\n% \n% Another example, where antipodal symmetry matters is\n% . For ordinary\n% directions we obtain an arbitrary spherical function\n\nv = vector3d.rand(100)\ndensity = v.calcDensity;\nplot(density)\n\n%%\n% Whereas, if antipodal symmetry is present the resulting density function\n% will have antipodal symmetry as well\n\ndensity = v.calcDensity('antipodal')\nplot(density,'complete')\n\n\n%% Antipodal Symmetry in Experimental Pole Figures\n%\n% Due to Friedel's law experimental pole figures always provide antipodal\n% symmetry. One consequence of this fact is that MTEX plots pole figure\n% data always on the upper hemisphere. Moreover if you annotate a certain\n% direction to pole figure data, it is always interpreted as an axis, i.e.\n% projected to the upper hemisphere if necessary\n\nmtexdata dubna\nCS = pf.CS;\n\n% plot the first pole figure\nplot(pf({1}))\n\n% annotate a axis on the souther hemisphere\nannotate(vector3d(1,0,-1),'labeled','backgroundColor','w')\n\n%% Antipodal Symmetry in Recalculated Pole Figures\n%\n% However, in the case of pole figures calculated from an ODF antipodal\n% symmetry is in general not present.\n\n% some prefered orientation\no = orientation.byEuler(20*degree,30*degree,0,'ZYZ',CS);\n\n% define an unimodal ODF\nodf = unimodalODF(o);\n\n% plot pole figures\nplotPDF(odf,[Miller(1,2,2,CS),-Miller(1,2,2,CS)])\n\n%%\n% Hence, if one wants to compare calculated pole figures with experimental\n% ones, one has to add antipodal symmetry.\n\nplotPDF(odf,Miller(1,2,2,CS),'antipodal')\n\n%% Antipodal Symmetry in Inverse Pole Figures\n%\n% The same reasoning as above holds true for inverse pole figures. If we\n% look at complete, inverse pole figures they do not posses antipodal symmetry\n% in general\n\nplotIPDF(odf,[yvector,-yvector],'complete')\n\n%%\n% However, if we add the keyword antipodal, antipodal symmetry is enforced.\n\nplotIPDF(odf,yvector,'antipodal','complete')\n\n%%\n% Notice how MTEX, automatically reduces the fundamental region of inverse\n% pole figures in the case that antipodal symmetry is present.\n\nplotIPDF(odf,yvector)\n\n%%\nplotIPDF(odf,yvector,'antipodal')\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/Vectors/VectorsAxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.76908023177796, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.6458227944891918}} {"text": "function [C] = TWSC_ADMM( Y, D, S, W1, W2, Par )\n% This routine solves the following trilateral weighted sparse coding problem\n%\n% min_{C,Z} |W1(Y-DSC)W2|_F,2 + |Z|_1 s.t. C=Z\n%\n% inputs:\n% Y -- d*M data matrix, d is the data dimension, and M is the number\n% of image patches.\n% W1 -- d*d matrix of row weights\n% W2 -- M*M matrix of column weights\n% outputs:\n% C -- d*M data matrix, sparse coding coefficient matrix\n% Z -- d*M data matrix, auxiliary variable, equal to C\n\ntol = 1e-8;\nPar.maxrho = 100;\nPar.maxIter = 10;\nPar.rho = 0.5;\nPar.mu = 1.1;\nPar.display = 0;\n% Initializing optimization variables\nC = zeros(size(S, 1), size(Y, 2));\nZ = zeros(size(C));\nU = zeros(size(C));\n% Start main loop\niter = 0;\nstopCZ = zeros(Par.maxIter, 1);\nstopC = zeros(Par.maxIter, 1);\nstopZ = zeros(Par.maxIter, 1);\nwhile iter < Par.maxIter\n iter = iter + 1;\n Cpre = C;\n Zpre = Z;\n %% update C, fix Z and U\n % min_{C} ||W1 * (Y - DSC) * W2||_F^2 + 0.5 * rho * ||C - Z + 1/rho * U||_F^2\n % The solution is equal to solve A * X + X * B = E\n A = S' * D' * diag(W1.^2) * D * S;\n W2inv = diag(1./(W2.^2));\n B = 0.5 * Par.rho * W2inv;\n E = S' * D' * diag(W1.^2) * Y + 0.5 * (Par.rho * Z - U) * W2inv;\n C = sylvester(A, B, E);\n \n % %% faster solution\n % [Ua, Sa, ~] = svd(A);\n % I1 = eye(size(A, 2));\n % I2 = eye(size(B, 1));\n % K = kron(I1, A) + kron(B', I2);\n % invK = 1./diag(K);\n % UTE = Ua'*E;\n % vecUTE = UTE(:);\n % vecUTC = invK .* vecUTE;\n % MatvecUTC = reshape(vecUTC, [size(UTE, 1) size(UTE, 2)]);\n % C = Ua*MatvecUTC;\n \n %% update Z, fix X and D\n % min_{Z} 0.5 * rho * ||Z - (C + 1/rho * U)||_F^2 + ||Z||_1\n Temp = C + U/Par.rho;\n Z = sign(Temp) .* max( abs(Temp) - 1/Par.rho, 0 );\n \n %% check the convergence conditions\n stopCZ(iter) = max(max(abs(C - Z)));\n stopC(iter) = max(max(abs(C - Cpre)));\n stopZ(iter) = max(max(abs(Z - Zpre)));\n if Par.display %&& (iter==1 || mod(iter,10)==0 || stopC 0\n buf0(bcf,1:BL) = v0(win); % Use recursive double buffers\n buf1(bcf,1:BL) = v1(win);\n \n [u01,Zf0(1,count)] = filter(numa0,dena0,buf0(bcf,1:BL));\n [u11,Zf1(1,count)] = filter(numa1,dena1,buf1(bcf,1:BL));\n \n buf0(bcb,1:BL) = u01; \n buf1(bcb,1:BL) = u11;\n \n u0p(win) = buf0(bcb,1:BL);\n u1p(win) = buf1(bcb,1:BL);\n \n bcf = mod(bcf+2,2)+1; % Switch input buffer\n bcb = mod(bcb+2,2)+3; % Switch output buffer\n pointer = pointer + BL;\n win = [pointer:pointer + BL - 1]; % Slide window\n count = count - 1;\nend\n\n% Create/tx band coefficients\nL = u0p + u1p;\nH = u0p - u1p;", "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/6541-dbncaudiorecon-m/nciab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6456842751166271}} {"text": "function [varargout]=discQuadMesh(varargin)\n\n% function [F,V,C,indEdge]=discQuadMesh(nElements,r,f)\n% ------------------------------------------------------------------------\n% This function meshes a circle using quadrilaterial elements. \n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 10/05/2016 Updated for GIBBON\n%------------------------------------------------------------------------\n\n%% Parse input \nswitch nargin\n case 1\n nElements=varargin{1};\n r=1;\n f=0.5;\n case 2\n nElements=varargin{1};\n r=varargin{2};\n f=0.5;\n case 3\n nElements=varargin{1};\n r=varargin{2};\n f=varargin{3};\nend\n\n%% Creating central regular quad mesh\n\nnElements=nElements+~iseven(nElements);%Force even\n\n[X_centralMesh,Y_centralMesh]=meshgrid(linspace(-1,1,nElements+1));\n[F_centralMesh,V_centralMesh] = surf2patch(X_centralMesh,Y_centralMesh,zeros(size(X_centralMesh)));\nV_centralMesh=V_centralMesh(:,1:2);\n\n%Edge of central mesh\nlogicCentralMeshEdge=(X_centralMesh==1)|(Y_centralMesh==1)|(X_centralMesh==-1)|(Y_centralMesh==-1);\nnEdge=(nElements*4);\n\n% Scaling radius\n[ThetaMesh,RadiusMesh]=cart2pol(V_centralMesh(:,1),V_centralMesh(:,2));\nRadiusMesh=f*(1/2)*sqrt(2)*RadiusMesh;\n[V_centralMesh(:,1),V_centralMesh(:,2)]=pol2cart(ThetaMesh,RadiusMesh);\n\n%% Creating outer mesh\n\nRadiusOuterEdge=ones(1,nEdge);\nThetaOuterEdge=linspace(0,pi*2,nEdge+1); \nThetaOuterEdge=ThetaOuterEdge(2:end)-pi;\n\n[xOuterEdge,yOuterEdge]=pol2cart(ThetaOuterEdge,RadiusOuterEdge);\nV_outerEdge=[xOuterEdge(:) yOuterEdge(:)];\n\nV_innerEdge=V_centralMesh(logicCentralMeshEdge,:);\n[ThetaEdge,RadiusEdge]=cart2pol(V_innerEdge(:,1),V_innerEdge(:,2));\n[ThetaEdge,sortInd]=sort(ThetaEdge);\nRadiusEdge=RadiusEdge(sortInd);\n[V_innerEdge(:,1),V_innerEdge(:,2)]=pol2cart(ThetaEdge,RadiusEdge);\n\n[Xr]=linspacen(V_innerEdge(:,1),V_outerEdge(:,1),nElements/2+1); Xr(end+1,:)=Xr(1,:);\n[Yr]=linspacen(V_innerEdge(:,2),V_outerEdge(:,2),nElements/2+1); Yr(end+1,:)=Yr(1,:);\n\n[Fs2,Vs2] = surf2patch(Xr,Yr,zeros(size(Xr)));\nVs2=Vs2(:,1:2);\n\nV=[V_centralMesh;Vs2];\nF=[F_centralMesh;Fs2+size(V_centralMesh,1)];\nC=[ones(size(F_centralMesh,1),1); 2*ones(size(Fs2,1),1); ];\n\nindEdge=((size(V,1)-size(Xr,1))+1):size(V,1);\n\n%% Removing double points\n\n[F,V,~,IND_IND]=mergeVertices(F,V);\nindEdge=IND_IND(indEdge(1:end-1));\n\n%Scaling radius\n[ThetaMesh,RadiusMesh]=cart2pol(V(:,1),V(:,2));\nRadiusMesh=r*RadiusMesh;\n[V(:,1),V(:,2)]=pol2cart(ThetaMesh,RadiusMesh);\n\nvarargout{1}=F; \nvarargout{2}=V; \nvarargout{3}=C; \nvarargout{4}=indEdge; \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/discQuadMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6456842726985891}} {"text": "function [ fea, out ] = ex_navierstokes1( varargin )\n%EX_NAVIERSTOKES1 2D Example for incompressible stationary flow in a channel.\n%\n% [ FEA, OUT ] = EX_NAVIERSTOKES1( VARARGIN ) Sets up and solves stationary Poiseuille\n% flow in a rectangular channel. The inflow profile is constant and the outflow\n% should assume a parabolic profile ( u(y)=U_max*4/h^2*y*(h-y) ).\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% rho scalar {1} Density\n% miu scalar {0.001} Molecular/dynamic viscosity\n% umax scalar {0.3} Maximum magnitude of inlet velocity\n% h scalar {0.5} Channel height\n% l scalar {2.5} Channel length\n% igrid scalar 1/{0} Cell type (0=quadrilaterals, 1=triangles)\n% hmax scalar {0.04} Max grid cell size\n% sf_u string {sflag1} Shape function for velocity\n% sf_p string {sflag1} Shape function for pressure\n% iphys scalar 0/{1} Use physics mode to define problem (=1)\n% solver string openfoam/su2/{} Use OpenFOAM, SU2, FEniCS, or default solver\n% ischeme scalar {0} Time stepping scheme (0 = stationary)\n% iplot scalar 0/{1} Plot solution and error (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n%\n% See also EX_NAVIERSTOKES1B\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'rho', 1;\n 'miu', 1e-3;\n 'umax', 0.3;\n 'h', 0.5;\n 'l', 2.5;\n 'igrid', 1;\n 'hmax', 0.04;\n 'sf_u', 'sflag1';\n 'sf_p', 'sflag1';\n 'iphys', 1;\n 'solver', '';\n 'ischeme', 0;\n 'iplot', 1;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\n% Model parameters.\nrho = opt.rho; % Density.\nmiu = opt.miu; % Molecular/dynamic viscosity.\numax = opt.umax; % Maximum magnitude of inlet velocity.\n% Geometry and grid parameters.\nh = opt.h; % Height of rectangular domain.\nl = opt.l; % Length of rectangular domain.\n% Discretization parameters.\nsf_u = opt.sf_u; % FEM shape function type for velocity.\nsf_p = opt.sf_p; % FEM shape function type for pressure.\n\n\n% Geometry definition.\ngobj = gobj_rectangle( 0, l, 0, h );\nfea.geom.objects = { gobj };\nfea.sdim = { 'x' 'y' }; % Coordinate names.\n\n\n% Grid generation.\nif ( opt.igrid==1 )\n fea.grid = gridgen(fea,'hmax',opt.hmax,'fid',fid);\nelse\n fea.grid = rectgrid(round(l/opt.hmax),round(h/opt.hmax),[0 l;0 h]);\n if( opt.igrid<0 )\n fea.grid = quad2tri( fea.grid );\n end\nend\nn_bdr = max(fea.grid.b(3,:)); % Number of boundaries.\n\n\n% Boundary conditions.\ndtol = opt.hmax;\ni_inflow = findbdr( fea, ['x<',num2str(dtol)] ); % Inflow boundary number.\ni_outflow = findbdr( fea, ['x>',num2str(l-dtol)] ); % Outflow boundary number.\ns_inflow = ['2/3*',num2str(umax)]; % Definition of inflow profile.\ns_refsol = ['4*',num2str(umax),'*(y*(',num2str(h),'-y))/',num2str(h),'^2']; % Definition of velocity profile.\n\n\n% Problem definition.\nif ( opt.iphys==1 )\n\n fea = addphys(fea,@navierstokes); % Add Navier-Stokes equations physics mode.\n fea.phys.ns.eqn.coef{1,end} = { rho };\n fea.phys.ns.eqn.coef{2,end} = { miu };\n fea.phys.ns.eqn.coef{5,end} = { s_inflow };\n if( any(strcmp(opt.solver,{'openfoam','su2'})) )\n fea.phys.ns.sfun = { 'sflag1', 'sflag1', 'sflag1' };\n else\n fea.phys.ns.sfun = { sf_u sf_u sf_p }; % Set shape functions.\n end\n fea.phys.ns.bdr.sel(i_inflow) = 2;\n fea.phys.ns.bdr.sel(i_outflow) = 4;\n fea.phys.ns.bdr.coef{2,end}{1,i_inflow} = s_inflow; % Set inflow profile.\n fea = parsephys(fea); % Check and parse physics modes.\n\nelse\n\n fea.dvar = { 'u' 'v' 'p' }; % Dependent variable name.\n fea.sfun = { sf_u sf_u sf_p }; % Shape function.\n\n % Define equation system.\n cvelx = [num2str(rho),'*',fea.dvar{1}]; % Convection velocity in x-direction.\n cvely = [num2str(rho),'*',fea.dvar{2}]; % Convection velocity in y-direction.\n fea.eqn.a.form = { [2 3 2 3;2 3 1 1] [2;3] [1;2];\n [3;2] [2 3 2 3;2 3 1 1] [1;3];\n [2;1] [3;1] [] };\n fea.eqn.a.coef = { {2*miu miu cvelx cvely} miu -1;\n miu {miu 2*miu cvelx cvely} -1;\n 1 1 [] };\n fea.eqn.f.form = { 1 1 1 };\n fea.eqn.f.coef = { 0 0 0 };\n\n\n % Define boundary conditions.\n fea.bdr.d = cell(3,n_bdr);\n [fea.bdr.d{1:2,:}] = deal( 0 );\n\n fea.bdr.d{1,i_inflow} = s_inflow;\n\n [fea.bdr.d{:,i_outflow }] = deal([]);\n % fea.bdr.d{end,i_outflow} = 0; % Set pressure to zero on outflow boundary.\n\n fea.bdr.n = cell(3,n_bdr);\nend\n\n\n% Parse and solve problem.\nfea = parseprob(fea); % Check and parse problem struct.\nif( opt.iphys==1 && strcmp(opt.solver,'fenics') )\n fea = fenics( fea, 'fid', fid, 'ischeme', opt.ischeme, 'tmax', 10 );\nelseif( opt.iphys==1 && strcmp(opt.solver,'openfoam') )\n if( opt.ischeme==0 )\n dt = 1.0;\n tstop = 1000;\n ddtScheme = 'steadyState';\n elseif( opt.ischeme==1 )\n dt = 0.1;\n tstop = 100;\n ddtScheme = 'backward';\n elseif( opt.ischeme>=2 )\n dt = 0.1;\n tstop = 100;\n ddtScheme = 'CrankNicolson 0.9';\n end\n logfid = fid; if( ~got.fid ), fid = []; end\n fea.sol.u = openfoam( fea, 'fid', fid, 'logfid', logfid, 'ddtScheme', ddtScheme, 'deltaT', dt, 'endTime', tstop );\n fid = logfid;\nelseif( opt.iphys==1 && strcmp(opt.solver,'su2') )\n logfid = fid; if( ~got.fid ), fid = []; end\n fea.sol.u = su2( fea, 'fid', fid, 'logfid', logfid, 'ischeme', opt.ischeme, 'tstep', 0.5, 'tmax', 20+30*(opt.ischeme==1) );\n fid = logfid;\nelse\n if( opt.ischeme==0 )\n jac.form = {[1;1] [1;1] [];[1;1] [1;1] []; [] [] []};\n jac.coef = {[num2str(rho),'*ux'] [num2str(rho),'*uy'] []; [num2str(rho),'*vx'] [num2str(rho),'*vy'] []; [] [] []};\n fea.sol.u = solvestat( fea, 'fid', fid, 'nsolve', 2, 'jac', jac ); % Call to stationary solver.\n else\n fea.sol.u = solvetime( fea, 'fid', fid, 'ischeme', opt.ischeme, 'tmax', 10 );\n end\nend\nfea.sol.u = fea.sol.u(:,end);\n\n\n% Postprocessing.\ns_velm = 'sqrt(u^2+v^2)';\ns_err = ['abs(sqrt((',s_refsol,')^2)-(',s_velm,'))'];\ns_len = ['(x>',num2str(3/4*l),')'];\nif ( opt.iplot>0 )\n figure\n subplot(3,1,1)\n postplot(fea,'surfexpr',s_velm,'evaltype','exact')\n title('Velocity field')\n subplot(3,1,2)\n postplot(fea,'surfexpr','p','evaltype','exact')\n title('Pressure')\n subplot(3,1,3)\n postplot(fea,'surfexpr',[s_err,'*',s_len],'evaltype','exact')\n title('Error')\nend\n\n\n% Error checking.\nif ( size(fea.grid.c,1)==4 )\n xi = [0;0];\nelse\n xi = [1/3;1/3;1/3];\nend\nc_ind = find(evalexpr0(s_len,xi,1,1:size(fea.grid.c,2),[],fea))';\nerr = evalexpr0(s_err,xi,1,c_ind,[],fea);\nref = evalexpr0(['sqrt((',s_refsol,')^2)'],xi,1,c_ind,[],fea);\nerr = sqrt(sum(err.^2)/sum(ref.^2));\n\n\nif( ~isempty(fid) )\n fprintf(fid,'\\nL2 Error: %f\\n',err)\n fprintf(fid,'\\n\\n')\nend\n\n\nout.err = err;\nout.pass = err<0.06;\nif ( nargout==0 )\n clear fea out\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_navierstokes1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842652322471}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n%Fourier Transfrom properties\n\n%\tTime reversal\n\n%x(t)=t*u(t)\n\n%X(-w)\nx=t*heaviside(t);\nX=fourier(x,w) ;\nRight=subs(X,w,-w)\n\n%x(-t)\nx_t=subs(x,t,-t);\nLeft=fourier(x_t,w)\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/6/c64e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842551356392}} {"text": "% blob_unity1.m\n% find blob parameters that make the best \"partition of unity\"\n% jeff fessler\n\n% 1d\n% J m alpha\talpha/J\t(max/min-1)%\n% 2 2 2.502\t1.251\t0.0192\t\t1 min\n% 3 2 2.472\t0.824\t0.0021\t\t2 min\n% 3 2 7.464\t2.488\t0.0587776%\t\"\n% 4 2 2.461\t0.61525 0.000315658%\t3 min\n% 4 2 8.687\t2.17175\t0.0102284%\t\"\n% 4 2 11.17\t2.7925\t0.00177428%\t\"\n\n% 2d\n% J m alpha\talpha/J\t(max/min-1)%\n% 4 2 7.888\t1.972\t0.0411645\n% 4 2 10.83\t2.7075\t0.0180456%\n\n% 3d\n% J m alpha\talpha/J\t(max/min-1)%\n% 4 2 10.4\t2.6\t0.0290578\tand mae and rmse < 0.01%.\n% for CT this is a fraction of a HU!\n\nif ~isvar('J')\n\tJ = 4; % a = J/2\n\n\talf_list = linspace(0.5*J, 3.0*J, 26+0*101);\n\talf_list = linspace(7, 12, 5*10+1); % 2d\n\talf_list = linspace(10.5, 11, 5*10+1); % 2d\n\talf_list = linspace(2, 12, 10001); % 1d\n\talf_list = linspace(7.0, 8.0, 1001); % 1d fine, J=3\nalf_list = linspace(0.1, 20, 1001); % 1d coarse\n\talf_list = linspace(8.0, 9.0, 1001); % 1d fine, J=4\n%\talf_list = linspace(10.3, 10.5, 3); % 3d\n%\talf_list = 10.4; % 3d\n%\tm_list = linspace(1.9, 2.1, 21);\n\tm_list = 2.0;\n\t%alf_list = 2.34 * J;\n\t%m_list = 2;\n\t[aa mm] = ndgrid(alf_list, m_list);\n\n\tx1 = linspace(0, J/2, 101)';\n\tx2 = linspace(0, J/2, 101)';\n\tx3 = linspace(0, J/2, 101)';\n\tx2 = 0; % 1d\n\tx3 = 0; % 2d\n\t[xx1 xx2 xx3] = ndgrid(x1, x2, x3);\n\n\t% get all j that affect x in [0,J/2]\n\tj1max = ceil(J-1);\n\tj1min = floor(-J/2+1);\n\tndim = 1 + (length(x2) > 1);\n\tnj1 = j1max-j1min+1;\n\n\tif ndim >= 3\n\t\tnj3 = nj1;\n\t\tj3min = j1min;\n\t\tj3max = j1max;\n\telse\n\t\tnj3 = 1;\n\t\tj3min = 0;\n\t\tj3max = 0;\n\tend\n\n\tif ndim >= 2\n\t\tnj2 = nj1;\n\t\tj2min = j1min;\n\t\tj2max = j1max;\n\telse\n\t\tnj2 = 1;\n\t\tj2min = 0;\n\t\tj2max = 0;\n\tend\nend\n\n\n%\n% precompute r samples for each j offset\n%\nif ~isvar('rr'), disp 'do rr'\n\trr = zeros([length(x1) length(x2) length(x3) nj1 nj2 nj3]);\n\tfor j3=j3min:j3max\n\t\tfor j2=j2min:j2max\n\t\t\tfor j1=j1min:j1max\n\t\t\t\trr(:,:,:,j1-j1min+1,j2-j2min+1,j3-j3min+1) = ...\n\t\t\t\tsqrt((xx1-j1).^2 + (xx2-j2).^2 + (xx3-j3).^2);\n\t\t\tend\n\t\tend\n\tend\n\t%im(x1, x2, rr)\nend\n\nif ~isvar('bad'), disp 'do bad'\n\tbad = zeros(size(mm));\n\tbb = zeros(length(x1), length(x2), length(x3), nj1*nj2*nj3);\n\n\tfor ii=1:numel(aa)\n\t\tticker(mfilename, ii, numel(aa))\n\t\tkb_a = aa(ii);\n\t\tkb_m = mm(ii);\n\n\t\tbb = kaiser_bessel(rr, J, kb_a, kb_m);\n\t\tbsum = sum(sum(sum(bb, 3), 4), 5);\n\t\tbad(ii) = max(bsum(:)) / min(bsum(:));\n\tend\n\tbad = abs(bad-1);\nend\n\nif 1\n\tim clf, im(121, alf_list/J, m_list, bad), cbar\n\taxis normal\n\thold on\n\tibest = imin(bad, 2);\n\tplot(alf_list(ibest(1))/J, m_list(ibest(2)), '*')\n\thold off\n\txlabel '\\alpha/J', ylabel 'm'\nend\n\nif ~isvar('bmean')\n\tkb_a = alf_list(ibest(1));\n\tkb_m = m_list(ibest(2));\n\n\tbb = kaiser_bessel(rr, J, kb_a, kb_m);\n\tbsum = sum(sum(sum(bb, 3), 4), 5);\n\tbmean = mean(bsum(:));\nend\n\nprintf('J m alpha alpha/J ratio-1')\nprintf('%g %g %g %g %g%%', ...\n\tJ, kb_m, kb_a, kb_a / J, (max(bsum(:)) / min(bsum(:))-1)*100)\nprintf('mea=%g%%', mean(abs(bsum(:)-bmean))/bmean * 100)\nprintf('rmse=%g%%', sqrt(mean(abs(bsum(:)-bmean).^2))/bmean * 100)\n\nif 1\n\tsubplot(122)\n\tif ndim == 1\n\t\tplot(x1, reshape(bb, length(x1), []), '--', x1, bsum, '-')\n\t\tclf, semilogy(alf_list, bad, '.-'), xlabel '\\alpha'\n\telse\n\t\tim(x1, x2, bsum/bmean, 'bsum/bmean'), cbar\n\tend\nend\n\nif 0\n\tclf\n\tfor j1=1:nj1\n\t\tfor j2=1:nj2\n\t\t\tsubplot(nj1, nj2, j1 + (j2-1)*nj1)\n\t\t\tif ndim == 1\n\t\t\t\tplot(x1, bb(:,1,j1,j2))\n\t\t\telse\n\t\t\t\tim(x1, x2, bb(:,:,j1,j2))\n\t\t\tend\n\t\tend\n\tend\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/blob/blob_unity1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842526114871}} {"text": "% \n%\n% Copyright (c) 2012 University of Crete - Computer Science Department (UOC-CSD)\n%\n% License\n% This file is under the LGPL license, you can\n% redistribute it and/or modify it under the terms of the GNU Lesser General \n% Public License as published by the Free Software Foundation, either version 3 \n% of the License, or (at your option) any later version. This file is\n% distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n% PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n% details.\n%\n% This function is part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Gilles Degottex \n%\n\nfunction p = wrappednormcdf(x, m, s, N)\n\n % N=10 gives a log error smaller than 1e-12 for s=8\n % with s=8 distribution is \"almost\" uniform (std < 1e-12)\n if nargin<4; N=10; end\n\n p = 0;\n for k=-N:N\n p = p + normcdf(x+2.*pi.*k, m, s);\n end\n\n p = p - N;\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/misc/wrappednormcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6456842501934492}} {"text": "classdef CoSaMP < handle\n % Implements CoSaMP-MMV algorithm for sparse recovery\n\n properties\n % These properties can be configured before running cosamp\n % Default threshold\n errorNormThreshold = 1e-6;\n % Maximum number of iterations for approximation\n MaxIters\n Verbose = false\n % Indicates if matching pursuit should be used for identification\n % UseMPIdentification = false\n % Indicates if least squares should be run on final support\n LSOnFinalSupport = false\n % The norm to be chosen for rows\n P\n % Indicates that residuals should be orthogonalized for rank awareness\n RankAwareResidual = false\n end\n\n properties(SetAccess=private)\n % The dictionary\n Dict\n % Ambient signal dimensions\n N\n % Number of atoms in dictionary\n D\n % Sparsity level of representations (may be negative)\n K\n % Result of a solver\n result\n end\n \n methods\n function self = CoSaMP(Dict, K, P, options)\n if nargin < 3\n % By default we apply l_1 norm on rows\n P = 1;\n end\n if P ~= 1 && P ~= 2\n error('Only l_1 and l_2 norms are supported.');\n end\n self.P = P;\n % We assume that all the columns in dictionary are normalized.\n if isa(Dict, 'spx.dict.Operator')\n self.Dict = Dict;\n elseif ismatrix(Dict)\n self.Dict = spx.dict.MatrixOperator(Dict); \n else\n error('Unsupported operator.');\n end\n [self.N, self.D] = size(Dict);\n if nargin < 2\n % No sparsity level has been pre-specified.\n % We make an estimate of sparsity level\n % based on phase transition analysis by Donoho\n K = round((self.N / 2) * log (self.D));\n end\n self.K = K;\n % Maximum number of iterations\n maxIter = 30;\n self.MaxIters = maxIter;\n if nargin >= 4\n % options have been specified \n if isfield(options, 'RankAwareResidual')\n self.RankAwareResidual = options.RankAwareResidual;\n end\n end\n end\n\n function result = solve(self,Y)\n n = self.N;\n d = self.D;\n k = self.K;\n % The number of signals being approximated.\n s = size(Y, 2); \n dict = self.Dict;\n % Current estimate\n solution_nz_mat = zeros(k,s);\n % Current residual\n residual_mat = Y;\n % Number of iterations\n iterations = 0;\n y_norm = norm(Y, 'fro');\n old_residual_norm = 1;\n min_residual_norm = old_residual_norm;\n errorNormThreshold = self.errorNormThreshold;\n maxIterations = self.MaxIters;\n result.halted_on_max_iter = false;\n result.halted_on_residual_norm = false;\n result.halted_on_norm_change = false;\n result.halted_on_support_change = false;\n % K indices for current support\n current_support = [];\n while true\n iterations = iterations+1;\n % We identify the support for largest 2K entries\n extra = 2*k;\n % if isempty(current_support)\n % extra = k + extra;\n % end\n if self.RankAwareResidual\n residual_mat = orth(residual_mat);\n end\n % Compute the proxy\n proxy_mat = dict.apply_ctranspose(residual_mat);\n % identify the largest entries\n largest_2k = spx.pursuit.joint.CoSaMP.largest_k_l2(proxy_mat, extra);\n % We now compute our support\n % build an array holding up to 3 K largest indices\n support_3k = false(d, 1);\n % the older K columns\n support_3k(current_support) = true;\n % New 2K columns\n support_3k(largest_2k) = true; % T <= 3K\n % We pickup corresponding columns from Phi\n subdict = dict.columns(support_3k); % MxT\n % We compute signal estimate over these columns\n % B_subdict = linsolve(subdict, Y); % TxM * MxS\n B_subdict = spx.pursuit.joint.CoSaMP.least_squares_on_support(subdict, Y);\n % sort them in descending row norm order\n pruned_largest_k = spx.pursuit.joint.CoSaMP.largest_k_l2(B_subdict, k);\n % keep only first k rows as new solution\n solution_nz_mat = B_subdict(pruned_largest_k, :);\n old_support = current_support;\n % update current support by choosing largest k indices\n support_3k = find(support_3k == 1);\n current_support = support_3k(pruned_largest_k);\n % compute the measurement estimate\n y_estimate_matrix = dict.apply_columns(...\n solution_nz_mat, current_support);\n % compute the new residual\n residual_mat = Y - y_estimate_matrix;\n % compute the residual norm\n residual_norm = norm(residual_mat, 'fro');\n residual_norm = residual_norm / y_norm;\n % how many indices have been added and/or removed\n support_change = length(union(old_support,current_support)) - length(intersect(old_support,current_support));\n % if residual_norm > 1.2*min_residual_norm\n % % We are diverging\n % break;\n % end\n if residual_norm < old_residual_norm\n improvement = (old_residual_norm - residual_norm) / old_residual_norm;\n % if improvement < 1e-8\n % % No improvement in this iteration\n % result.halted_on_norm_change = true;\n % break;\n % end\n end\n if(residual_norm < errorNormThreshold)\n result.halted_on_residual_norm = true;\n break;\n end\n if iterations >= maxIterations\n % Too many iterations we are going nowhere\n result.halted_on_max_iter = true;\n break;\n end\n if ~isempty(old_support) && support_change == 0\n result.halted_on_support_change = true;\n break;\n end\n % TODO add support for detection of no change \n % in support\n old_residual_norm = residual_norm;\n min_residual_norm = min(residual_norm, min_residual_norm);\n end\n % CoSaMP is done\n if self.LSOnFinalSupport\n % This is used only in high coherence situations.\n % The least squares estimate is not good enough\n % as it allows more distribution of energy on to other 2K indices\n % solve another least squares problem.\n subdict = dict.columns(current_support);\n solution_nz_mat = linsolve(subdict, Y);\n end\n % copy the solution\n result.Z = zeros(d, s);\n result.Z(current_support, :) = solution_nz_mat;\n % copy the measurement residual\n result.R = residual_mat;\n result.iterations = iterations;\n result.support = current_support;\n end\n\n end\n\n methods(Static)\n function largest_indices = largest_thresholding(dict, R, count)\n % We create the proxy of current residual\n E = dict.apply_ctranspose(R);\n tmp = abs(e);\n [~, indices] = sort(tmp, 'descend');\n % We identify the support for largest count entries\n largest_indices = indices(1:count);\n end\n\n function largest_indices = largest_k_l1(data_matrix, K)\n sums = spx.norm.norms_l1_rw(data_matrix);\n [~, indices] = sort(sums, 'descend');\n % We identify the support for largest K entries\n largest_indices = indices(1:K);\n end\n\n function largest_indices = largest_k_l2(data_matrix, K)\n sums = spx.norm.norms_l2_rw(data_matrix);\n [~, indices] = sort(sums, 'descend');\n % We identify the support for largest K entries\n largest_indices = indices(1:K);\n end\n\n function largest_indices = largest_mp(dict, r, count)\n % Uses matching pursuit to identify largest indices.\n % We create the proxy of current residual\n d = size(dict,2);\n indices = false(1, d);\n k = 0;\n while k < count\n products = dict.apply_ctranspose(r);\n abs_products = abs(products);\n % Find the highest inner product\n [~, index] = max(abs_products);\n % Add this index to support\n if ~indices(index)\n % we have discovered a new atom.\n k = k + 1;\n indices(index) = true;\n end\n % pick up the coefficient of this inner product\n coeff = products(index);\n % update residual\n r = r - coeff * dict.column(index);\n end\n % We identify the support for largest 2K entries\n largest_indices = find(indices);\n end\n\n function X = least_squares_on_support(subdict, Y)\n [U,s,V] = csvd(subdict);\n num_signals = size(Y, 2);\n num_cols = size(subdict, 2);\n X = zeros(num_cols, num_signals);\n x = zeros(num_cols, 1);\n for ns=1:num_signals\n y = Y(:, ns);\n normBound = 2*norm(y);\n [alpha2,lambda,maxIterReached] = lsqi(U,s,V,y,normBound);\n if maxIterReached\n % lsqi did not converge; use cvx (slower) instead\n [aa,bb] = size(subdict);\n cvx_begin quiet\n variable alpha3(bb) complex;\n minimize norm(y - subdict*alpha3)\n subject to\n norm(alpha3) <= normBound;\n cvx_end\n x = alpha3;\n else \n x = alpha2;\n end\n X(:, ns) = x;\n end\n end\n end\nend\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+pursuit/+joint/CoSaMP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842500873349}} {"text": "% DEMO\n%\n% Demonstrate the use of the Support Vector Machine toolbox to distinguish\n% examples of Versicolour from Setosa and Virginica varieties of Iris, given\n% petal width an length attributes. The data is taken from the well known\n% Iris benchmark [1], available from the UCI Repository of Machine Learning\n% Databases (http://www.ics.uci.edu/~mlearn/MLRepository.html).\n%\n% [1] R. A. Fisher,\n% \"The use of multiple measurements in taxonomic problems\",\n% Annual Eugenics, 7(2), pp 179-188, 1936.\n\n%\n% File : demo.m\n%\n% Date : Saturday 16th September 2000\n%\n% Author : Dr Gavin C. Cawley\n%\n% Description : Test harness for object oriented implementation of Vapnik's\n% linear support vector machine (SVM) [1].\n%\n% References : [1] V.N. Vapnik,\n% \"The Nature of Statistical Learning Theory\",\n% Springer-Verlag, New York, ISBN 0-387-94559-8,\n% 1995.\n%\n% History : 16/08/1999 - v1.00\n% 13/09/2000 - v1.01 minor changes to comments etc\n% 13/09/2000 - v1.02 updated to use gateway method svc/train\n% 16/09/2000 - v1.10 added xi-alpha estimate of l-o-o error\n% 24/11/2000 - v1.11 minor bug-fix for loading iris data under\n% all operating systems.\n%\n% Copyright : (c) Dr Gavin C. Cawley, November 2000.\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n\n% start from a clean slate\n\nclf;\n\nclear classes all;\n\n% load some data\n\nfprintf(1,'loading training data...\\n');\n\niris = load('data/iris.txt');\n\nx = iris(:,3:4);\ny = 2*(iris(:,5) == 2)-1;\n\n% define useful constants\n\nl = size(x,1);\n\n% display data\n\nfprintf(1,'displaying data...\\n');\n\nplot(x(find(y==1),1)',x(find(y==1),2)','bs',x(find(y==-1),1)',x(find(y==-1),2)','go')\naxis(axis + [-0.1 +0.1 -0.1 +0.1])\nlegend('class one','class two',0);\ndrawnow;\n\n% create tutor\n\nfprintf(1,'creating tutor...\\n');\n\nkernel = rbf(0.5);\nC = 1.0;\ntutor = smosvctutor;\n\n% train support vector machine\n\nfprintf(1,'training support vector machine...\\n');\n\nnet = train(svc, tutor, x, y, C, kernel);\n\nnet = fixduplicates(net, x, y);\n\nnet2 = strip(net);\n\n% display support vectors\n\nfprintf(1,'displaying support vectors...\\n');\n\nsv = getsv(net2);\n\nhold on\nplot(sv(:,1)',sv(:,2)','k+');\nlegend('class one','class two','support vector',0);\nhold off\n\nfprintf(1, 'there are %d support vectors\\n', getnsv(net2));\n\n% compute correctness\n\nfprintf(1,'correctness = %4.1f%%\\n', 100*sum(sign(fwd(net2,x))==y)/l);\n\n% display decision boundary\n\nfprintf(1,'displaying decision boundary...\\n');\n\na = axis;\n[X,Y] = meshgrid(a(1):0.05:a(2),a(3):0.05:a(4));\nX2 = [reshape(X,prod(size(X)),1) reshape(Y,prod(size(X)),1)];\nz = fwd(net2,X2);\nz = reshape(z,size(X));\n\nhold on\ncontour(X,Y,z,[+1 +1],'b');\ncontour(X,Y,z,[+0 +0],'r');\ncontour(X,Y,z,[-1 -1],'g');\nlegend('class one','class two','support vector','class one margin','decision boundary','class two margin',0);\nhold off\n\n% highlight estimated leave-one-out errors\n\ne = xialpha(net);\n\ni = find(e);\n\nfprintf(1,'l-o-o correctness >= %4.1f%%\\n', 100*correctness(e));\n\nhold on\nplot(x(i,1)', x(i,2)', 'rx');\nlegend('class one','class two','support vector','class one margin','decision boundary','class two margin','l-o-o error',0);\nhold off\n\n% all done\n\nfprintf(1,'bye bye...\\n');\n\n% bye bye...\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/RSVista/mrMethods/svm/cawleyTools/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6455935290625755}} {"text": "function psi = data2psiX(data,srate,freqbins,permtest)\n% calculates phase slope index (PSI) as formulated in the paper:\n% Nolte G, Ziehe A, Nikulin VV, Schlogl A, Kramer N, Brismar T, Muller KR.\n% Robustly estimating the flow direction of information in complex physical systems.\n% Physical Review Letters. To appear.\n% (for further information: http://doc.ml.tu-berlin.de/causality/ )\n%\n% Usage:\n% psi = data2psiX(data,srate,freqbins,permtest);\n%\n% Input:\n% data: MxNxT matrix for M channels, N timepoints, and T trials\n% srate: data sampling rate in Hz\n% freqbins: KxQ matrix containing frequency boundaries in rows K. \n% permtest: Permutation test (boolean). If true, psi output values are in standardizes Z values\n% relative to a null hypothesis distribution\n%\n% Output:\n% psi: phase-slope-index values. For M channels PSI is an MxM matrix if \n% one frequency bin, or MxMxK if freqbins has K rows (with K>1).\n% psi(i,j) is the directed connectivity from channel i to\n% channel j, (e.g., channel i is the sender if psi(i,j) is\n% positive; channel i is the receiver if negative)\n%\n%\n% (This function was modified from the original by Mike X Cohen)\n\n\n% License\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 http://www.gnu.org/licenses/.\n\n% modified from the original dat2psi.m by mikexcohen@gmail.com\n\n%% check inputs and initialize\n\nif nargin<2\n help data2psiX\n error('Read help file.');\nelseif nargin==2\n permtest = 0;\n freqbins = [];\nelseif nargin==3\n permtest = 0;\nend\n\nn_permutes = 1000;\n\n\n% data dimensions\n[nchan,npnts,ntrials]=size(data);\n\n% define frequencies\nhz = linspace(0,srate/2,floor(npnts/2)+1);\nnhz = length(hz);\n\n% initialize\ncs = zeros(nchan,nchan,nhz);\npsi = zeros(nchan,nchan,size(freqbins,1));\n\n%% compute cross-spectral density\n\ndatafft = fft(bsxfun(@times,data,hanning(npnts)'),[],2);\n\n% trial-average cross-spectral density\nfor triali=1:ntrials\n for freqi=1:nhz\n \n tempfftdat = squeeze(datafft(:,freqi,triali))';\n cs(:,:,freqi) = cs(:,:,freqi) + tempfftdat'*conj(tempfftdat);\n end\nend\ncs = cs./triali;\n\n%% compute PSI\n\nfor freqbini=1:size(freqbins,1)\n \n % find FFT indices of requested frequency bands\n freqidx = dsearchn(hz',freqbins(freqbini,1)) : dsearchn(hz',freqbins(freqbini,2));\n nfidx = length(freqidx);\n \n if nfidx<4\n warning('There are fewer than four frequency bins. Consider using longer time windows or wider frequency bands.')\n end\n \n % temporary phase-frequency matrix from this frequency band\n pp = zeros(nchan,nchan,nfidx);\n \n for fi=1:nfidx\n pp(:,:,fi) = cs(:,:,freqidx(fi))./sqrt(diag(cs(:,:,freqidx(fi)))*diag(cs(:,:,freqidx(fi)))');\n end\n \n % average phase slope for each frequency band\n psi(:,:,freqbini) = sum(imag(conj(pp(:,:,1:end-1)).*pp(:,:,2:end)),3);\n \n \n %% optional permutation testing\n \n if permtest\n \n nulldist = zeros(nchan,nchan,n_permutes);\n for permi=1:n_permutes\n nulldist(:,:,permi) = sum(imag(conj(pp(:,:,randperm(nfidx))).*pp(:,:,randperm(nfidx))),3);\n end\n \n psi(:,:,freqbini) = ( psi(:,:,freqbini)-mean(nulldist,3) ) ./ std(nulldist,[],3);\n end\n \n % zero-out diagonals\n tmp = squeeze(psi(:,:,freqbini));\n tmp(logical(eye(nchan))) = 0;\n psi(:,:,freqbini) = tmp;\n \nend\n\n%% end\n\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/data2psiX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6455935147232873}} {"text": "function [C,T,A]=naca4_3d(airfoil,y,nc)\n% determine airfoil skin and camber coordinates from NACA designation\n%% NacaCoord.m\n% NACA 4-digit or 5-digit series airfoil\n%\n% outputs: C = matrix of camber line coordinates, x,y,z\n% ordered trailing edge first\n% T = matrix of skin coordinates\n% ordered from trailing edge over top surface then\n% along bottom surface to trailing edge\n% A = area of airfoil cross section (normalized)\n%\n% NOTE: Chord of output airfoil is 1\n%\n% inputs: airfoil = NACA 4- or 5-digit airfoil as string\n% y = spanwise location\n% nc = number of chordwise panels\n%\n% Ref: http://www.aerospaceweb.org/question/airfoils/q0041.shtml\n\n% Ira H. Abbott and Albert E. Von Doenhoff, Theory of Wing\n% Sections, 1959, Dover Publications, NY.\n%\n% Coordinate system:\n% x: chord direction, origin at LE, positive is pointing toward TE\n% y: station along span, perpendicular to aircraft midplane\n% z: perpendicular to chord, positive is up\n\n%This 'if' statement establishes the constants for either 4- or 5- digit\n%airfoils.\nif length(airfoil) == 4\n m = str2num(airfoil(1))/100;\n p = str2num(airfoil(2))/10;\n t = str2num(airfoil(3:4))/100;\n\nelseif length(airfoil) == 5\n switch airfoil(1:3)\n case '210'\n m = 0.0580;\n k1 = 361.4;\n case '220'\n m = 0.1260;\n k1 = 51.64;\n case '230'\n m = 0.2025;\n k1 = 15.957;\n case '240'\n m = 0.2900;\n k1 = 6.643;\n case '250'\n m = 0.3910;\n k1 = 3.230;\n otherwise\n end\n t = str2num(airfoil(4:5))/100;\nend\n\n\n\n\n\n%% Constants\n% nc % number of line segments describing top surface\n% (= number of line segments describing bottom surface)\nnpc = nc+1; % number of points along mean camber line\nnps = 2*nc+1; % number of points along surface\ndx=1/nc; % x-direction increment (along chord)\n\n%% Fill coordinate matrices with y coordinate\nC = zeros(npc,3); % mean camber\nC(:,2) = y;\nT = zeros(nps,3); %skin\nT(:,2) = y;\n\n%% Mean Camber Line and Slope\n% dzcdx is the derivative of the mean camber line\n% theta is the local angle of the mean camber line\n% x=1:-dx:0; % order x locations starting at trailing edge, x=1\nx=0:dx:1; % order x locations starting at leading edge, x=0\nif length(airfoil) == 4\n for i = 1:nc+1\n if x(i)

.\n\n%% Setup default parameters\n% translation, affine\ntransformationModel = 'affine';\n\n% multi-modal\nmultiModal = false;\n\n% number of channels, only valid for multi-modal registration\nnumberOfChannels = 8;\n\n% Overwrites default parameter\nfor k=1:2:length(varargin)\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\n% Initialize transformation matrix\ntransformationMatrix = eye(3);\n\n[b_moving(:,:,1) b_moving(:,:,2)] = gradient(moving);\n[b_fixed(:,:,1) b_fixed(:,:,2)] = gradient(fixed);\n\nif multiModal\n b = b_fixed(:,:,2);\n b(:,:,2) = b_fixed(:,:,1);\n \n [delta_c mask] = estimate_delta_c(fixed,moving,numberOfChannels);\n delta_c(mask ~= 1) = 0;\n mask = repmat(mask,[1 1 2]);\n b(mask ~= 1) = 0;\nelse\n b = (b_moving(:,:,2) + b_fixed(:,:,2))/2;\n b(:,:,2) = (b_moving(:,:,1) + b_fixed(:,:,1))/2;\n \n delta_c = fixed - moving;\nend\n\n[G, h] = build_G_h_linear2d(b, delta_c, transformationModel);\n \n% Solve the equation system\nswitch transformationModel\n case 'translation'\n d = G \\ h;\n transformationMatrix(1:2,3) = d;\n case {'rigid','affine'}\n p = G \\ h;\n transformationMatrix(1:2,1:3) = [1+p(1) p(2) p(5);...\n p(3) 1+p(4) p(6)];\nend\n", "meta": {"author": "fordanic", "repo": "image-registration", "sha": "36c23d5da1f035b07c66a04fe5bac20de1bd1c74", "save_path": "github-repos/MATLAB/fordanic-image-registration", "path": "github-repos/MATLAB/fordanic-image-registration/image-registration-36c23d5da1f035b07c66a04fe5bac20de1bd1c74/registration/optical-flow/optical_flow_linear_registration2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758842, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6455774104635825}} {"text": "function [mssim, ssim_map, mcs, cs_map] = ssim_index_new(img1, img2, K, win, max_val)\n\nif (nargin < 2 || nargin > 5)\n mssim = -Inf;\n ssim_map = -Inf;\n return;\nend\n\nif (size(img1) ~= size(img2))\n mssim = -Inf;\n ssim_map = -Inf;\n return;\nend\n\n[M N] = size(img1);\n\nif (nargin == 2)\n if ((M < 11) || (N < 11))\n\t mssim = -Inf;\n\t ssim_map = -Inf;\n return\n end\n win = fspecial('gaussian', 11, 1.5);\t%\n K(1) = 0.01;\t\t\t\t\t\t\t\t\t\t% default settings\n K(2) = 0.03;\t\t\t\t\t\t\t\t\t\t%\nend\n\nif (nargin == 3)\n if ((M < 11) || (N < 11))\n\t mssim = -Inf;\n\t ssim_map = -Inf;\n return\n end\n win = fspecial('gaussian', 11, 1.5);\n if (length(K) == 2)\n if (K(1) < 0 || K(2) < 0)\n\t\t mssim = -Inf;\n \t\tssim_map = -Inf;\n\t \treturn;\n end\n else\n\t mssim = -Inf;\n \tssim_map = -Inf;\n\t return;\n end\nend\n\nif (nargin == 4 || nargin == 5)\n [H W] = size(win);\n if ((H*W) < 4 || (H > M) || (W > N))\n\t mssim = -Inf;\n\t ssim_map = -Inf;\n return\n end\n if (length(K) == 2)\n if (K(1) < 0 || K(2) < 0)\n\t\t mssim = -Inf;\n \t\tssim_map = -Inf;\n\t \treturn;\n end\n else\n\t mssim = -Inf;\n \tssim_map = -Inf;\n\t return;\n end\nend\n\nC1 = (K(1)*max_val)^2;\nC2 = (K(2)*max_val)^2;\nwin = win/sum(sum(win));\n\nmu1 = filter2(win, img1, 'valid');\nmu2 = filter2(win, img2, 'valid');\nmu1_sq = mu1.*mu1;\nmu2_sq = mu2.*mu2;\nmu1_mu2 = mu1.*mu2;\nsigma1_sq = filter2(win, img1.*img1, 'valid') - mu1_sq;\nsigma2_sq = filter2(win, img2.*img2, 'valid') - mu2_sq;\nsigma12 = filter2(win, img1.*img2, 'valid') - mu1_mu2;\n\nif (C1 > 0 & C2 > 0)\n ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));\n cs_map = (2*sigma12 + C2)./(sigma1_sq + sigma2_sq + C2);\nelse\n numerator1 = 2*mu1_mu2 + C1;\n numerator2 = 2*sigma12 + C2;\n\tdenominator1 = mu1_sq + mu2_sq + C1;\n denominator2 = sigma1_sq + sigma2_sq + C2;\n \n ssim_map = ones(size(mu1));\n index = (denominator1.*denominator2 > 0);\n ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));\n index = (denominator1 ~= 0) & (denominator2 == 0);\n ssim_map(index) = numerator1(index)./denominator1(index);\n \n cs_map = ones(size(mu1));\n index = denominator2 > 0;\n cs_map(index) = numerator2(index)./denominator2(index);\nend\n\nmssim = mean2(ssim_map);\nmcs = mean2(cs_map);\n\nreturn", "meta": {"author": "sooyekim", "repo": "Deep-SR-ITM", "sha": "139ca3b8b236e599a4361dc0797a0ff0b3c67665", "save_path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM", "path": "github-repos/MATLAB/sooyekim-Deep-SR-ITM/Deep-SR-ITM-139ca3b8b236e599a4361dc0797a0ff0b3c67665/utils/ssim_index_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6454794002298315}} {"text": "function [Y, problem, S] = elliptope_SDP_complex(A, p, Y0)\n% Solver for complex semidefinite programs (SDP's) with unit diagonal.\n% \n% function [Y, problem, S] = elliptope_SDP_complex(A)\n% function [Y, problem, S] = elliptope_SDP_complex(A, p)\n% function [Y, problem, S] = elliptope_SDP_complex(A, p, Y0)\n%\n% A is a Hermitian matrix of size n.\n%\n% This function uses a local optimization method in Manopt to solve the SDP\n%\n% min_X trace(A*X) s.t. diag(X) = 1, X is complex, positive semidefinite.\n%\n% In practice, the Hermitian matrix X of size n is parameterized as\n% X = Y*Y', where Y has size n x p. By default, p is taken large enough\n% (that is, sqrt(n)) to ensure that there exists an optimal X whose rank is\n% smaller than p. This ensures that the SDP is equivalent to the new\n% problem in Y:\n%\n% min_Y trace(Y'*A*Y) s.t. diag(Y*Y') = 1, Y complex\n%\n% The constraints on Y require each row of Y to have unit norm, which is\n% why Manopt is appropriate software to solve this problem. An optional\n% initial guess can be specified via the input Y0.\n%\n% See the paper below for theory, specifically, for a proof that, for\n% almost all A, second-order critical points of the problem in Y are\n% globally optimal. In other words: there are no local traps in Y, despite\n% non-convexity.\n%\n% Outputs:\n%\n% Y: is the best point found (an nxp matrix with unit norm rows.)\n% To find X, form Y*Y' (or, more efficiently, study X through Y.)\n% \n% problem: is the Manopt problem structure used to produce Y.\n% \n% S: is a dual optimality certificate (a Hermitian matrix of size n,\n% sparse if A is sparse). The optimality gap (in the cost\n% function) is at most n*min(eig(S)), for both Y and X = Y*Y'.\n% Hence, if min(eig(S)) is close to zero, Y is close to globally\n% optimal. This can be computed via eigs(S, 1, 'SR').\n% \n% Paper: https://arxiv.org/abs/1606.04970\n%\n% @inproceedings{boumal2016bmapproach,\n% author = {Boumal, N. and Voroninski, V. and Bandeira, A.S.},\n% title = {The non-convex {B}urer-{M}onteiro approach works on smooth semidefinite programs},\n% booktitle={Neural Information Processing Systems (NIPS 2016)},\n% year = {2016}\n% }\n% \n% See also: maxcut elliptope_SDP\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Oct. 21, 2016\n% Contributors:\n% Change log:\n%\n% Xiaowen Jiang Aug. 20, 2021\n% Added AD to compute the egrad and the ehess\n\n % If no inputs are provided, since this is an example file, generate\n % a random complex matrix. This is for illustration purposes only.\n if ~exist('A', 'var') || isempty(A)\n n = 100;\n A = randn(n) + 1i*randn(n);\n A = (A+A')/sqrt(2*n);\n end\n\n n = size(A, 1);\n assert(n >= 2, 'A must be at least 2x2.');\n assert(size(A, 2) == n, 'A must be square.');\n \n % Force A to be Hermitian\n A = (A+A')/2;\n \n % By default, pick a sufficiently large p (number of columns of Y).\n if ~exist('p', 'var') || isempty(p)\n p = floor(sqrt(n)+1);\n end\n \n assert(p >= 1 && p == round(p), 'p must be an integer >= 1.');\n\n % Pick the manifold of complex n-by-p matrices with unit norm rows.\n manifold = obliquecomplexfactory(p, n, true);\n \n problem.M = manifold;\n \n \n % These three, quick commented lines of code are sufficient to define\n % the cost function and its derivatives. This is good code to write\n % when prototyping. Below, a more advanced use of Manopt is shown,\n % where the redundant computation A*Y is avoided between the gradient\n % and the cost evaluation.\n % % problem.cost = @(Y) .5*sum(sum(real((A*Y).*conj(Y))));\n % % problem.egrad = @(Y) A*Y;\n % % problem.ehess = @(Y, Ydot) A*Ydot;\n \n % Products with A dominate the cost, hence we store the result.\n % This allows to share the results among cost, grad and hess.\n % This is completely optional.\n function store = prepare(Y, store)\n if ~isfield(store, 'AY')\n AY = A*Y;\n store.AY = AY;\n store.diagAYYt = sum(real(AY .* conj(Y)), 2);\n end\n end\n \n % Define the cost function to be /minimized/.\n problem.cost = @cost;\n function [f, store] = cost(Y, store)\n store = prepare(Y, store);\n f = .5*sum(store.diagAYYt);\n end\n\n % Define the Riemannian gradient.\n problem.grad = @grad;\n function [G, store] = grad(Y, store)\n store = prepare(Y, store);\n G = store.AY - bsxfun(@times, Y, store.diagAYYt);\n end\n\n % If you want to, you can specify the Riemannian Hessian as well.\n problem.hess = @hess;\n function [H, store] = hess(Y, Ydot, store)\n store = prepare(Y, store);\n SYdot = A*Ydot - bsxfun(@times, Ydot, store.diagAYYt);\n H = manifold.proj(Y, SYdot);\n end\n\n % An alternative way to compute the egrad and the ehess is to use \n % automatic differentiation provided in the deep learning toolbox\n % (slower). AD does not support complex numbers if the Matlab version\n % is R2021a or earlier. The cost function should be defined differently\n % In this case. See complex_example_AD.m and manoptADhelp.m for more\n % information.\n % problem.cost = @cost_AD;\n % function f = cost_AD(Y)\n % AY = cprod(A, Y);\n % diagAYYt = csum(creal(cdottimes(AY, cconj(Y))), 2);\n % f = .5*csum(diagAYYt);\n % end\n % Call manoptAD to automatically obtain egrad and ehess:\n % problem = manoptAD(problem);\n\n % If the version of Matlab installed is R2021b or later, specify the \n % cost function in the normal way and call manoptAD. \n % problem.cost = @cost_AD;\n % function f = cost_AD(Y)\n % AY = A*Y;\n % diagAYYt = sum(real(AY .* conj(Y)), 2);\n % f = .5*sum(diagAYYt);\n % end\n % problem = manoptAD(problem);\n\n\n % If no initial guess is available, tell Manopt to use a random one.\n if ~exist('Y0', 'var') || isempty(Y0)\n Y0 = [];\n end\n\n % Call your favorite solver.\n opts = struct();\n opts.verbosity = 0; % Set to 0 for no output, 2 for normal output\n opts.maxinner = 500; % maximum Hessian calls per iteration\n opts.tolgradnorm = 1e-6; % tolerance on gradient norm\n Y = trustregions(problem, Y0, opts);\n \n % If required, produce an optimality certificate.\n if nargout >= 3\n S = A - spdiags(sum(real((A*Y).*conj(Y)), 2), 0, n, n);\n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/examples/elliptope_SDP_complex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6454793894809431}} {"text": "function val = peval(x,coef,deg)\n% function val = peval(x,coef,deg)\n%\n% DESCRIPTION\n% Evaluate a polynomial at x.\n%\n% Note: The SUBS function should be used for polynomial evaluations.\n% The PEVAL function has no error checking for speed and it assumes\n% that the polynomial is a row or column vector. It also assumes that\n% the rows of x are ordered to correspond to the columns in the degree\n% matrix deg. \n%\n% INPUTS\n% x: nvars-by-npts matrix each column of which specifies a point\n% at which to evaluate the polynomial.\n% coef: nterms-by-lp coefficient matrix where lp is the length\n% of the polynomial\n% deg: nterms-by-nvars degree matrix\n%\n% OUTPUTS\n% val: lp-by-npts matrix where each column specifies the value of\n% the polynomial evaluated at the corresponding column of x.\n%\n% SYNTAX\n% val = peval(x,coef,deg)\n\n% 6/15/06 PJS Initial Coding\n\n% Compute dimensions\n[nterms,nvars]=size(deg);\nnpts = size(x,2);\nlp = size(coef,2);\ncoef = full(coef);\ndeg = full(deg);\n\n% Compute monomials\nxs = shiftdim(x,-1); % xs is 1-by-nvars-by-npts\nxrep = repmat(xs,[nterms 1 1]); % xrep is nterms-by-nvars-by-npts\ndrep = repmat(deg,[1 1 npts]); % drep is nterms-by-nvars-by-npts\n\n% npow = xrep;\n% idx = find(drep~=1);\n% npow(idx) = xrep(idx).^drep(idx);\n\nnpow = xrep.^drep;\nnmonom = prod(npow,2); % nmonom is nterms-by-1-by-npts\n\n% Evalute polynomial--mulitply by coefs and sum monomials\nnmonomrep = repmat(nmonom,[1 lp 1]); % nmonomrep is nterms-by-lp-by-npts\ncoefrep = repmat(coef,[1 1 npts]); % coefrep is nterms-by-lp-by-npts\nval = sum(coefrep.*nmonomrep,1); % val is 1-by-lp-by-npts\n\n% Reshape val from 1-by-lp-by-npts to lp-by-npts\nif npts==1\n val = val(:);\nelseif lp==1\n val = val(:)';\nelse\n val = squeeze(val);\nend\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SOSTOOLS.300/SOSTOOLS.300/multipoly/peval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6454793809920377}} {"text": "function [ n_data, n, x, fx ] = p_polynomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% P_POLYNOMIAL_VALUES returns values of the Legendre polynomials P(n,x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the order of the function.\n%\n% Output, real X, the point where the function is evaluated.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 22;\n\n fx_vec = [ ...\n 0.1000000000000000E+01, ...\n 0.2500000000000000E+00, ...\n -0.4062500000000000E+00, ...\n -0.3359375000000000E+00, ...\n 0.1577148437500000E+00, ...\n 0.3397216796875000E+00, ...\n 0.2427673339843750E-01, ...\n -0.2799186706542969E+00, ...\n -0.1524540185928345E+00, ...\n 0.1768244206905365E+00, ...\n 0.2212002165615559E+00, ...\n 0.0000000000000000E+00, ...\n -0.1475000000000000E+00, ...\n -0.2800000000000000E+00, ...\n -0.3825000000000000E+00, ...\n -0.4400000000000000E+00, ...\n -0.4375000000000000E+00, ...\n -0.3600000000000000E+00, ...\n -0.1925000000000000E+00, ...\n 0.8000000000000000E-01, ...\n 0.4725000000000000E+00, ...\n 0.1000000000000000E+01 ];\n\n n_vec = [ ...\n 0, 1, 2, ...\n 3, 4, 5, ...\n 6, 7, 8, ...\n 9, 10, 3, ...\n 3, 3, 3, ...\n 3, 3, 3, ...\n 3, 3, 3, ...\n 3 ];\n\n x_vec = [ ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.00E+00, ...\n 0.10E+00, ...\n 0.20E+00, ...\n 0.30E+00, ...\n 0.40E+00, ...\n 0.50E+00, ...\n 0.60E+00, ...\n 0.70E+00, ...\n 0.80E+00, ...\n 0.90E+00, ...\n 1.00E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n x = 0.0;\n fx = 0.0;\n else\n n = n_vec(n_data);\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/legendre_polynomial/p_polynomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6454793743957635}} {"text": "function xform = find_xform(c, d)\n%Finds the xform that maps from c to d\n%in this case the xform is a simple translation and scaling\n%xform is a [3 x 3] matrix which maps coordinates from c's frame to\n%d's frame. the transformation is applied to homogeneous\n%coordinaes\n\n%convert bounding box to cornners\nxs(:,1) = c([1 2])';\nxs(:,2) = c([3 2])';\nxs(:,3) = c([1 4])';\nxs(:,4) = c([3 4])';\n\nys(:,1) = d([1 2])';\nys(:,2) = d([3 2])';\nys(:,3) = d([1 4])';\nys(:,4) = d([3 4])';\n\nxs(3,:) = 1;\nys(3,:) = 1;\n\nA=ys*pinv(xs);\nA(abs(A)<.000001) = 0;\n\nxform = A;\n\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/util/find_xform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6453988071803554}} {"text": "function [in2] = km22in2(km2)\n% Convert area from square kilometers to square inches.\n% Chad A. Greene 2012\nin2 = km2*1550003100.006;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/km22in2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.645398799741771}} {"text": "function psi = conv(psi1,psi2,varargin)\n% convolution of an SO3Kernel function with a function or a kernel on SO(3)\n%\n% We convolute an SO3Kernel $f$ with another SO3Kernel or an SO3Fun $g$\n% by the convolution\n%\n% $$ (f *_L g)(R) = \\frac1{8\\pi^2} \\int_{SO(3)} f(q) \\cdot g(q^{-1}\\,R) \\, dq $$\n%\n% which in this case is similar to the so caled right sided convolution,\n% see SO3FunHarmonic/conv.\n%\n% The convolution of an SO3Kernel with an S2Kernel or an S2Fun $h$ is\n% defined by\n%\n% $$ (f * h)(\\xi) = \\frac1{8\\pi^2} \\int_{SO(3)} f(q) \\cdot h(q^{-1}\\,\\xi) \\, dq $$.\n% \n%\n% Syntax\n% psi = conv(psi1,psi2)\n% SO3F2 = conv(psi1,SO3F1)\n% sF2 = conv(psi1,sF1)\n% phi2 = conv(psi1,phi1)\n% psi = conv(psi1)\n%\n% Input\n% psi1, psi2 - @SO3Kernel\n% phi1 - @S2Kernel\n% SO3F1 - @SO3Fun\n% sF1 - @S2Fun\n%\n% Output\n% psi - @SO3Kernel\n% SO3F2 - @SO3Fun\n% sF2 - @S2Fun\n% phi2 - @S2Kernel\n%\n% See also\n% SO3FunHarmonic/conv SO3FunRBF/conv S2FunHarmonic/conv S2Kernel/conv\n\nif nargin == 1, psi2 = psi1; end\n\n\n% ------------------- convolution with a SO3Fun -------------------\n% In case psi2 is a SO3Fun, convolute the SO3Fun with the kernel\n% conv is commutative if kernel is included\nif isa(psi2,'SO3Fun')\n psi = conv(psi2,psi1,varargin{:});\n return\nend\n\n\n% ------------------- convolution with a S2Fun -------------------\nif isa(psi2,'S2Fun')\n sF = S2FunHarmonic(psi2);\n L = min(psi1.bandwidth,sF.bandwidth);\n \n fhat = zeros((L+1)^2,1);\n for l = 0:L\n fhat(l^2+1:(l+1)^2) = psi1.A(l+1) * sF.fhat(l^2+1:(l+1)^2) ./ (2*l+1);\n end\n\n if isa(psi2,'S2FunHarmonicSym')\n warning(['There is no symmetry given for the SO3Kernel function. But for convolution the ' ...\n 'right symmetry of the SO3Fun has to be compatible with the symmetry of the S2Fun.'])\n end\n psi = S2FunHarmonic(fhat);\n return\nend\n\n\n% ------------------- convolution with a S2Kernel -------------------\nif isa(psi2,'S2Kernel')\n L = min(psi1.bandwidth,psi2.bandwidth); \n l = (0:L);\n psi = S2Kernel(psi1.A(1:L+1) .* psi2.A(1:L+1) ./ (2*l+1));\n return\nend\n\n\n% ------------------- convolution of SO3Kernels -------------------\nif isnumeric(psi1)\n psi = conv(psi2,psi1,varargin{:});\n return\nend\n\n% extract Legendre coefficients of psi1\nA1 = psi1.A(:);\n\n% extract Legendre coefficients of psi2\nif isnumeric(psi2)\n A2 = psi2(:);\nelse\n A2 = psi2.A(:);\n A2 = A2 ./ (2*(0:length(A2)-1)+1).';\nend\n\n% multiplication in harmonic domain\nL = min(psi1.bandwidth,psi2.bandwidth); \npsi = SO3Kernel(A1(1:L+1) .* A2(1:L+1));\n\n\nend", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/SO3KernelFunctions/@SO3Kernel/conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6453987988118269}} {"text": "function t = bartlett_sample ( m, df, sigma )\n\n%*****************************************************************************80\n%\n%% BARTLETT_SAMPLE samples the Bartlett distribution.\n%\n% Discussion:\n%\n% If the matrix T is sampled from the Bartlett distribution, then \n% the matrix W = T' * T is a sample from the Wishart distribution.\n% \n% This function requires functions from the PDFLIB and RNGLIB libraries.\n%\n% The \"initialize()\" function from RNGLIB must be called before using\n% this function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 July 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Patrick Odell, Alan Feiveson,\n% A numerical procedure to generate a sample covariance matrix,\n% Journal of the American Statistical Association,\n% Volume 61, Number 313, March 1966, pages 199-203.\n%\n% Stanley Sawyer,\n% Wishart Distributions and Inverse-Wishart Sampling,\n% Washington University,\n% 30 April 2007, 12 pages.\n%\n% Parameters:\n%\n% Input, integer M, the order of the matrix.\n%\n% Input, integer DF, the number of degrees of freedom.\n% M <= DF.\n%\n% Input, real SIGMA(M,M), the covariance matrix, which should be \n% a symmetric positive definite matrix.\n%\n% Output, real T(M,M), the sample matrix from the Bartlett distribution.\n%\n if ( df < m )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BARTLETT_SAMPLE - Fatal error!\\n' );\n fprintf ( 1, ' DF = %d < M = %d.\\n', df, m );\n error ( 'BARTLETT_SAMPLE - Fatal error!\\n' );\n end\n%\n% Get the upper triangular Cholesky factor of SIGMA.\n%\n r = chol ( sigma );\n%\n% Sample the unit Bartlett distribution.\n%\n tu = bartlett_unit_sample ( m, df );\n%\n% Construct the matrix.\n%\n t = tu * r;\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/wishart/bartlett_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.64536725146863}} {"text": "function nearest = find_closest1 ( m, nr, r, ns, s )\n\n%*****************************************************************************80\n%\n%% FIND_CLOSEST1 finds the nearest R point to each S point.\n%\n% Discussion:\n%\n% We are given R, a set of NR points in M dimensions.\n%\n% We are given S, a set of NS points in M dimensions.\n%\n% For each S(I) in S, we seek the index J of the point R(J)\n% which is nearest to S(I) over all points in R.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer NR, the number of cell generators.\n%\n% Input, real R(M,NR), the cell generators.\n%\n% Input, integer NS, the number of sample points.\n%\n% Input, real S(M,NS), the points to be checked.\n%\n% Output, integer NEAREST(NS), the index of the nearest cell generators.\n%\n nearest = zeros ( ns, 1 );\n\n for js = 1 : ns\n\n distance = Inf;\n nearest(js) = -1;\n\n for jr = 1 : nr\n\n dist_sq = 0.0;\n for i = 1 : m\n dist_sq = dist_sq + ( r(i,jr) - s(i,js) )^2;\n end\n\n if ( dist_sq < distance )\n distance = dist_sq;\n nearest(js) = jr;\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_nearest/find_closest1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.6452754083487587}} {"text": "function R = fit_rotation(S)\n % FIT_ROTATION find rotation for a given covariance matrix\n %\n % R = fit_rotation(S)\n %\n % Inputs:\n % S n by n covariance matrix\n % Outputs:\n % R n by n rotation matrix closest to S\n %\n\n % svd \n [su,ss,sv]=svd(S);\n R = sv*su';\n % if reflection then flip last column\n if( det(R) < 0 )\n su(:,end) = -su(:,end);\n R = sv*su';\n end\n % should definitely be rotation now\n %assert( det(R) >= 0 );\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/fit_rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6452751067517267}} {"text": "function mbr = mbrot()\n i_list = 1:1024;\n mbr = nan(1024,1024,3);\n for i = i_list(:)'\n for j = i_list(:)'\n \n mbr(i,j,1) = red(i,j);\n mbr(i,j,2) = green(i,j);\n mbr(i,j,3) = blue(i,j);\n end\n end\n \n figure; image(mbr./max(mbr(:)));\n \n function out = red(i, j)\n a = 0;\n b = 0;\n d = 0;\n n = 0;\n while (a*a+(b*b)<4 && n<1024)\n b=2*a*b+(j-1)/5e4+.06;\n a=a*a-d+(i-1)/5e4+.34;\n d = b*b;\n n = n+1;\n end\n out = n/4;\n end\n \n function out = green(i, j)\n out = 4 * red(i, j);\n end\n \n function out = blue(i, j)\n out = 6 * red(i, j);\n end\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/mbrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6452599837217027}} {"text": "function [disp_row, disp_col, scale_ind] = optimize_scores(scores_fs, iterations)\n\n% Maximizes the continuous convolution response (classification scores).\n% Find the size of the output.\n[sz1, sz2, num_scales] = size(scores_fs);\noutput_sz = [sz1 sz2];\n\n% Do the grid search step by finding the maximum in the sampled response\n% for each scale.\nsampled_scores = sample_fs(scores_fs);\n[max_resp_row, max_row] = max(sampled_scores, [], 1);\n[init_max_score, max_col] = max(max_resp_row, [], 2);\nmax_row_perm = permute(max_row, [2 3 1]);\ncol = max_col(:)';\nrow = max_row_perm(sub2ind(size(max_row_perm), col, 1:size(sampled_scores,3)));\n\n% Shift and rescale the coordinate system to [-pi, pi]\ntrans_row = mod(row - 1 + floor((output_sz(1)-1)/2), output_sz(1)) - floor((output_sz(1)-1)/2);\ntrans_col = mod(col - 1 + floor((output_sz(2)-1)/2), output_sz(2)) - floor((output_sz(2)-1)/2);\ninit_pos_y = permute(2*pi * trans_row / output_sz(1), [1 3 2]);\ninit_pos_x = permute(2*pi * trans_col / output_sz(2), [1 3 2]);\n\n% Set the current maximum to the sampled one\nmax_pos_y = init_pos_y;\nmax_pos_x = init_pos_x;\n\n% construct grid\nky = -ceil((output_sz(1) - 1)/2) : floor((output_sz(1) - 1)/2);\nkx = (-ceil((output_sz(2) - 1)/2) : floor((output_sz(2) - 1)/2))';\n\n% pre-compute complex exponential\nexp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\nexp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n\nky2 = ky.*ky;\nkx2 = kx.*kx;\n\niter = 1;\nwhile iter <= iterations\n % Compute gradient\n ky_exp_ky = bsxfun(@times, ky, exp_iky);\n kx_exp_kx = bsxfun(@times, kx, exp_ikx);\n y_resp = mtimesx(exp_iky, scores_fs, 'speed');\n resp_x = mtimesx(scores_fs, exp_ikx, 'speed');\n grad_y = -imag(mtimesx(ky_exp_ky, resp_x, 'speed'));\n grad_x = -imag(mtimesx(y_resp, kx_exp_kx, 'speed'));\n \n % Compute Hessian\n ival = 1i * mtimesx(exp_iky, resp_x, 'speed');\n H_yy = real(-mtimesx(bsxfun(@times, ky2, exp_iky), resp_x, 'speed') + ival);\n H_xx = real(-mtimesx(y_resp, bsxfun(@times, kx2, exp_ikx), 'speed') + ival);\n H_xy = real(-mtimesx(ky_exp_ky, mtimesx(scores_fs, kx_exp_kx, 'speed'), 'speed'));\n det_H = H_yy .* H_xx - H_xy .* H_xy;\n \n % Compute new position using newtons method\n max_pos_y = max_pos_y - (H_xx .* grad_y - H_xy .* grad_x) ./ det_H;\n max_pos_x = max_pos_x - (H_yy .* grad_x - H_xy .* grad_y) ./ det_H;\n \n % Evaluate maximum\n exp_iky = exp(bsxfun(@times, 1i * ky, max_pos_y));\n exp_ikx = exp(bsxfun(@times, 1i * kx, max_pos_x));\n \n iter = iter + 1;\nend\n\n% Evaluate the Fourier series at the estimated locations to find the\n% corresponding scores.\nmax_score = real(mtimesx(mtimesx(exp_iky, scores_fs, 'speed'), exp_ikx, 'speed'));\n\n% check for scales that have not increased in score\nind = max_score < init_max_score;\nmax_score(ind) = init_max_score(ind);\nmax_pos_y(ind) = init_pos_y(ind);\nmax_pos_x(ind) = init_pos_x(ind);\n\n% Find the scale with the maximum response\n[max_scale_response, scale_ind] = max(max_score(:));\n\n% Scale the coordinate system to output_sz\ndisp_row = (mod(max_pos_y(1,1,scale_ind) + pi, 2*pi) - pi) / (2*pi) * output_sz(1);\ndisp_col = (mod(max_pos_x(1,1,scale_ind) + pi, 2*pi) - pi) / (2*pi) * output_sz(2);\nend\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/implementation/localization/optimize_scores.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6452599696957326}} {"text": "% Frequency response 3rd Order Bessel HPF\n% and G array.\n% File: c:\\M_files\\short_updates\\UsingGarray2.m\n% 02/10/07\n% See Word file UsingGarray2.doc for schemtic and equations.\nclear;clc; \n% unit suffixes\nu=1e-6;K=1e3;m=1e-3;u=1e-6;n=1e-9;p=1e-12;\n% component values\nR1=52*K;R2=75*K;R3=287*K;\nC1=1.55*n;C2=C1;C3=C1;\nEin=1; % Unity input for (normalized) transfer function\nN=3; % Number of capacitors = order of circuit\n%\n% Form W, Q, S, and P arrays: \n%\nW=[R2 -R2 0;0 R1 R3-R1;0 0 R3];\nQ=-[1 0 0;1 1 0;1 1 1];S=Ein*[1;1;1];P=diag([C1 C2 C3]);\n%\n% Get A, B, D, & E arrays:\n%\nC=inv(W*P);A=C*Q;B=C*S;\n% D & E \nD=[0 0 0];E=0;\n%\nF=[0 0 R3]; % R3 is the coefficient of both iC1 and iC2 in Vo2 \n% which are derivative terms (iC=dVc/dt, etc.) \nG=F*P;\n%\n% * * * * * * * * * * * * Frequency response * * * * * * * * * * * *\n%\nI=eye(N); % identity matrix\n%\n% Log frequency sweep from BF to BF+ND\n%\nBF=2;ND=2;PD=50;NP=ND*PD+1;Fr=logspace(BF,BF+ND,NP);\nfor i=1:NP\n s=2*pi*Fr(i)*j; % j = sqrt(-1)\n stm=(s*I-A)\\B;\n v2=abs((D+G*A)*stm+E+G*B);Vo(i)=20*log10(v2);\n asym(i)=60*log10(Fr(i)/1000); % +60 dB/decade slope\nend\n%\nh=plot(log10(Fr),Vo,'r',log10(Fr),asym,'k--');\nset(h,'LineWidth',2);\ngrid on;\naxis([2 4 -60 20]);\nylabel('dBV');title('Bessel HPF');\nxlabel('Log Freq(Hz)');\nlegend('Vo','Asymptote');\nfigure(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/2435-shortcut-state-space-circuit-analysis/Matlab_Files/UsingGarray2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6451700354063569}} {"text": "function [month, day, year] = gdate (jdate)\n\n% convert Julian date to Gregorian (calendar) date\n \n% input\n\n% jdate = julian day\n\n% output\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% note: day may include fractional part\n\n% Celestial Computing with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\njd = jdate;\n\nz = fix(jd + .5);\nfday = jd + .5 - z;\n\nif (fday < 0)\n fday = fday + 1;\n z = z - 1;\nend\n\nif (z < 2299161)\n a = z;\nelse\n alpha = floor((z - 1867216.25) / 36524.25);\n a = z + 1 + alpha - floor(alpha / 4);\nend\n \nb = a + 1524;\nc = fix((b - 122.1) / 365.25);\nd = fix(365.25 * c);\ne = fix((b - d) / 30.6001);\nday = b - d - fix(30.6001 * e) + fday;\n \nif (e < 14)\n month = e - 1;\nelse\n month = e - 13;\nend\n \nif (month > 2)\n year = c - 4716;\nelse\n year = c - 4715;\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43173-a-matlab-script-for-predicting-orbital-events-of-the-planets/gdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6451414841748532}} {"text": "classdef DCF < dagnn.ElementWise\n%DCF layer\n% Discriminant Correlation Filters(DCF)\n%\n% QiangWang, 2016\n% -------------------------------------------------------------------------------------------------------------------------\n properties\n win_size = [3,3];\n sigma = 1;\n end\n properties (Transient)\n yf = [];\n lambda = 1e-4;\n end\n methods\n function outputs = forward(obj, inputs, params)\n \n xf = fft2(inputs{1});% target region\n zf = fft2(inputs{2});% search region\n xf_conj = conj(xf);\n [h,w,c,~] = size(xf);\n hwc = h*w*c;\n \n useGPU = isa(xf, 'gpuArray');\n if isempty(obj.yf)\n obj.initYF(useGPU);\n end\n \n kxxf = sum(xf .* xf_conj, 3) ./ hwc;\n alphaf = bsxfun(@rdivide, obj.yf, (kxxf + obj.lambda));\n kzxf = sum(zf .* xf_conj, 3) ./ hwc;\n outputs{1} = real(ifft2(alphaf .* kzxf));\n end\n \n function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)\n \n dldrf = fft2(derOutputs{1}); \n xf = fft2(inputs{1});% target region\n zf = fft2(inputs{2});% search region\n xf_conj = conj(xf);\n \n [h,w,c,~] = size(xf);\n hwc = h*w*c;\n \n kxxf = sum(xf .* xf_conj, 3) ./ hwc +obj.lambda;\n \n alphaf = bsxfun(@rdivide,obj.yf, kxxf);\n dldz = real(ifft2(bsxfun(@times,dldrf.*conj(alphaf),xf)))/hwc;\n kzxf = sum(zf .* xf_conj, 3) ./ hwc;\n dldx = real(ifft2(bsxfun(@times,conj(dldrf).*alphaf,zf)-...\n 2*bsxfun(@times,xf,real(dldrf.*conj(alphaf.*kzxf)./kxxf))))/hwc;\n \n derInputs{1} = dldx;\n derInputs{2} = dldz;\n derParams = {};\n end\n \n function initYF(obj, useGPU)\n yf_ = single(fft2(gaussian_shaped_labels(obj.sigma, obj.win_size)));\n lambda_ = gather(obj.lambda);\n if useGPU\n obj.yf = gpuArray(yf_);\n obj.lambda = gpuArray(lambda_);\n else\n obj.yf = yf_;\n obj.lambda = lambda_;\n end\n end\n \n function obj = reset(obj)\n obj.yf = [] ;\n obj.lambda = 1e-4;\n end\n \n function obj = DCF(varargin)\n obj.load(varargin);\n obj.win_size = obj.win_size;\n obj.sigma = obj.sigma ;\n end \n end\nend\n\nfunction labels = gaussian_shaped_labels(sigma, sz)%kcf\n[rs, cs] = ndgrid((1:sz(1)) - floor(sz(1)/2), (1:sz(2)) - floor(sz(2)/2));\nlabels = exp(-0.5 / sigma^2 * (rs.^2 + cs.^2));\nlabels = circshift(labels, -floor(sz(1:2) / 2) + 1);\nassert(labels(1,1) == 1)\nend", "meta": {"author": "foolwood", "repo": "DCFNet", "sha": "97d2cd784d9c2b1083c1249a2aef914062fb5910", "save_path": "github-repos/MATLAB/foolwood-DCFNet", "path": "github-repos/MATLAB/foolwood-DCFNet/DCFNet-97d2cd784d9c2b1083c1249a2aef914062fb5910/training/+dagnn/DCF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6451064676140799}} {"text": "function [X1, Y1] = Direction2CubeMap(D, r, c)\n%\n% [X1, Y1] = Direction2CubeMap(D, r, c)\n%\n%\n% Input:\n% -D: 3D directions of the img format\n% Output:\n% -X1: X coordinates in the CubeMap format\n% -Y1: Y coordinates in the CubeMap format\n%\n% Copyright (C) 2011 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\n[rD, cD, ~] = size(D);\n\nX1 = zeros(rD, cD);\nY1 = zeros(rD, cD);\ntotD = rD * cD;\n\nface_cm = round((r / 4 + c / 3) / 2);\n\n%Calculating faces' directions\nMul = [1, 1, 1, -1, -1, -1];\n\nT = [2, 1, 3, 2, 1, 3]; \nA = [1, 3, 1, 1, 3, 1]; \nB = [3, 2, 2, 3, 2, 2];\n\nX1_1 = [1.5,2.5, 1.5, 1.5, 0.5, 1.5];\nX1_2 = [0.5,0.5, 0.5,-0.5, 0.5,-0.5];\nY1_1 = [2.5,1.5, 3.5, 0.5, 1.5, 1.5];\nY1_2 = [0.5,0.5,-0.5, 0.5,-0.5,-0.5];\n\nfor i=1:6\n indx = find( (Mul(i) * D(:,:,T(i)) > 0)&...\n (Mul(i) * D(:,:,T(i)) >= abs(D(:,:,A(i))))&...\n (Mul(i) * D(:,:,T(i)) >= abs(D(:,:,B(i)))));\n \n indx_shifted = indx + (T(i) - 1) * totD;\n \n X1(indx) = X1_1(i) + X1_2(i) * D(indx + (A(i) - 1) * totD) ./ D(indx_shifted);\n Y1(indx) = Y1_1(i) + Y1_2(i) * D(indx + (B(i) - 1) * totD) ./ D(indx_shifted);\nend\n\nX1 = RemoveSpecials(X1) * face_cm;\nY1 = flipud(RemoveSpecials(Y1) * face_cm);\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/EnvironmentMaps/Direction2CubeMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6451064656647608}} {"text": "function value = mean(SO3F, varargin)\n% Calculates the mean value of a SO3Fun or calculates the mean\n% along a specified dimension of a vector-valued SO3Fun\n%\n% Syntax\n% value = mean(SO3F)\n% SO3F = mean(SO3F, d)\n%\n% Input\n% SO3F - @SO3Fun\n% d - dimension to take the mean value over\n%\n% Output\n% SO3F - @SO3Fun\n% value - double\n%\n% Description\n%\n% If SO3F is a 3x3 SO3Fun then \n% |mean(SO3F)| returns a 3x3 matrix with the mean values of each function \n% |mean(SO3F, 1)| returns a 1x3 SO3Fun which contains the pointwise mean values along the first dimension\n%\n% Example \n% %generate SO3Funs\n% SO3F1 = SO3Fun.dubna\n% SO3F2 = SO3FunHandle(@(rot) SO3F1.eval(rot))\n% A = ones(2,3);\n% SO3F3 = SO3F2.*A\n% \n% %calculate mean values of SO3Funs\n% mean(SO3F2)\n% mean(SO3F3)\n% mean(SO3F3,2)\n% mean(SO3F3,1)\n%\n\n\n% mean along specific dimension\nif nargin>1 && isnumeric(varargin{1})\n value = SO3FunHandle(@(rot) mean(SO3F.eval(rot),varargin{1}+1),SO3F.SRight,SO3F.SLeft);\n return\nend\n\n% mean value of a SO3Fun\nres = get_option(varargin,'resolution',2.5*degree);\nnodes = equispacedSO3Grid(SO3F.SRight,SO3F.SLeft,'resolution',res);\nvalue = mean(SO3F.eval(nodes(:)));\nvalue = reshape(value,size(SO3F));\nif isalmostreal(value,'componentwise')\n value = real(value);\nend\n\nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/SO3Fun/@SO3Fun/mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6450856571434528}} {"text": "function points3d = mytriangualation(matchedPoints1,matchedPoints2,cam1, cam2)\npoints2d(:,:,1)=matchedPoints1;\npoints2d(:,:,2)=matchedPoints2;\ncam(:,:,1)=cam1;\ncam(:,:,2)=cam2;\nnPoints = size(points2d, 1);\npoints3d = zeros(nPoints, 3, 'like', points2d);\n\nfor i = 1:nPoints\n pairs=squeeze(points2d(i, :, :))';\n A = zeros(4, 4);\n for j = 1:2\n P = cam(:,:,j)';\n A(2*j-1,:)=pairs(j, 1)*P(3,:)-P(1,:);\n A(2*j,:)=pairs(j, 2)*P(3,:)-P(2,:);\n end\n [~,~,V] = svd(A);\n X = V(:, end);\n X = X/X(end);\n points3d(i, :) = X(1:3)';\nend\n\n", "meta": {"author": "yihui-he", "repo": "3D-reconstruction", "sha": "6a5c98d71ab2f5eaf3e1b9c5cbc9b07d9677a57f", "save_path": "github-repos/MATLAB/yihui-he-3D-reconstruction", "path": "github-repos/MATLAB/yihui-he-3D-reconstruction/3D-reconstruction-6a5c98d71ab2f5eaf3e1b9c5cbc9b07d9677a57f/mytriangualation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6450788085555759}} {"text": "function DeltaR=solidTideShift(rStation,rSun,rMoon,Jul1,Jul2,addPermTide)\n%%SOLIDTIDESHIFT Compute the vector offset of a point on the surface of the\n% Earth due to solid Earth tidal effects. These effects can be\n% over 31cm. If a Julian date is given, third-order solid Earth\n% tidal effects will be taken into account. Note that site\n% displacement due to ocean loading, which is not included in\n% the solid Earth tide offset, can also be quite significant,\n% with the IERS Conventions 2010 listing it up to 10cm.\n%\n%INPUTS: rStation A vector from the geocenter to the (non-offset) location\n% of a station on the surface of the Earth in WGS-84 Earth-\n% centered Earth-fixed (ECEF) coordinates in meters. This\n% value is converted into spherical coordinates by this\n% function, and only the angles in spherical coordinates,\n% not the radius, are important for this algorithm.\n% However, since locations on the ground are generally\n% given in WGS-84 ellipsoidal coordinates, the ellipsoidal\n% height of the ground plays a role in the conversion to\n% spherical coordinates. However, variations in the\n% ellipsoidal height provided on the order of 2km result in\n% differences in the output DeltaR on the order of microns,\n% so in practice, one could just set rStation to the\n% Cartesian position corresponding to a particular\n% ellipsoidal latitude and longitude with zero ellipsoidal\n% height. Ideally, however, rStation is the Cartesian\n% location of the land in a mean-tide model (if\n% addPermTide=false), or in a tide-free model if\n% addPermTide=true.\n% rSun A vector from the geocenter to the sun in ITRS\n% coordinates in meters. This can be obtained using the\n% readJPLEphem and GCRS2ITRS functions.\n% rMoon A vector from the geocenter to the moon in ITRS\n% coordinates in meters. This can be obtained using the\n% readJPLEphem and GCRS2ITRS functions.\n% Jul1, Jul2 Two parts of a Julian date given in terrestrial time\n% (TT). The units of the date are days. The full date is\n% the sum of both terms. The date is broken into two\n% parts to provide more bits of precision. It does not\n% matter how the date is split. These parameters must be\n% given for the third-order tidal components to be taken\n% into account.\n% addPermTide The deltaR values are for a conventional tide-free model.\n% If addPermTide is true, then a constant (depending on\n% latitude) permanent tide offset will be added to put the\n% point into a mean-tide model. If this parameter is\n% omitted, the default value is \"false\".\n%\n%OUTPUTS: DeltaR The offset of a point on the surface of the Earth due to\n% solid Earth tides. rStation+DeltaR is the location of the\n% station (point on the ground) at the terrestial time given\n% by Jul1 and Jul2 taking into account solid Earth tides.\n% Note that the addPermTide term must be consistent with the\n% coordinate system of rStation. If rStation already\n% includes the permanent tides (is in a mean-tide model),\n% then addPermTide should be false. Otherwise, addPermTide\n% should be true.\n%\n%The Sun and Moon cause the crust of the Earth to warp and points on the\n%Earth in WGS-84 coordinates to move over time. The formulae for computing\n%tidal shits of the crust are given in Section 7.1 of [1].\n%\n%Section 7.1.1 discusses solid Earth tides. While the second-order\n%corrections are well documneted, the third order corrections can not be\n%implemented directly from the standard. However, the standard specifies\n%FORTRAN routines, whose algorithms do not resemble the work given in the\n%standard. These Fortran routines, have been converted to Matlab and are\n%called for the third-order corrections if Julian dates are given. The\n%converted routines are separate functions at the bottom of this file.\n%\n%Note that third-order model has an implied set of ephemerides built into\n%it that might not be perfectly consistent with whatever model was used to\n%obtain rSun and rMoon.\n%\n%One time component is supposed to be in Julian centuries since J2000.0. As\n%J2000.0 is defined in TDB and the time is given in TT, the TDB2TT function\n%is used. The extra parameters needed for the TDB2TT function are not\n%requested as inputs to this function, since it is assumed that the\n%difference between the tides is too small to matter for the model.\n%\n%To test this function, one can use the same values that are given in the\n%IERS's implementation, DEHANTTIDEINEL.F Those are\n% rStation = [4075578.385;931852.890;4801570.154];\n% rSun=[137859926952.015;54228127881.4350;23509422341.6960];\n% rMoon=[-179996231.920342;-312468450.131567;-169288918.592160];\n% addPermTide=false;\n% [Jul1,Jul2]=Cal2TT(2009,4,13,0,0,0);\n% DeltaR=solidTideShift(rStation,rSun,rMoon,addPermTide,Jul1,Jul2);\n%\n%The value of DeltaR truncated to 9 places should be about\n%DeltaR = 0.0770042035\n% 0.0630405632\n% 0.0551656815\n%\n%REFERENCES:\n%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth\n% Rotation and Reference Systems Service Std. 36, 2010.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The convention for indexing arrays is that 1 refers to a value with\n%respect to lunar parameters and 2 refers to a value with respect to solar\n%parameters.\n\nif(nargin<6||isempty(addPermTide))\n addPermTide=false;\nend\n\n%%%%%%General constants that are used%%%%%%\nRe=Constants.EarthEqRadius;%meters\nGMGMe(1)=Constants.MoonEarthMassRatio;\nGMGMe(2)=Constants.SunEarthMassRatio;\n\n%%%%%%Convert the input parameters into different coordinate systems%%%%%%\n\n%Obtain the spherical coordinates of the station.\npointSpherStation=Cart2Sphere(rStation);\nlambda=pointSpherStation(2);%Geocentric longitude\nphi=pointSpherStation(3);%Geocentric latitude.\nr=pointSpherStation(1);\nrHat=rStation/r;%A unit vector in the direction of the station.\n\n%Get East-North-Up Axes using a local SPHERICAL Earth model. A flattening\n%factor of zero makes the Earth flat.\nuENU=getENUAxes([phi;lambda;0],false,r,0);\nuE=uENU(:,1);%Spherical East unit vector\nuN=uENU(:,2);%Spherical North unit vector.\nuU=uENU(:,3);%Spherical radial *up) unit vector\n\n%Extract the x,y, and z coordinates of the moon.\nXj(1)=rMoon(1);\nYj(1)=rMoon(2);\nZj(1)=rMoon(3);\n%Obtain the spherical coordinates of the moon.\npointSpherMoon=Cart2Sphere(rMoon);\nLambdaj(1)=pointSpherMoon(2);\nPhij(1)=pointSpherMoon(3);\nRj(1)=pointSpherMoon(1);\nRjHat(:,1)=rMoon/Rj(1);%A unit vector in the direction of the moon.\n\n%Extract the x,y, and z coordinates of the sun.\nXj(2)=rSun(1);\nYj(2)=rSun(2);\nZj(2)=rSun(3);\n%Obtain the spherical coordinates of the sun.\npointSpherSun=Cart2Sphere(rSun);\nLambdaj(2)=pointSpherSun(2);\nPhij(2)=pointSpherSun(3);\nRj(2)=pointSpherSun(1);\nRjHat(:,2)=rSun/Rj(2);%A unit vector in the direction of the sun.\n\n%%%%%%Determine the solid Earth tidal displacement.%%%%%%\n%This is a three step process. The first two steps are described in the\n%table on page 103 of the 2010 IERS conventions.\n\n%%%Step 1: time-domain contributions\n%%First, the in-phase contribution.\n\n%Determine the second degree nomial Love (h) and Shida (l) numbers using\n%the latitude correction in the second paragraph on page 105.\nh0=0.6078;\nh2=-0.0006;\nl0=0.0847;\nl2=0.0002;\n\nh2=h0+h2*(3*sin(phi)^2-1)/2;\nl2=l0+l2*(3*sin(phi)^2-1)/2;\n\n%Equation 7.5 for the degree 2 tidal offset\nDeltaR=0;\nfor n=1:2\n RjHatDotrHat=dot(RjHat(:,n),rHat);\n DeltaR=DeltaR+GMGMe(n)*(Re^4/Rj(n)^3)*(h2*rHat*(3*RjHatDotrHat^2-1)/2+3*l2*RjHatDotrHat*(RjHat(:,n)-RjHatDotrHat*rHat));\nend\n\n%Equation 7.6 for the degree 3 tidal offset\nh3=0.292;\nl3=0.015;\nfor n=1:2\n RjHatDotrHat=dot(RjHat(:,n),rHat);\n DeltaR=DeltaR+GMGMe(n)*(Re^5/Rj(n)^4)*(h3*rHat*((5/2)*RjHatDotrHat^3-(3/2)*RjHatDotrHat)+l3*((15/2)*RjHatDotrHat^2-3/2)*(RjHat(:,n)-RjHatDotrHat*rHat));\nend\n\n%Equation 7.8 for the diurnal latitude dependence of the Love numbers.\nl1Diurn=0.0012;\ndeltaT=0;\nfor n=1:2\n P12Cos=3*Xj(n)*Zj(n)/Rj(n)^2;%Equation 7.7b\n P12Sin=3*Yj(n)*Zj(n)/Rj(n)^2;%Equation 7.7b\n \n %This is a term in the sum of Equation 7.8. However, it does not look\n %like Equation 7.8, since angle difference formulae had to be used to\n %get terms suitable for the values in Equation 7.7b to be used.\n %Specifically,\n %sin(lambda-Lambdaj(n))=sin(lambda)*cos(Lambdaj(n))-cos(lambda)*sin(Lambdaj(n));\n %cos(lambda-Lambdaj(n))=cos(lambda)*cos(Lambdaj(n))+sin(lambda)*sin(Lambdaj(n));\n deltaT=deltaT+GMGMe(n)*(Re^4/Rj(n)^3)*(uN*sin(phi)*(cos(lambda)*P12Cos+sin(lambda)*P12Sin)-uE*cos(2*phi)*(sin(lambda)*P12Cos-cos(lambda)*P12Sin));\nend\ndeltaT=-l1Diurn*sin(phi)*deltaT;\n\nDeltaR=DeltaR+deltaT;\n\n%Equation 7.9 for the semi-diurnal latitude dependence of the Love numbers.\nl1SemiDiurn=0.0024;\ndeltaT=0;\nfor n=1:2\n P22Cos=(3/Rj(n)^2)*(Xj(n)^2-Yj(n)^2);%Equation 7.7c\n P22Sin=(6/Rj(n)^2)*Xj(n)*Yj(n);%Equation 7.7c\n \n %This is a term in the sum of Equation 7.9. However, it does not look\n %like Equation 7.9, since angle difference formulae had to be used to\n %get terms suitable for the values in Equation 7.7c to be used.\n %Specifically,\n %sin(2*(lambda-Lambdaj(n)))=sin(2*lambda)*cos(2*Lambdaj(n))-cos(2*lambda)*sin(2*Lambdaj(n));\n %cos(2*(lambda-Lambdaj(n)))=cos(2*lambda)*cos(2*Lambdaj(n))+sin(2*lambda)*sin(2*Lambdaj(n));\n deltaT=deltaT+GMGMe(n)*(Re^4/Rj(n)^3)*(uN*(cos(2*lambda)*P22Cos+sin(2*lambda)*P22Sin)+uE*sin(phi)*(sin(2*lambda)*P22Cos-cos(2*lambda)*P22Sin));\nend\ndeltaT=-(1/2)*l1SemiDiurn*sin(phi)*cos(phi)*deltaT;\n\nDeltaR=DeltaR+deltaT;\n\n%%Next, the out-of-phase contributions for the second degree terms\n\n%First, the diurnal tides in Equations 7.10a and 7.10b\nhIDiurn=-0.0025;\nlIDirun=-0.0007;\n\ndeltaR=0;\ndeltaT=0;\nfor n=1:2\n deltaR=deltaR+GMGMe(n)*(Re^4/Rj(n)^3)*sin(2*Phij(n))*sin(2*phi)*sin(lambda-Lambdaj(n));\n deltaT=deltaT+GMGMe(n)*(Re^4/Rj(n)^3)*sin(2*Phij(n))*(cos(2*phi)*sin(lambda-Lambdaj(n))*uN+sin(phi)*cos(lambda-Lambdaj(n))*uE);\nend\ndeltaR=-(3/4)*hIDiurn*deltaR;\ndeltaT=-(3/2)*lIDirun*deltaT;\n\nDeltaR=DeltaR+deltaR*uU+deltaT;\n\n%Next, the semidiurnal tides in Equations 7.11a and 7.11b.\nhISemiDiurn=-0.0022;\nlISemiDiurn=-0.0007;\n\ndeltaR=0;\ndeltaT=0;\nfor n=1:2\n deltaR=deltaR+GMGMe(n)*(Re^4/Rj(n)^3)*cos(Phij(n))^2*cos(phi)^2*sin(2*(lambda-Lambdaj(n)));\n deltaT=deltaT+GMGMe(n)*(Re^4/Rj(n)^3)*cos(Phij(n))^2*(sin(2*phi)*sin(2*(lambda-Lambdaj(n)))*uN-2*cos(phi)*cos(2*(lambda-Lambdaj(n)))*uE);\nend\ndeltaR=-(3/4)*hISemiDiurn*deltaR;\ndeltaT=(3/4)*lISemiDiurn*deltaT;\n\nDeltaR=DeltaR+deltaR*uU+deltaT;\n\n%%%Step 2: frequency-domain contributions\n\n%Only apply the corrections if a Julian date has been provided.\nif(nargin>4)\n %%First, the contributions for the diurnal band \n %Convert Terrestrial Time to Julian centuries since J2000.0. A Julian\n %century is defined to have 36525 days in it. The offset of 2451545.0\n %days is the Julian date at J2000.0 in TDB. In TT, a difference of a\n %few milliseconds exists.\n [TDB1,TDB2]=TT2TDB(Jul1,Jul2);\n T=((TDB1-2451545.0)+TDB2)/36525;\n\n %Convert the Julian date to UTC and determine the fractional number\n %of hours passed in the day assuming precisely 24 hours in a say.\n [Jul1,Jul2]=TT2UTC(Jul1,Jul2);\n [~,~,~,dayFrac]=UTC2Cal(Jul1,Jul2,true);\n FHR=24*dayFrac;\n\n DeltaR=DeltaR+diurBandCorr(rStation,FHR,T);\n\n %%Next, the contributions from the long-period band\n DeltaR=DeltaR+longBandCorr(rStation,T);\nend\n\nif(addPermTide~=false)\n P2=(3*sin(phi)^2-1)/2;\n %Equation 7.14a in the IERS conventions\n deltaR=(-0.1206+0.0001*P2)*P2;\n %Equation 7.14b in the IERS conventions\n deltaT=(-0.0252-0.0001*P2)*sin(2*phi);\n DeltaR=DeltaR+deltaR*uU+deltaT*uN;\nend\nend\n\n\nfunction XCORSTA=diurBandCorr(XSTA,FHR,T)\n%%DIURBANDCORR This subroutine is a Matlab translation of the subroutine\n% STEP2DIU that is provided by the IERS at\n% ftp://tai.bipm.org/iers/convupdt/chapter7/\n% The algorithm is not fully documented by the IERS 2010\n% conventions. For example, most of the constants are not\n% listed anywhere in the documentation.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%\n%SUBROUTINE STEP2DIU (XSTA,FHR,T,XCORSTA) \n%\n% - - - - - - - - - - -\n% S T E P 2 D I U\n% - - - - - - - - - - -\n%\n% This routine is part of the International Earth Rotation and\n% Reference Systems Service (IERS) Conventions software collection.\n%\n% This subroutine gives the in-phase and out-of-phase corrections\n% induced by mantle anelasticity in the diurnal band. \n%\n% In general, Class 1, 2, and 3 models represent physical effects that\n% act on geodetic parameters while canonical models provide lower-level\n% representations or basic computations that are used by Class 1, 2, or\n% 3 models.\n% \n% Status: Class 1\n%\n% Class 1 models are those recommended to be used a priori in the\n% reduction of raw space geodetic data in order to determine\n% geodetic parameter estimates.\n% Class 2 models are those that eliminate an observational\n% singularity and are purely conventional in nature.\n% Class 3 models are those that are not required as either Class\n% 1 or 2.\n% Canonical models are accepted as is and cannot be classified as a\n% Class 1, 2, or 3 model.\n%\n% Given:\n% XSTA d(3) Geocentric position of the IGS station (Note 1)\n% FHR d Fractional hours in the day (Note 2)\n% T d Centuries since J2000\n%\n% Returned:\n% XCORSTA d(3) In phase and out of phase station corrections\n% for diurnal band (Note 4)\n%\n% Notes:\n%\n% 1) The IGS station is in ITRF co-rotating frame. All coordinates are\n% expressed in meters. \n% \n% 2) The fractional hours in the day is computed as the hour + minutes/60.0\n% + sec/3600.0. The unit is expressed in Universal Time (UT).\n%\n% 4) All coordinates are expressed in meters.\n%\n% Test case:\n% given input: XSTA(1) = 4075578.385D0 meters\n% XSTA(2) = 931852.890D0 meters\n% XSTA(3) = 4801570.154D0 meters \n% FHR = 0.00D0 hours\n% T = 0.1059411362080767D0 Julian centuries\n% \n% expected output: XCORSTA(1) = 0.4193085327321284701D-02 meters\n% XCORSTA(2) = 0.1456681241014607395D-02 meters\n% XCORSTA(3) = 0.5123366597450316508D-02 meters\n%\n% References:\n%\n% Mathews, P. M., Dehant, V., and Gipson, J. M., 1997, ''Tidal station\n% displacements,\" J. Geophys. Res., 102(B9), pp. 20,469-20,477\n%\n% Petit, G. and Luzum, B. (eds.), IERS Conventions (2010),\n% IERS Technical Note No. 36, BKG (2010)\n%\n% Revisions:\n% 1996 March 23 V. Dehant Original code\n% 2009 July 31 B.E. Stetzler Initial standardization of code \n% 2009 August 06 B.E. Stetzler Provided a test case\n% 2009 August 06 B.E. Stetzler Capitalized all variables for \n% Fortran 77 compatibility\n% 2010 October 20 B.E. Stetzler Input T corrected to be number of\n% centuries since J2000\n%-----------------------------------------------------------------------\n \n D2PI = 6.283185307179586476925287;\n \n DATDI=[-3, 0, 2, 0, 0, -0.01, 0, 0, 0;\n -3, 2, 0, 0, 0, -0.01, 0, 0, 0;\n -2, 0, 1, -1, 0, -0.02, 0, 0, 0;\n -2, 0, 1, 0, 0, -0.08, 0, -0.01, 0.01;\n -2, 2, -1, 0, 0, -0.02, 0, 0, 0;\n -1, 0, 0, -1, 0, -0.10, 0, 0, 0;\n -1, 0, 0, 0, 0, -0.51, 0, -0.02, 0.03;\n -1, 2, 0, 0, 0, 0.01, 0, 0, 0;\n 0, -2, 1, 0, 0, 0.01, 0, 0, 0;\n 0, 0, -1, 0, 0, 0.02, 0, 0, 0;\n 0, 0, 1, 0, 0, 0.06, 0, 0, 0;\n 0, 0, 1, 1, 0, 0.01, 0, 0, 0;\n 0, 2, -1, 0, 0, 0.01, 0, 0, 0;\n 1, -3, 0, 0, 1, -0.06, 0, 0, 0;\n 1, -2, 0, -1, 0, 0.01, 0, 0, 0;\n 1, -2, 0, 0, 0, -1.23, -0.07, 0.06, 0.01;\n 1, -1, 0, 0, -1, 0.02, 0, 0, 0;\n 1, -1, 0, 0, 1, 0.04, 0, 0, 0;\n 1, 0, 0, -1, 0, -0.22, 0.01, 0.01, 0;\n 1, 0, 0, 0, 0, 12.00, -0.80, -0.67, -0.03;\n 1, 0, 0, 1, 0, 1.73, -0.12, -0.10, 0;\n 1, 0, 0, 2, 0, -0.04, 0, 0, 0;\n 1, 1, 0, 0, -1, -0.50, -0.01, 0.03, 0;\n 1, 1, 0, 0, 1, 0.01, 0, 0, 0;\n 0, 1, 0, 1, -1, -0.01, 0, 0, 0;\n 1, 2, -2, 0, 0, -0.01, 0, 0, 0;\n 1, 2, 0, 0, 0, -0.11, 0.01, 0.01, 0;\n 2, -2, 1, 0, 0, -0.01, 0, 0, 0;\n 2, 0, -1, 0, 0, -0.02, 0, 0, 0;\n 3, 0, 0, 0, 0, 0, 0, 0, 0;\n 3, 0, 0, 1, 0, 0, 0, 0, 0];\n \n DEG2RAD = D2PI/360;\n\n% Compute the phase angles in degrees.\n S = 218.31664563+(481267.88194+(-0.0014663889+(0.00000185139)*T)*T)*T;\n\n TAU = FHR*15+280.4606184+(36000.7700536+(0.00038793+(-0.0000000258)*T)*T)*T+(-S);\n\n PR = (1.396971278+(0.000308889+(0.000000021+(0.000000007)*T)*T)*T)*T;\n\n S = S + PR;\n\n H = 280.46645+(36000.7697489+(0.00030322222+(0.000000020+(-0.00000000654)*T)*T)*T)*T;\n\n P = 83.35324312+(4069.01363525+(-0.01032172222+(-0.0000124991+(0.00000005263)*T)*T)*T)*T;\n\n ZNS = 234.95544499+(1934.13626197+(-0.00207561111+(-0.00000213944+(0.00000001650)*T)*T)*T)*T;\n\n PS = 282.93734098+(1.71945766667+(0.00045688889+(-0.00000001778+(-0.00000000334)*T)*T)*T)*T;\n\n% Reduce angles to between the range 0 and 360.\n S = mod(S,360);\n TAU = mod(TAU,360);\n H = mod(H,360);\n P = mod(P,360);\n ZNS = mod(ZNS,360);\n PS = mod(PS,360);\n\n RSTA = norm(XSTA); \n SINPHI = XSTA(3)/RSTA;\n COSPHI = norm(XSTA(1:2))/RSTA;\n\n COSLA = XSTA(1)/COSPHI/RSTA;\n SINLA = XSTA(2)/COSPHI/RSTA;\n ZLA = atan2(XSTA(2),XSTA(1));\n \n% Initialize.\n XCORSTA=zeros(3,1);\n\n for J=1:31\n % Convert from degrees to radians.\n THETAF=(TAU+DATDI(J,1)*S+DATDI(J,2)*H+DATDI(J,3)*P+DATDI(J,4)*ZNS+DATDI(J,5)*PS)*DEG2RAD;\n\n DR=DATDI(J,6)*2*SINPHI*COSPHI*sin(THETAF+ZLA)+DATDI(J,7)*2*SINPHI*COSPHI*cos(THETAF+ZLA);\n\n DN=DATDI(J,8)*(COSPHI^2-SINPHI^2)*sin(THETAF+ZLA)+DATDI(J,9)*(COSPHI^2-SINPHI^2)*cos(THETAF+ZLA);\n % DE=DATDI(8,J)*SINPHI*COS(THETAF+ZLA)+\n % Modified 20 June 2007\n\n DE=DATDI(J,8)*SINPHI*cos(THETAF+ZLA)-DATDI(J,9)*SINPHI*sin(THETAF+ZLA);\n\n XCORSTA(1)=XCORSTA(1)+DR*COSLA*COSPHI-DE*SINLA-DN*SINPHI*COSLA;\n XCORSTA(2)=XCORSTA(2)+DR*SINLA*COSPHI+DE*COSLA-DN*SINPHI*SINLA; \n XCORSTA(3)=XCORSTA(3)+DR*SINPHI+DN*COSPHI;\n end\n\n XCORSTA=XCORSTA/1000;\n\n% Finished.\n\n%+----------------------------------------------------------------------\n%\n% Copyright (C) 2008\n% IERS Conventions Center\n%\n% ==================================\n% IERS Conventions Software License\n% ==================================\n%\n% NOTICE TO USER:\n%\n% BY USING THIS SOFTWARE YOU ACCEPT THE FOLLOWING TERMS AND CONDITIONS\n% WHICH APPLY TO ITS USE.\n%\n% 1. The Software is provided by the IERS Conventions Center (\"the\n% Center\").\n%\n% 2. Permission is granted to anyone to use the Software for any\n% purpose, including commercial applications, free of charge,\n% subject to the conditions and restrictions listed below.\n%\n% 3. You (the user) may adapt the Software and its algorithms for your\n% own purposes and you may distribute the resulting \"derived work\"\n% to others, provided that the derived work complies with the\n% following requirements:\n%\n% a) Your work shall be clearly identified so that it cannot be\n% mistaken for IERS Conventions software and that it has been\n% neither distributed by nor endorsed by the Center.\n%\n% b) Your work (including source code) must contain descriptions of\n% how the derived work is based upon and/or differs from the\n% original Software.\n%\n% c) The name(s) of all modified routine(s) that you distribute\n% shall be changed.\n% \n% d) The origin of the IERS Conventions components of your derived\n% work must not be misrepresented; you must not claim that you\n% wrote the original Software.\n%\n% e) The source code must be included for all routine(s) that you\n% distribute. This notice must be reproduced intact in any\n% source distribution. \n%\n% 4. In any published work produced by the user and which includes\n% results achieved by using the Software, you shall acknowledge\n% that the Software was used in obtaining those results.\n%\n% 5. The Software is provided to the user \"as is\" and the Center makes\n% no warranty as to its use or performance. The Center does not\n% and cannot warrant the performance or results which the user may\n% obtain by using the Software. The Center makes no warranties,\n% express or implied, as to non-infringement of third party rights,\n% merchantability, or fitness for any particular purpose. In no\n% event will the Center be liable to the user for any consequential,\n% incidental, or special damages, including any lost profits or lost\n% savings, even if a Center representative has been advised of such\n% damages, or for any claim by any third party.\n%\n% Correspondence concerning IERS Conventions software should be\n% addressed as follows:\n%\n% Gerard Petit\n% Internet email: gpetit[at]bipm.org\n% Postal address: IERS Conventions Center\n% Time, frequency and gravimetry section, BIPM\n% Pavillon de Breteuil\n% 92312 Sevres FRANCE\n%\n% or\n%\n% Brian Luzum\n% Internet email: brian.luzum[at]usno.navy.mil\n% Postal address: IERS Conventions Center\n% Earth Orientation Department\n% 3450 Massachusetts Ave, NW\n% Washington, DC 20392\n%\n%\n%-----------------------------------------------------------------------\nend \n\n\nfunction XCORSTA=longBandCorr(XSTA,T)\n%%DIURBANDCORR This subroutine is a Matlab translation of the subroutine\n% STEP2LON that is provided by the IERS at\n% ftp://tai.bipm.org/iers/convupdt/chapter7/\n% The algorithm is not fully documented by the IERS 2010\n% conventions. For example, most of the constants are not\n% listed anywhere in the documentation.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%\n%SUBROUTINE STEP2LON (XSTA,T,XCORSTA)\n%\n% - - - - - - - - - - -\n% S T E P 2 L O N\n% - - - - - - - - - - -\n%\n% This routine is part of the International Earth Rotation and\n% Reference Systems Service (IERS) Conventions software collection.\n%\n% This subroutine gives the in-phase and out-of-phase corrections\n% induced by mantle anelasticity in the long period band. \n%\n% In general, Class 1, 2, and 3 models represent physical effects that\n% act on geodetic parameters while canonical models provide lower-level\n% representations or basic computations that are used by Class 1, 2, or\n% 3 models.\n% \n% Status: Class 1\n%\n% Class 1 models are those recommended to be used a priori in the\n% reduction of raw space geodetic data in order to determine\n% geodetic parameter estimates.\n% Class 2 models are those that eliminate an observational\n% singularity and are purely conventional in nature.\n% Class 3 models are those that are not required as either Class\n% 1 or 2.\n% Canonical models are accepted as is and cannot be classified as a\n% Class 1, 2, or 3 model.\n%\n% Given:\n% XSTA d(3) Geocentric position of the IGS station (Note 1)\n% T d Centuries since J2000\n%\n% Returned:\n% XCORSTA d(3) In phase and out of phase station corrections\n% for diurnal band (Note 2)\n%\n% Notes:\n%\n% 1) The IGS station is in ITRF co-rotating frame. All coordinates are\n% expressed in meters. \n% \n% 2) All coordinates are expressed in meters.\n%\n% Test case:\n% given input: XSTA(1) = 4075578.385D0 meters\n% XSTA(2) = 931852.890D0 meters\n% XSTA(3) = 4801570.154D0 meters \n% T = 0.1059411362080767D0 Julian centuries\n% \n% expected output: XCORSTA(1) = -0.9780962849562107762D-04 meters\n% XCORSTA(2) = -0.2236349699932734273D-04 meters\n% XCORSTA(3) = 0.3561945821351565926D-03 meters\n%\n% References:\n%\n% Mathews, P. M., Dehant, V., and Gipson, J. M., 1997, ''Tidal station\n% displacements,\" J. Geophys. Res., 102(B9), pp. 20,469-20,477\n%\n% Petit, G. and Luzum, B. (eds.), IERS Conventions (2010),\n% IERS Technical Note No. 36, BKG (2010)\n%\n% Revisions:\n% 1996 March 23 V. Dehant Original code\n% 2009 August 07 B.E. Stetzler Initial standardization of code\n% and found unnecessary variables tau\n% and fhr \n% 2009 August 07 B.E. Stetzler Provided a test case\n% 2009 August 07 B.E. Stetzler Capitalized all variables for \n% Fortran 77 compatibility\n% 2010 October 20 B.E. Stetzler Input T corrected to be number of \n% centuries since J2000\n%-----------------------------------------------------------------------\n\n D2PI = 6.283185307179586476925287;\n\n DATDI=[0, 0, 0, 1, 0, 0.47, 0.23, 0.16, 0.07;\n 0, 2, 0, 0, 0, -0.20,-0.12,-0.11,-0.05;\n 1, 0,-1, 0, 0, -0.11,-0.08,-0.09,-0.04;\n 2, 0, 0, 0, 0, -0.13,-0.11,-0.15,-0.07;\n 2, 0, 0, 1, 0, -0.05,-0.05,-0.06,-0.03];\n\n\n DEG2RAD = D2PI/360;\n\n% Compute the phase angles in degrees.\n S = 218.31664563+(481267.88194+(-0.0014663889+(0.00000185139)*T)*T)*T;\n\n PR = (1.396971278+(0.000308889+(0.000000021+(0.000000007)*T)*T)*T)*T;\n\n S = S + PR;\n\n H = 280.46645+(36000.7697489+(0.00030322222+(0.000000020+(-0.00000000654)*T)*T)*T)*T; \n\n P = 83.35324312+(4069.01363525+(-0.01032172222+(-0.0000124991+(0.00000005263)*T)*T)*T)*T;\n\n ZNS = 234.95544499+(1934.13626197+(-0.00207561111+(-0.00000213944+(0.00000001650)*T)*T)*T)*T;\n\n PS = 282.93734098+(1.71945766667+(0.00045688889+(-0.00000001778+(-0.00000000334)*T)*T)*T)*T;\n\n RSTA=norm(XSTA);\n SINPHI=XSTA(3)/RSTA;\n COSPHI=norm(XSTA(1:2))/RSTA;\n \n COSLA=XSTA(1)/COSPHI/RSTA;\n SINLA=XSTA(2)/COSPHI/RSTA;\n\n% Reduce angles to between the range 0 and 360.\n S = mod(S,360);\n % TAU = DMOD(TAU,360D0)\n H = mod(H,360);\n P = mod(P,360);\n ZNS = mod(ZNS,360);\n PS = mod(PS,360);\n\n DR_TOT = 0;\n DN_TOT = 0;\n\n XCORSTA=zeros(3,1);\n \n for J=1:5\n THETAF=(DATDI(J,1)*S+DATDI(J,2)*H+DATDI(J,3)*P+DATDI(J,4)*ZNS+DATDI(J,5)*PS)*DEG2RAD;\n\n DR=DATDI(J,6)*(3D0*SINPHI^2-1)/2*cos(THETAF)+DATDI(J,8)*(3D0*SINPHI^2-1)/2*sin(THETAF);\n\n DN=DATDI(J,7)*(COSPHI*SINPHI*2)*cos(THETAF)+DATDI(J,9)*(COSPHI*SINPHI*2)*sin(THETAF);\n\n DE = 0;\n DR_TOT = DR_TOT+DR;\n DN_TOT = DN_TOT+DN;\n\n XCORSTA(1)=XCORSTA(1)+DR*COSLA*COSPHI-DE*SINLA-DN*SINPHI*COSLA; \n XCORSTA(2)=XCORSTA(2)+DR*SINLA*COSPHI+DE*COSLA-DN*SINPHI*SINLA;\n XCORSTA(3)=XCORSTA(3)+DR*SINPHI+DN*COSPHI;\n end \n\n XCORSTA=XCORSTA/1000;\n\n% Finished.\n\n%+----------------------------------------------------------------------\n%\n% Copyright (C) 2008\n% IERS Conventions Center\n%\n% ==================================\n% IERS Conventions Software License\n% ==================================\n%\n% NOTICE TO USER:\n%\n% BY USING THIS SOFTWARE YOU ACCEPT THE FOLLOWING TERMS AND CONDITIONS\n% WHICH APPLY TO ITS USE.\n%\n% 1. The Software is provided by the IERS Conventions Center (\"the\n% Center\").\n%\n% 2. Permission is granted to anyone to use the Software for any\n% purpose, including commercial applications, free of charge,\n% subject to the conditions and restrictions listed below.\n%\n% 3. You (the user) may adapt the Software and its algorithms for your\n% own purposes and you may distribute the resulting \"derived work\"\n% to others, provided that the derived work complies with the\n% following requirements:\n%\n% a) Your work shall be clearly identified so that it cannot be\n% mistaken for IERS Conventions software and that it has been\n% neither distributed by nor endorsed by the Center.\n%\n% b) Your work (including source code) must contain descriptions of\n% how the derived work is based upon and/or differs from the\n% original Software.\n%\n% c) The name(s) of all modified routine(s) that you distribute\n% shall be changed.\n% \n% d) The origin of the IERS Conventions components of your derived\n% work must not be misrepresented; you must not claim that you\n% wrote the original Software.\n%\n% e) The source code must be included for all routine(s) that you\n% distribute. This notice must be reproduced intact in any\n% source distribution. \n%\n% 4. In any published work produced by the user and which includes\n% results achieved by using the Software, you shall acknowledge\n% that the Software was used in obtaining those results.\n%\n% 5. The Software is provided to the user \"as is\" and the Center makes\n% no warranty as to its use or performance. The Center does not\n% and cannot warrant the performance or results which the user may\n% obtain by using the Software. The Center makes no warranties,\n% express or implied, as to non-infringement of third party rights,\n% merchantability, or fitness for any particular purpose. In no\n% event will the Center be liable to the user for any consequential,\n% incidental, or special damages, including any lost profits or lost\n% savings, even if a Center representative has been advised of such\n% damages, or for any claim by any third party.\n%\n% Correspondence concerning IERS Conventions software should be\n% addressed as follows:\n%\n% Gerard Petit\n% Internet email: gpetit[at]bipm.org\n% Postal address: IERS Conventions Center\n% Time, frequency and gravimetry section, BIPM\n% Pavillon de Breteuil\n% 92312 Sevres FRANCE\n%\n% or\n%\n% Brian Luzum\n% Internet email: brian.luzum[at]usno.navy.mil\n% Postal address: IERS Conventions Center\n% Earth Orientation Department\n% 3450 Massachusetts Ave, NW\n% Washington, DC 20392\n%\n%\n%-----------------------------------------------------------------------\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Terrain/Tides/solidTideShift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6450788085555759}} {"text": "% edgeNL: Edge detection function based on nonlinear derivatives \n% (elementary demo):\n% This function differientiates the image to estimate the gradient. \n% The principle is based on polarized derivatives to automatically select\n% the best edge localization.\n% The main benefits are\n% - univocal edge localization for synthetic and real images\n% - noise reduction with no regularization: the noise level is weaker than\n% the noise level in the original image\n% - better direction estimation of the gradient\n% - can product a confident edge reference map for synthetic images\n% - extremely efficient on salt noise OR pepper noise (this last case needs \n% a change in the nonlinear derivatives)\n% - still noise reduction with regularized schemes (Canny, Demigny, ..., \n% can also be adapted to the asymetrical filters (Prewitt, Sobel, ...)\n% Drawback\n% - no detection of vertical and horizontal \"white\" thin (1 pixel) lines\n% Rk: this demo only performs edge detection and does not include edge \n% extraction (local maxima) and other steps to obtain a binary\n% edge map.\n% Written by O. Laligant - 2009, University of Burgundy\n% Ref: A Nonlinear Derivative Scheme Applied to Edge Detection, \n% Olivier Laligant, Frederic Truchetet, IEEE Transactions on Pattern \n% Analysis and Machine Intelligence - PAMI , vol. 32, no. 2, \n% pp. 242-257, 2010\nfunction edgeNL()\n\n% ------------- Edge detection on a simple synthetic image ------------- \nIm = example();\nfigure(1), imagesc(Im);\ntitle ('Original image');\n\n\n% edge detection (nonlinear gradient estimate)\n% better localization and direction estimation than the linear scheme\ngI = algoNL(Im);\n\n% For a synthetic object, the edges are localized inside the object shape\nfigure(2), imagesc(gI);\ntitle('Edge detection');\n\n\n% ------------- Additive gaussian white noise ------------------------\n\nImn = imnoise(Im, 'gaussian', 0, 0.01);\nfigure(3), imagesc(Imn);\ntitle ('Noisy image');\n\ngIn = algoNL(Imn);\n\nfigure(4), imagesc(gIn);\ntitle('Edge detection on the noisy image');\n\nend\n% ----------------------------------------------------------------------------\n\n\n\n\n%\n% --------------------------- functions -------------------------------------\n%\n\n\n% ------------- computation of the nonlinear derivatives ------------- \n% polarized derivatives\n% lead to an univocal localization of edges\nfunction [gm, gh, gv] = algoNL(I);\n% for classical regularization schemes, I can be replaced by a regularized\n% version\n% for asymetrical schemes (Prewitt, Sobel, etc), I must be replaced by two\n% regularized versions (the regularization is different on columns and rows)\ndph = thresh0(conv2(I, [0 1 -1], 'same'));\ndnh = -thresh0(-conv2(I, [1 -1 0], 'same'));\ngh = dph+dnh;\ndpv = thresh0(conv2(I, [0; 1; -1], 'same'));\ndnv = -thresh0(-conv2(I, [1; -1; 0], 'same'));\ngv = dpv + dnv;\ngm = sqrt(gh.*gh + gv.*gv);\n\nend\n\n% ------------- threshold -------------\nfunction st = thresh0(s)\n\tst = s.*(sign(s)+1)/2;\nend%function\n\n% ------------- test image -------------\n% an example of image to illustrate the localization of the method\nfunction Im = example()\nIm =[\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 255 255 255 0 0 0 0 0 0 0 255 0 0\n 0 0 255 255 255 0 0 0 0 0 0 255 255 0 0\n 0 0 255 255 255 0 0 0 0 0 255 255 255 0 0\n 0 0 0 0 0 0 0 0 0 255 255 255 255 0 0\n 0 0 0 0 0 0 0 0 255 255 255 255 255 0 0\n 0 0 0 0 0 0 0 255 255 255 255 0 0 0 0\n 0 0 0 0 0 0 255 255 255 255 0 0 0 0 0\n 0 0 0 0 0 255 255 255 255 255 0 0 0 0 0\n 0 0 0 0 255 255 255 0 255 255 0 0 0 0 0\n 0 0 0 255 255 255 0 0 0 255 255 0 0 0 0\n 0 0 255 255 255 255 255 0 255 255 255 255 255 0 0\n 0 0 0 255 255 255 255 255 255 255 255 255 0 0 0\n 0 0 0 0 255 255 255 255 255 255 255 255 255 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n];\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31029-edge-detection-by-nonlinear-derivatives/edgeNL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.645078789868447}} {"text": "function W=twoMatDiag(C1,C2,algorithm)\n%%TWOMATDIAG Given two real or complex Hermitian matrices, the first of\n% which must be positive definite, find a matrix W that\n% diagonalizes both of them. Specifically, W*C1*W'=I and\n% W*C2*W'=a diagonal matrix.\n%\n%INPUTS: C1 An NXN real or complex positive definite Hermitian matrix.\n% C2 An NXN real or complex Hermitian matrix. This matrix does not\n% have to be positive definite.\n% algorithm An optional parameter specifying the algorithm to use. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is passed) Use the\n% singular value decomposition (SVD)-based algorithm given in\n% [1].\n% 1 Use the eigenvalue-based decomposition given in [2]. There is\n% generally not a need to use the algorithmic variant. It is\n% not implemented in the C++/mex version of this function.\n%\n%OUTPUTS: W An NXN matrix such that W*C1*W'=identity matrix and W*C2*W'=a\n% diagonal matrix.\n%\n%Joint diagonalization of a pair of matrices arises in the fusion problem\n%discussed in [1] and [2], among other applications. If both matrices are not\n%positive definite, then the jointMatDiagFrob function can produce the\n%desired W diagonalization matrix.\n%\n%EXAMPLE 1:\n%Here, we diagonalize two real, positive definite matrices:\n% C1=[87, 25, 18, 31;\n% 25, 63, 20, 17;\n% 18, 20, 65, 29;\n% 31, 17, 29, 65];\n% C2=[57, 7, 12, 17;\n% 7, 47, 17, 22;\n% 12, 17, 37, 27;\n% 17, 22, 27, 27];\n% %C1 is positive definite. C2 is positive semi-definite.\n% W=twoMatDiag(C1,C2);\n% offDiagErr1=W*C1*W'-diag(diag(W*C1*W'))\n% offDiagErr2=W*C2*W'-diag(diag(W*C2*W'))\n%One will see that the off-diagonal errors are on the order of 1e-16, which\n%is around what one would expect with finite precision limitiations.\n%\n%EXAMPLE 2:\n%This is the diagonalization of two complex Hermitian matrices, the first\n%of which is positive definite and the second of which has some negative\n%eigenvalues.\n%C1 is positive definite.\n% C1=[ 9+ 0*1i, -65+ 0*1i, -11-153*1i, -91-173*1i;\n% -65+ 0*1i, 83+ 0*1i, 54- 38*1i, 31+ 28*1i;\n% -11+153*1i, 54+ 38*1i, 130+ 0*1i, 16- 47*1i;\n% -91+173*1i, 31- 28*1i, 16+ 47*1i, 22+ 0*1i]+215*eye(4);\n% %C2 has both positive and negative eigenvalues.\n% C2=[-16+ 0*1i, -32- 56*1i, -12-128*1i, 16+114*1i;\n% -32+ 56*1i, 79+ 0*1i, -87- 67*1i, -48+ 51*1i;\n% -12+128*1i, -87+ 67*1i, 76+ 0*1i, -7- 96*1i;\n% 16-114*1i, -48- 51*1i, -7+ 96*1i, -147+ 0*1i];\n% W=twoMatDiag(C1,C2);\n% offDiagErr=W*C1*W'-diag(diag(W*C1*W'))\n% offDiagErr=W*C2*W'-diag(diag(W*C2*W'))\n%One will see that the errors are on the order of 1e-14 or less, which is\n%around what one would expect with finite precision errors.\n%\n%REFERENCES:\n%[1] J. Nygårds, V. Deleskog, and G. Hendeby, \"Safe fusion compared to\n% established distributed fusion methods,\" in IEEE International\n% Conference on Multisensor Fusion and Integration for Intelligent\n% Systems, Baden-Baden, Germany, 19-21 Sep. 2016, pp. 265-271.\n%[2] M. Reinhardt, B. Noack, and U. D. Hanebeck, \"Closed-form optimization\n% of covariance intersection for low-dimensional matrices,\" in \n% Proceedings of the 15th International Conference on Information\n% Fusion, Singapore, 9-12 Jun. 2012, pp. 1891-1896.\n%\n%February 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(algorithm))\n algorithm=0;\nend\n\nswitch(algorithm)\n case 0\n %Use the SVD-based algorithm.\n %Note that C1=U1*D1*U1' for a valid covariance matrix.\n [U1,D1,~]=svd(C1);%Equation 6\n d1=diag(D1);\n\n D1Root=diag(1./sqrt(d1));\n\n temp=U1*D1Root;\n [U2,~,~]=svd(temp'*C2*temp);%Equation 7 in [1].\n\n W=U2'*D1Root*U1';%Equation 8a in [1].\n %Note that W*C1*W'=eye(xDim,xDim);\n case 1\n %Use the eigenvalue-based algorithm.\n [V1,E1]=eig(C1);\n T1=inv(V1*diag(sqrt(diag(E1))));\n C2p=T1*C2*T1';\n [V2p,~]=eig(C2p);\n\n %The transformation matrix in Equation 2 of [2].\n W=V2p'*diag(1./sqrt(diag(E1)))*V1';\n otherwise\n error('Unknown algorithm specified.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Basic_Matrix_Operations/Joint_Matrix_Diagonalization/twoMatDiag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6450524112597691}} {"text": "%% SOBOL_TEST04 tests SOBOL.\n%\nglobal SOBOL_lastq;\nglobal SOBOL_seed;\n\nfprintf ( 1, '\\n' );\nfprintf ( 1, 'SOBOL_TEST04\\n' );\nfprintf ( 1, ' SOBOL returns the next element\\n' );\nfprintf ( 1, ' of a Sobol sequence.\\n' );\nfprintf ( 1, '\\n' );\nfprintf ( 1, ' In this test, we call Sobol repeatedly.\\n' );\n\ndim_max = 4;\n\nfor ( dim_num = 2 : dim_max )\n\n SOBOL_seed = 0;\n seed = 0;\n qs = prime_ge ( dim_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Seed Seed Sobol\\n' );\n fprintf ( 1, ' In Out\\n' );\n fprintf ( 1, '\\n' );\n for ( i = 0 : 110 )\n [ r, seed_out ] = sobol ( dim_num, seed );\n if ( i <= 11 || 95 <= i )\n fprintf ( 1, '%6d %6d ', seed, seed_out );\n for ( j = 1 : dim_num )\n fprintf ( 1, '%10f ', r(j) );\n end\n fprintf ( 1, '\\n' );\n elseif ( i == 12 )\n fprintf ( 1, '......................\\n' );\n end\n seed = seed_out;\n end\n\nend \n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/GA3/Sobol/sobol_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6450072288593903}} {"text": "function [ out ] = proj_box( x,l,u )\n%PROJ_BOX computes the orthogonal projection onto the box {x:l<=x<=u}\n%\n% Usage: \n% out = PROJ_BOX(x,l,u)\n% ===========================================\n% Input:\n% x - point to be projected (vector/matrix)\n% l - lower bound (vector/matrix/scalar)\n% u - upper bound (vector/matrix/scalar)\n% ===========================================\n% Assumptions:\n% l<=u\n% ===========================================\n% Output:\n% out - projection vector\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\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%reading the user x and \nif (nargin < 3)\n error ('usage: proj_box( x,l,u )') ;\nend\n\nif any(any((l > u)))\n error('Set is infeasible') ;\nend\n\nout= min(max(l,x),u) ;\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/proj_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6448641164681556}} {"text": "function vol=surfvolume(node,face,option)\n%\n% vol=surfvolume(node,face,option)\n%\n% calculate the enclosed volume for a closed surface\n%\n% author: Qianqian Fang, \n%\n% input:\n% node: node coordinates\n% face: surface triangle list\n%\n% output:\n% vol: total volume of the enclosed space\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nface=face(:,1:3);\n\ned=surfedge(face);\nif(~isempty(ed))\n error('open surface is detected, you have to close it first, consider meshcheckrepair() with meshfix option');\nend\n\n[no,el]=fillsurf(node,face);\n\nvol=elemvolume(no,el);\nvol=sum(vol);\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/surfvolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6448625507579719}} {"text": "function [ n_data, x, fx ] = i1ml1_values ( n_data )\n\n%*****************************************************************************80\n%\n%% I1ML1_VALUES returns some values of the I1ML1 function.\n%\n% Discussion:\n%\n% The function is defined by:\n%\n% I1ML1(x) = I1(x) - L1(x)\n%\n% I1(x) is the modified Bessel function of the first kind of order 1, \n% L1(x) is the modified Struve function of order 1.\n%\n% The data was reported by McLeod.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Allan McLeod,\n% Algorithm 757, MISCFUN: A software package to compute uncommon\n% special functions,\n% ACM Transactions on Mathematical Software,\n% Volume 22, Number 3, September 1996, pages 288-301.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 20;\n\n fx_vec = [ ...\n 0.97575346155386267134E-03, ...\n 0.77609293280609272733E-02, ...\n 0.59302966404545373770E-01, ...\n 0.20395212276737365307E+00, ...\n 0.33839472293667639038E+00, ...\n 0.48787706726961324579E+00, ...\n 0.59018734196576517506E+00, ...\n 0.62604539530312149476E+00, ...\n 0.63209315274909764698E+00, ...\n 0.63410179313235359215E+00, ...\n 0.63417966797578128188E+00, ...\n 0.63439268632392089434E+00, ...\n 0.63501579073257770690E+00, ...\n 0.63559616677359459337E+00, ...\n 0.63591001826697110312E+00, ...\n 0.63622113181751073643E+00, ...\n 0.63636481702133606597E+00, ...\n 0.63650653499619902120E+00, ...\n 0.63655609126300261851E+00, ...\n 0.63657902087183929223E+00 ];\n\n x_vec = [ ...\n 0.0019531250E+00, ...\n 0.0156250000E+00, ...\n 0.1250000000E+00, ...\n 0.5000000000E+00, ...\n 1.0000000000E+00, ...\n 2.0000000000E+00, ...\n 4.0000000000E+00, ...\n 8.0000000000E+00, ...\n 12.0000000000E+00, ...\n 16.0000000000E+00, ...\n 16.2500000000E+00, ...\n 17.0000000000E+00, ...\n 20.0000000000E+00, ...\n 25.0000000000E+00, ...\n 30.0000000000E+00, ...\n 40.0000000000E+00, ...\n 50.0000000000E+00, ...\n 75.0000000000E+00, ...\n 100.0000000000E+00, ...\n 125.0000000000E+00 ]; \n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/i1ml1_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6448625395422454}} {"text": "function inter = learn_struct_dbn_reveal(seqs, ns, max_fan_in, penalty)\n% LEARN_STRUCT_DBN_REVEAL Learn inter-slice adjacency matrix given fully observable discrete time series\n% inter = learn_struct_dbn_reveal(seqs, node_sizes, max_fan_in, penalty)\n% \n% seqs{l}{i,t} = value of node i in slice t of time-series l.\n% If you have a single time series in an N*T array D, use\n% seqs = { num2cell(D) }.\n% If you have L time series, each of length T, in an N*T*L array D, use\n% seqs= cell(1,L); for l=1:L, seqs{l} = num2cell(D(:,:,l)); end\n% or, in vectorized form,\n% seqs = squeeze(num2cell(num2cell(D),[1 2]));\n% Currently the data is assumed to be discrete (1,2,...)\n%\n% node_sizes(i) is the number of possible values for node i\n% max_fan_in is the largest number of parents we allow per node (default: N)\n% penalty is weight given to the complexity penalty (default: 0.5)\n% A penalty of 0.5 gives the BIC score.\n% A penalty of 0 gives the ML score.\n% Maximizing likelihood is equivalent to maximizing mutual information between parents and child.\n%\n% inter(i,j) = 1 iff node in slice t connects to node j in slice t+1\n%\n% The parent set for each node in slice 2 is computed by evaluating all subsets of nodes in slice 1,\n% and picking the largest scoring one. This takes O(n^k) time per node, where n is the num. nodes\n% per slice, and k <= n is the max fan in.\n% Since all the nodes are observed, we do not need to use an inference engine.\n% And since we are only learning the inter-slice matrix, we do not need to check for cycles.\n%\n% This algorithm is described in\n% - \"REVEAL: A general reverse engineering algorithm for inference of genetic network\n% architectures\", Liang et al. PSB 1998\n% - \"Extended dependency analysis of large systems\",\n% Roger Conant, Intl. J. General Systems, 1988, vol 14, pp 97-141\n% - \"Learning the structure of DBNs\", Friedman, Murphy and Russell, UAI 1998.\n\nn = length(ns);\n\nif nargin < 3, max_fan_in = n; end\nif nargin < 4, penalty = 0.5; end\n\ninter = zeros(n,n);\n\nif ~iscell(seqs)\n data{1} = seqs;\nend\n\nnseq = length(seqs);\nnslices = 0;\ndata = cell(1, nseq);\nfor l=1:nseq\n nslices = nslices + size(seqs{l}, 2);\n data{l} = cell2num(seqs{l})'; % each row is a case\nend\nndata = nslices - nseq; % subtract off the initial slice of each sequence\n\n% We concatenate the sequences as in the following example.\n% Let there be 2 sequences of lengths 4 and 5, with n nodes per slice,\n% and let i be the target node.\n% Then we construct following matrix D \n%\n% s{1}{1,1} ... s{1}{1,3} s{2}{1,1} ... s{2}{1,4}\n% ....\n% s{1}{n,1} ... s{1}{n,3} s{2}{n,1} ... s{2}{n,4}\n% s{1}{i,2} ... s{1}{i,4} s{2}{i,2} ... s{2}{i,5}\n%\n% D(1:n, i) is the i'th input and D(n+1, i) is the i'th output.\n% \n% We concatenate each sequence separately to avoid treating the transition\n% from the end of one sequence to the beginning of another as a \"normal\" transition.\n\n\nfor i=1:n\n D = [];\n for l=1:nseq\n T = size(seqs{l}, 2);\n A = cell2num(seqs{l}(:, 1:T-1));\n B = cell2num(seqs{l}(i, 2:T));\n C = [A;B];\n D = [D C];\n end\n SS = subsets(1:n, max_fan_in, 1); % skip the empty set \n nSS = length(SS);\n bic_score = zeros(1, nSS);\n ll_score = zeros(1, nSS);\n target = n+1;\n ns2 = [ns ns(i)];\n for h=1:nSS\n ps = SS{h};\n dom = [ps target];\n counts = compute_counts(D(dom, :), ns2(dom));\n CPT = mk_stochastic(counts);\n [bic_score(h), ll_score(h)] = bic_score_family(counts, CPT, ndata);\n end\n if penalty == 0\n h = argmax(ll_score);\n else\n h = argmax(bic_score);\n end\n ps = SS{h};\n inter(ps, i) = 1;\nend\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/learning/learn_struct_dbn_reveal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6448625388266224}} {"text": "function [ frames, indexes ] = vec2frames( vec, Nw, Ns, direction, window, padding )\n% VEC2FRAMES Splits signal into overlapped frames using indexing.\n% \n% B=vec2frames(A,M,N) creates a matrix B whose columns consist of \n% segments of length M, taken at every N samples along input vector A.\n%\n% [B,R]=vec2frames(A,M,N,D,W,P) creates a matrix B whose columns \n% or rows, as specified by D, consist of segments of length M, taken \n% at every N samples along the input vector A and windowed using the\n% analysis window specified by W. The division of A into frames is \n% achieved using indexes returned in R as follows: B=A(R);\n%\n% Summary\n%\n% A is an input vector\n%\n% M is a frame length (in samples)\n%\n% N is a frame shift (in samples)\n%\n% D specifies if the frames in B are rows or columns,\n% i.e., D = 'rows' or 'cols', respectively\n%\n% W is an optional analysis window function to be applied to \n% each frame, given as a function handle, e.g., W = @hanning\n% or as a vector of window samples, e.g., W = hanning( M )\n%\n% P specifies if last frame should be padded to full length,\n% or simply discarded, i.e., P = true or false, respectively\n% \n% B is the output matrix of frames\n%\n% R is a matrix of indexes used for framing, such that division \n% of A into frames is achieved as follows: B=A(R);\n%\n% Examples\n%\n% % divide the input vector into seven-sample-long frames with a shift\n% % of three samples and return frames as columns of the output matrix\n% % (note that the last sample of the input vector is discarded)\n% vec2frames( [1:20], 7, 3 )\n%\n% % divide the input vector into seven-sample-long frames with a shift\n% % of three samples and return frames as rows of the output matrix\n% % (note that the last sample of the input vector is discarded)\n% vec2frames( [1:20], 7, 3, 'rows' )\n%\n% % divide the input vector into seven-sample-long frames with a shift\n% % of three samples, pad the last frame with zeros so that no samples\n% % are discarded and return frames as rows of the output matrix\n% vec2frames( [1:20], 7, 3, 'rows', [], true )\n%\n% % divide the input vector into seven-sample-long frames with a shift\n% % of three samples, pad the last frame with white Gaussian noise\n% % of variance (1E-5)^2 so that no samples are discarded and \n% % return frames as rows of the output matrix\n% vec2frames( [1:20], 7, 3, 'rows', false, { 'noise', 1E-5 } )\n%\n% % divide the input vector into seven-sample-long frames with a shift\n% % of three samples, pad the last frame with zeros so that no samples \n% % are discarded, apply the Hanning analysis window to each frame and\n% % return frames as columns of the output matrix\n% vec2frames( [1:20], 7, 3, 'cols', @hanning, 0 )\n% \n% See also FRAMES2VEC, DEMO\n\n% Author: Kamil Wojcicki, UTD, July 2011\n\n\n % usage information\n usage = 'usage: [ frames, indexes ] = vec2frames( vector, frame_length, frame_shift, direction, window, padding );';\n\n % default settings \n switch( nargin )\n case { 0, 1, 2 }, error( usage );\n case 3, padding=false; window=false; direction='cols';\n case 4, padding=false; window=false; \n case 5, padding=false; \n end\n\n % input validation\n if( isempty(vec) || isempty(Nw) || isempty(Ns) ), error( usage ); end;\n if( min(size(vec))~=1 ), error( usage ); end;\n if( Nw==0 || Ns==0 ), error( usage ); end;\n\n vec = vec(:); % ensure column vector\n\n L = length( vec ); % length of the input vector\n M = floor((L-Nw)/Ns+1); % number of frames \n\n\n % perform signal padding to enable exact division of signal samples into frames \n % (note that if padding is disabled, some samples may be discarded)\n if( ~isempty(padding) )\n \n % figure out if the input vector can be divided into frames exactly\n E = (L-((M-1)*Ns+Nw));\n\n % see if padding is actually needed\n if( E>0 ) \n\n % how much padding will be needed to complete the last frame?\n P = Nw-E;\n\n % pad with zeros\n if( islogical(padding) && padding ) \n vec = [ vec; zeros(P,1) ];\n\n % pad with a specific numeric constant\n elseif( isnumeric(padding) && length(padding)==1 ) \n vec = [ vec; padding*ones(P,1) ];\n\n % pad with a low variance white Gaussian noise\n elseif( isstr(padding) && strcmp(padding,'noise') ) \n vec = [ vec; 1E-6*randn(P,1) ];\n\n % pad with a specific variance white Gaussian noise\n elseif( iscell(padding) && strcmp(padding{1},'noise') ) \n if( length(padding)>1 ), scale = padding{2}; \n else, scale = 1E-6; end;\n vec = [ vec; scale*randn(P,1) ];\n\n % if not padding required, decrement frame count\n % (not a very elegant solution)\n else\n M = M-1;\n\n end\n\n % increment the frame count\n M = M+1;\n end\n end\n\n\n % compute index matrix \n switch( direction )\n\n case 'rows' % for frames as rows\n indf = Ns*[ 0:(M-1) ].'; % indexes for frames \n inds = [ 1:Nw ]; % indexes for samples\n indexes = indf(:,ones(1,Nw)) + inds(ones(M,1),:); % combined framing indexes\n \n case 'cols' % for frames as columns\n indf = Ns*[ 0:(M-1) ]; % indexes for frames \n inds = [ 1:Nw ].'; % indexes for samples\n indexes = indf(ones(Nw,1),:) + inds(:,ones(1,M)); % combined framing indexes\n \n otherwise\n error( sprintf('Direction: %s not supported!\\n', direction) ); \n\n end\n\n\n % divide the input signal into frames using indexing\n frames = vec( indexes );\n\n\n % return if custom analysis windowing was not requested\n if( isempty(window) || ( islogical(window) && ~window ) ), return; end;\n \n % if analysis window function handle was specified, generate window samples\n if( isa(window,'function_handle') )\n window = window( Nw );\n end\n \n % make sure analysis window is numeric and of correct length, otherwise return\n if( isnumeric(window) && length(window)==Nw )\n\n % apply analysis windowing beyond the implicit rectangular window function\n switch( direction )\n case 'rows', frames = frames * diag( window );\n case 'cols', frames = diag( window ) * frames;\n end\n\n end\n\n\n% EOF \n", "meta": {"author": "a-nagrani", "repo": "VGGVox", "sha": "53481f018be60541909bcb2ae1c65cdd8ea3c147", "save_path": "github-repos/MATLAB/a-nagrani-VGGVox", "path": "github-repos/MATLAB/a-nagrani-VGGVox/VGGVox-53481f018be60541909bcb2ae1c65cdd8ea3c147/mfcc/vec2frames.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.6448625316378874}} {"text": "function [label, model, L] = mixGaussVb(X, m, prior)\n% Variational Bayesian inference for Gaussian mixture.\n% Input: \n% X: d x n data matrix\n% m: k (1 x 1) or label (1 x n, 1<=label(i)<=k) or model structure\n% Output:\n% label: 1 x n cluster label\n% model: trained model structure\n% L: variational lower bound\n% Reference: Pattern Recognition and Machine Learning by Christopher M. Bishop (P.474)\n% Written by Mo Chen (sth4nth@gmail.com).\nfprintf('Variational Bayesian Gaussian mixture: running ... \\n');\n[d,n] = size(X);\nif nargin < 3\n prior.alpha = 1;\n prior.kappa = 1;\n prior.m = mean(X,2);\n prior.v = d+1;\n prior.M = eye(d); % M = inv(W)\nend\nprior.logW = -2*sum(log(diag(chol(prior.M))));\n\ntol = 1e-8;\nmaxiter = 2000;\nL = -inf(1,maxiter);\nmodel = init(X,m,prior);\nfor iter = 2:maxiter\n model = expect(X,model);\n model = maximize(X,model,prior);\n L(iter) = bound(X,model,prior);\n if abs(L(iter)-L(iter-1)) < tol*abs(L(iter)); break; end\nend\nL = L(2:iter);\nlabel = zeros(1,n);\n[~,label(:)] = max(model.R,[],2);\n[~,~,label(:)] = unique(label);\n\nfunction model = init(X, m, prior)\nn = size(X,2);\nif isstruct(m) % init with a model\n model = m;\nelseif numel(m) == 1 % random init k\n k = m;\n label = ceil(k*rand(1,n));\n model.R = full(sparse(1:n,label,1,n,k,n));\nelseif all(size(m)==[1,n]) % init with labels\n label = m;\n k = max(label);\n model.R = full(sparse(1:n,label,1,n,k,n));\nelse\n error('ERROR: init is not valid.');\nend\nmodel = maximize(X,model,prior);\n\n% Done\nfunction model = maximize(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nm0 = prior.m;\nv0 = prior.v;\nM0 = prior.M;\nR = model.R;\n\nnk = sum(R,1); % 10.51\nalpha = alpha0+nk; % 10.58\nkappa = kappa0+nk; % 10.60\nv = v0+nk; % 10.63\nm = bsxfun(@plus,kappa0*m0,X*R);\nm = bsxfun(@times,m,1./kappa); % 10.61\n\n[d,k] = size(m);\nU = zeros(d,d,k); \nlogW = zeros(1,k);\nr = sqrt(R');\nfor i = 1:k\n Xm = bsxfun(@minus,X,m(:,i));\n Xm = bsxfun(@times,Xm,r(i,:));\n m0m = m0-m(:,i);\n M = M0+Xm*Xm'+kappa0*(m0m*m0m'); % equivalent to 10.62\n U(:,:,i) = chol(M);\n logW(i) = -2*sum(log(diag(U(:,:,i)))); \nend\n\nmodel.alpha = alpha;\nmodel.kappa = kappa;\nmodel.m = m;\nmodel.v = v;\nmodel.U = U;\nmodel.logW = logW;\n\n% Done\nfunction model = expect(X, model)\nalpha = model.alpha; % Dirichlet\nkappa = model.kappa; % Gaussian\nm = model.m; % Gasusian\nv = model.v; % Whishart\nU = model.U; % Whishart \nlogW = model.logW;\nn = size(X,2);\n[d,k] = size(m);\n\nEQ = zeros(n,k);\nfor i = 1:k\n Q = (U(:,:,i)'\\bsxfun(@minus,X,m(:,i)));\n EQ(:,i) = d/kappa(i)+v(i)*dot(Q,Q,1); % 10.64\nend\nElogLambda = sum(psi(0,0.5*bsxfun(@minus,v+1,(1:d)')),1)+d*log(2)+logW; % 10.65\nElogpi = psi(0,alpha)-psi(0,sum(alpha)); % 10.66\nlogRho = -0.5*bsxfun(@minus,EQ,ElogLambda-d*log(2*pi)); % 10.46\nlogRho = bsxfun(@plus,logRho,Elogpi); % 10.46\nlogR = bsxfun(@minus,logRho,logsumexp(logRho,2)); % 10.49\nR = exp(logR);\n\nmodel.logR = logR;\nmodel.R = R;\n\n% Done\nfunction L = bound(X, model, prior)\nalpha0 = prior.alpha;\nkappa0 = prior.kappa;\nv0 = prior.v;\nlogW0 = prior.logW;\nalpha = model.alpha; \nkappa = model.kappa; \nv = model.v; \nlogW = model.logW;\nR = model.R;\nlogR = model.logR;\n[d,n] = size(X);\nk = size(R,2);\n\nEpz = 0;\nEqz = dot(R(:),logR(:));\nlogCalpha0 = gammaln(k*alpha0)-k*gammaln(alpha0);\nEppi = logCalpha0;\nlogCalpha = gammaln(sum(alpha))-sum(gammaln(alpha));\nEqpi = logCalpha;\nEpmu = 0.5*d*k*log(kappa0);\nEqmu = 0.5*d*sum(log(kappa));\nlogB0 = -0.5*v0*(logW0+d*log(2))-logMvGamma(0.5*v0,d);\nEpLambda = k*logB0;\nlogB = -0.5*v.*(logW+d*log(2))-logMvGamma(0.5*v,d);\nEqLambda = sum(logB);\nEpX = -0.5*d*n*log(2*pi);\nL = Epz-Eqz+Eppi-Eqpi+Epmu-Eqmu+EpLambda-EqLambda+EpX;", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter10/mixGaussVb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6448625312800758}} {"text": "function [Q, R] = stiefelgeneralized_retraction_MGS(B, X, U, t)\n% Retraction for generalized Stiefel based on Modified Gram-Schmidt.\n% When used just as a retraction, only the output Q is relevant.\n% NB, Dec. 16, 2018.\n if ~exist('t', 'var') || isempty(t)\n A = X + U; % t = 1 by default\n else\n A = X + t*U;\n end\n [n, p] = size(X);\n Q = zeros(n, p);\n R = zeros(p, p);\n for j = 1 : p\n v = A(:, j);\n R(j, j) = sqrt(v'*B*v);\n Q(:, j) = v / R(j, j);\n R(j, (j+1):p) = Q(:, j)' * B * A(:, (j+1):p);\n A(:, (j+1):p) = A(:, (j+1):p) - Q(:, j) * R(j, (j+1):p);\n end\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/tests/stiefelgeneralized_retraction_MGS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6448592114932329}} {"text": "function [G] = uGal2G(uGal)\n% Convert acceleration from microgals to average acceleration due to \n% Earth's gravity. \n% Chad A. Greene 2012\nG = uGal/(9.80665e+8); \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/uGal2G.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6447400056347373}} {"text": "function [u,Du,eqn,info] = PoissonP3(node,elem,pde,bdFlag,option)\n%% POISSONP2 Poisson equation: P3 quadratic element.\n%\n% u = PoissonP3(node,elem,pde,bdFlag,option) produces the cubic\n% finite element approximation of the Poisson equation\n% \n% -div(d*grad(u))=f in \\Omega, with \n% Dirichlet boundary condition u=g_D on \\Gamma_D, \n% Neumann boundary condition d*grad(u)*n=g_N on \\Gamma_N,\n% Robin boundary condition g_R*u + d*grad(u)*n=g_N on \\Gamma _R\n%\n% [u,Du,eqn,info] = PoissonP3(node,elem,pde,bdFlag,option)\n%\n% The usage is the same as Poisson. For quadratic elements, middle points\n% of each edge are degree of freedom. See dofP2doc for detail.\n% \n% Example\n% femrateP2\n%\n% See also Poisson, Poisson3, Poisson3P2,PoissonP2 \n% Created by Jie Zhou\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\n\ntic;\n%% Construct Data Structure\n[elem2dof,elem2edge,edge,bdDof] = dofP3(elem); \nN = size(node,1); NT = size(elem,1); NE = size(edge,1);\nNdof = N + 2*NE + NT;\n\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix\n% Since Dphi_i*Dphi_j is four degree, so four order numerical quadrature rule is used here\nif ~isfield(pde,'d'), pde.d = []; end\nif ~isfield(option,'quadorder')\n option.quadorder = 5; % default order 2(p-1)+1\nend\n[lambda, w] = quadpts(option.quadorder);\nnQuad = size(lambda,1);\nii = zeros(55*NT,1); jj = zeros(55*NT,1); sA = zeros(55*NT,nQuad);\n% generate sparse pattern\nindex = 0;\nfor i = 1:10\n for j = i:10\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j)); \n index = index + NT;\n end\nend\n% compute non-zeros\nfor p = 1:nQuad\n % Dphi at quadrature points\n Dphip(:,:,1) = (27/2*lambda(p,1)*lambda(p,1)-9*lambda(p,1)+1).*Dlambda(:,:,1); \n Dphip(:,:,2) = (27/2*lambda(p,2)*lambda(p,2)-9*lambda(p,2)+1).*Dlambda(:,:,2); \n Dphip(:,:,3) = (27/2*lambda(p,3)*lambda(p,3)-9*lambda(p,3)+1).*Dlambda(:,:,3);\n Dphip(:,:,4) = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphip(:,:,5) = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphip(:,:,6) = 9/2*((3*lambda(p,3)*lambda(p,3)-lambda(p,3)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,3)-1).*Dlambda(:,:,3)); \n Dphip(:,:,7) = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,3)+...\n lambda(p,3)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphip(:,:,8) = 9/2*((3*lambda(p,1)*lambda(p,1)-lambda(p,1)).*Dlambda(:,:,2)+...\n lambda(p,2)*(6*lambda(p,1)-1).*Dlambda(:,:,1)); \n Dphip(:,:,9) = 9/2*((3*lambda(p,2)*lambda(p,2)-lambda(p,2)).*Dlambda(:,:,1)+...\n lambda(p,1)*(6*lambda(p,2)-1).*Dlambda(:,:,2)); \n Dphip(:,:,10) = 27*(lambda(p,1)*lambda(p,2)*Dlambda(:,:,3)+lambda(p,1)*lambda(p,3)*Dlambda(:,:,2)+...\n lambda(p,3)*lambda(p,2)*Dlambda(:,:,1)); \n index = 0;\n for i = 1:10\n for j = i:10\n Aij = 0;\n if isempty(pde.d) || isnumeric(pde.d)\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2);\n else\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2).*pde.d(pxy);\n end\n if ~isempty(pde.d) && isnumeric(pde.d) % d is piecewise constant\n Aij = pde.d.*Aij;\n end\n Aij = Aij.*area;\n sA(index+1:index+NT,p) = Aij;\n index = index + NT;\n end\n end\nend\nsA = sum(sA,2);\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nA = A + AU + AU';\nclear Aij ii jj sA\n\n%% Assemble right hand side by high order quadrature rule\nb = zeros(Ndof,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 6; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isempty(pde.f) \n % quadrature points in the barycentric coordinate\n [lambda,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n phi(:,1) = 0.5*(3*lambda(:,1)-1).*(3*lambda(:,1)-2).*lambda(:,1); \n phi(:,2) = 0.5*(3*lambda(:,2)-1).*(3*lambda(:,2)-2).*lambda(:,2); \n phi(:,3) = 0.5*(3*lambda(:,3)-1).*(3*lambda(:,3)-2).*lambda(:,3);\n phi(:,4) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,5) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,3)-1); \n phi(:,6) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,3)-1); \n phi(:,7) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,1)-1); \n phi(:,8) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,1)-1);\n phi(:,9) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,10) = 27*lambda(:,1).*lambda(:,2).*lambda(:,3); \n \n bt = zeros(NT,10);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n if isfield(pde,'f') && isnumeric(pde.f)\n fp = pde.f; % piecewise constant \n else\n fp = pde.f(pxy); % function handle\n end\n for j = 1:10\n bt(:,j) = bt(:,j) + w(p)*phi(p,j)*fp;\n end\n end\n bt = bt.*repmat(area,1,10);\n b = accumarray(elem2dof(:),bt(:),[Ndof 1]); \nend\n\n%% Boundary Conditions\nif nargin<=3, bdFlag = []; end\n[AD,b,u,freeDof,isPureNeumann] = getbdP3(b);\n\n\n%% Record assembeling time\nassembleTime = toc;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(freeDof), return; end\n% Set up solver\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 2e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % Multigrid-type solver for large size systems\n option.solver = 'mg';\n end\nend\n\nsolver = option.solver;\n% solve\nswitch solver\n case 'direct'\n tic;\n u(freeDof) = AD(freeDof,freeDof)\\b(freeDof);\n residual = norm(b - AD*u);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual);\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n case 'mg'\n option.x0 = u;\n option.solver = 'CG';\n option.tol = Ndof^(-2);\n [u,info] = mg(AD,b,elem,option,edge);\n case 'amg'\n option.solver = 'CG';\n option.tol = Ndof^(-2);\n [u(freeDof),info] = amg(AD(freeDof,freeDof),b(freeDof),option); \nend\nclear phi lambda\n% post-process for pure Neumann problem\nif isPureNeumann\n intguh = double(sparse(NT,1)); \n [lambda,w] = quadpts(3); %This is P3 element.\n nQuad = size(lambda,1);\n phi(:,1) = 0.5*(3*lambda(:,1)-1).*(3*lambda(:,1)-2).*lambda(:,1); \n phi(:,2) = 0.5*(3*lambda(:,2)-1).*(3*lambda(:,2)-2).*lambda(:,2); \n phi(:,3) = 0.5*(3*lambda(:,3)-1).*(3*lambda(:,3)-2).*lambda(:,3);\n phi(:,4) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,5) = 9/2*lambda(:,3).*lambda(:,2).*(3*lambda(:,3)-1); \n phi(:,6) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,3)-1); \n phi(:,7) = 9/2*lambda(:,1).*lambda(:,3).*(3*lambda(:,1)-1); \n phi(:,8) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,1)-1);\n phi(:,9) = 9/2*lambda(:,1).*lambda(:,2).*(3*lambda(:,2)-1); \n phi(:,10) = 27*lambda(:,1).*lambda(:,2).*lambda(:,3); \n for p = 1:nQuad\n intguh(:) = intguh(:) + w(p)*(phi(p,1)*u(elem2dof(:,1))+phi(p,2)*u(elem2dof(:,2))+phi(p,3)*u(elem2dof(:,3))...\n + phi(p,4)*u(elem2dof(:,4))+phi(p,5)*u(elem2dof(:,5))+phi(p,6)*u(elem2dof(:,6))...\n + phi(p,7)*u(elem2dof(:,7))+phi(p,8)*u(elem2dof(:,8))+phi(p,9)*u(elem2dof(:,9))...\n + phi(p,10)*u(elem2dof(:,10)));\n end %compute the intgrable of uh.\n intguh = intguh.*area;\n uc = sum(intguh)/sum(area);\n u = u - uc; % normalization for pure Neumann problem\nend\n\n% Output information\neqn = struct('A',AD,'b',b,'edge',edge,'freeDof',freeDof);\ninfo.assembleTime = assembleTime;\n\n%% Compute Du\nDu = [];\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdP3\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,b,u,freeDof,isPureNeumann] = getbdP3(b)\n %% Boundary conditions for Poisson equation: P3 quadratic FEM.\n %\n % The set up of boundary condition consists of two parts: \n %\n % 1) Modify the matrix for Dirichlet boundary nodes, which are not degree\n % of freedom. Values at these nodes are evaluatation of pde.g_D. The\n % original stiffness matrix A is turn into the matrix AD by enforcing\n % AD(fixedDof,fixedDof)=I, AD(fixedDof,freeDof)=0, AD(freeDof,fixedDof)=0.\n %\n % 2) Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedDof) is the evaluation of\n % pde.g_D.\n %\n % Special attentation should be given for the pure Neumann boundary\n % condition. To enforce the compatible condition, the vector b should have\n % mean value zero. To avoid a singular matrix, the 1st node is chosen as\n % fixedDof. \n %\n % The order of assigning Neumann and Dirichlet boundary condition is\n % important to get the right setting at the intersection nodes of Dirichlet\n % and Neumann boundary edges.\n\n u = zeros(Ndof,1);\n \n %% Set up boundary and basic parameter\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Modify the matrix for Dirichlet and Robin condition\n % Robin boundary condition\n Robin = [];\n idxR = (bdFlag(:) == 3); %index of Robin edges in bdFlag\n if any(idxR) \n isRobin = false(NE,1);\n isRobin(elem2edge(idxR)) = true;\n Robin = edge(isRobin,:); % Robin edges \n end\n if ~isempty(Robin) && ~isempty(pde.g_R) && ~(isnumeric(pde.g_R) && (pde.g_R == 0))\n if ~isfield(option,'gRquadorder')\n option.gRquadorder = 8; % we should use six order rule.\n end\n [lambdagR,weightgR] = quadpts1(option.gRquadorder);\n nQuadgR = size(lambdagR,1);\n % cubic bases (1--3--4--2)\n bdphi = zeros(nQuadgR,4); \n bdphi(:,1) = 0.5*(3*lambdagR(:,1)-1).*(3*lambdagR(:,1)-2).*lambdagR(:,1); \n bdphi(:,2) = 0.5*(3*lambdagR(:,2)-1).*(3*lambdagR(:,2)-2).*lambdagR(:,2);\n bdphi(:,3) = 9/2*lambdagR(:,1).*lambdagR(:,2).*(3*lambdagR(:,1)-1);\n bdphi(:,4) = 9/2*lambdagR(:,1).*lambdagR(:,2).*(3*lambdagR(:,2)-1); \n % length of edge\n el = sqrt(sum((node(Robin(:,1),:) - node(Robin(:,2),:)).^2,2));\n NR = size(Robin,1);\n ss = zeros(NR,4,4);\n for pp = 1:nQuadgR\n ppxy = lambdagR(pp,1)*node(Robin(:,1),:) ...\n + lambdagR(pp,2)*node(Robin(:,2),:);\n gRp = pde.g_R(ppxy);\n for iR = 1:4\n for jR = iR:4 % only compute half of the off-diagonal part\n ss(:,iR,jR) = ss(:,iR,jR) + ...\n weightgR(pp)*gRp*bdphi(pp,iR).*bdphi(pp,jR);\n end\n end\n end\n ss(:) = ss(:).*repmat(el,16,1);\n Robin(:,3) = 2*find(isRobin)+N-1; % the third one maps to corresponding dof\n Robin(:,4) = 2*find(isRobin)+N; % the fourth one maps to corresponding dof\n index = 0;\n for iR = 1:4\n for jR = 1:4\n iiR(index+1:index+NR) = double(Robin(:,iR)); \n jjR(index+1:index+NR) = double(Robin(:,jR)); \n if jR>=iR\n ssR(index+1:index+NR) = ss(:,iR,jR);\n else\n ssR(index+1:index+NR) = ss(:,jR,iR);\n end\n index = index + NR;\n end\n end\n A = A + sparse(iiR,jjR,ssR,Ndof,Ndof);\n end\n\n % Find Dirichlet boundary dof: fixedDof\n fixedDof = []; freeDof = [];\n isFixedDof = false(Ndof,1); \n if ~isempty(bdFlag) \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n isFixedDof(edge(isDirichlet,:)) = true;\n isFixedDof(N + 2*find(isDirichlet')-1) = true;\n isFixedDof(N + 2*find(isDirichlet')) = true;\n fixedDof = find(isFixedDof);\n freeDof = find(~isFixedDof); \n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n fixedDof = bdDof;\n isFixedDof(fixedDof) = true;\n freeDof = find(~isFixedDof); \n end\n isPureNeumann = false; \n if isempty(fixedDof) && isempty(Robin) % pure Neumann boundary condition\n % pde.g_N could be empty which is homogenous Neumann boundary condition\n isPureNeumann = true;\n fixedDof = 1;\n freeDof = 2:Ndof; % eliminate the kernel by enforcing u(1) = 0;\n end\n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % |AD(fixedDof,fixedDof)=I, AD(fixedDof,freeDof)=0,\n % AD(freeDof,fixedDof)=0|.\n if ~isempty(fixedDof)\n bdidx = zeros(Ndof,1); \n bdidx(fixedDof) = 1;\n Tbd = sparse(1:Ndof,1:Ndof,bdidx,Ndof,Ndof);\n T = sparse(1:Ndof,1:Ndof,1-bdidx,Ndof,Ndof);\n AD = T*A*T + Tbd;\n else\n AD = A;\n end\n \n %% Part 2: Find boundary edges and modify the load b\n % Find boundary edges: Neumann and Robin\n Neumann = [];\n if ~isempty(bdFlag) \n idxN = (bdFlag(:) == 2); % all Neumann edges in bdFlag \n Neumannidx = elem2edge(idxN | idxR); % index of Neumann and Robin edges\n % since boundary integral is also needed for Robin edges\n Neumann = edge(Neumannidx,:);\n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n Neumannidx = find(bdDof>N);\n Neumann = edge(Neumannidx,:);\n end\n \n % Neumann boundary condition\n if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 6; \n end\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n nQuadgN = size(lambdagN,1);\n % quadratic bases (1---3---4--2)\n bdphi = zeros(nQuadgN,4); \n bdphi(:,1) = 0.5*(3*lambdagN(:,1)-1).*(3*lambdagN(:,1)-2).*lambdagN(:,1); \n bdphi(:,2) = 0.5*(3*lambdagN(:,2)-1).*(3*lambdagN(:,2)-2).*lambdagN(:,2);\n bdphi(:,3) = 9/2*lambdagN(:,1).*lambdagN(:,2).*(3*lambdagN(:,1)-1);\n bdphi(:,4) = 9/2*lambdagN(:,1).*lambdagN(:,2).*(3*lambdagN(:,2)-1);\n % length of edge\n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n ge = zeros(size(Neumann,1),4);\n for pp = 1:nQuadgN\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNp = pde.g_N(ppxy);\n ge(:,1) = ge(:,1) + weightgN(pp)*gNp*bdphi(pp,1);\n ge(:,2) = ge(:,2) + weightgN(pp)*gNp*bdphi(pp,2);\n ge(:,3) = ge(:,3) + weightgN(pp)*gNp*bdphi(pp,3); \n ge(:,4) = ge(:,4) + weightgN(pp)*gNp*bdphi(pp,4);\n end\n ge = ge.*repmat(el,1,4);\n b(1:N) = b(1:N) + accumarray(Neumann(:), [ge(:,1); ge(:,2)],[N,1]);\n b(N+2*Neumannidx-1) = b(N+2*Neumannidx-1) + ge(:,3);\n b(N+2*Neumannidx) = b(N+2*Neumannidx) + ge(:,4);\n end\n\n % Dirichlet boundary conditions\n if ~isPureNeumann && ~isempty(fixedDof) && ...\n ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n % interpolation\n idx = (fixedDof > N); % index of edge nodes\n u(fixedDof(~idx)) = pde.g_D(node(fixedDof(~idx),:)); % bd value at vertex dofs\n % for P3, we should divide the points of edge into two parts. \n bdEdgeIdx = fixedDof(idx) - N;\n % First parts, the points * is in 1---*------2\n bdEdgeMid = node(edge(isDirichlet,1),:)+(node(edge(isDirichlet,2),:) ...\n - node(edge(isDirichlet,1),:))/3;\n u(N + bdEdgeIdx(1:2:end)) = pde.g_D(bdEdgeMid);\n % Second parts, the points * is in 1------*---2 \n bdEdgeMid = node(edge(isDirichlet,1),:)+2*(node(edge(isDirichlet,2),:)...\n - node(edge(isDirichlet,1),:))/3; \n u(N + bdEdgeIdx(2:2:end)) = pde.g_D(bdEdgeMid);\n % modify the right hand side\n b = b - A*u;\n end\n if ~isPureNeumann % non-empty Dirichlet boundary condition\n b(fixedDof) = u(fixedDof);\n end\n \n % Pure Neumann boundary condition\n if isPureNeumann\n b = b - mean(b); % compatilbe condition: sum(b) = 0\n b(1) = 0; \n end\n end % end of getbdP3\nend % end of function PoissonP3", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/PoissonP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6447399834447348}} {"text": "function S = tsmooth(I,lambda,sigma,sharpness,maxIter)\n%tsmooth - Structure Extraction from Texture via Relative Total Variation\n% S = tsmooth(I, lambda, sigma, maxIter) extracts structure S from\n% structure+texture input I, with smoothness weight lambda, scale\n% parameter sigma and iteration number maxIter. \n% \n% Paras: \n% @I : Input UINT8 image, both grayscale and color images are acceptable.\n% @lambda : Parameter controlling the degree of smooth. \n% Range (0, 0.05], 0.01 by default.\n% @sigma : Parameter specifying the maximum size of texture elements.\n% Range (0, 6], 3 by defalut. \n% @sharpness : Parameter controlling the sharpness of the final results,\n% which corresponds to \\epsilon_s in the paper [1]. The smaller the value, the sharper the result. \n% Range (1e-3, 0.03], 0.02 by defalut. \n% @maxIter : Number of itearations, 4 by default.\n% \n% Example\n% ==========\n% I = imread('Bishapur_zan.jpg');\n% S = tsmooth(I); % Default Parameters (lambda = 0.01, sigma = 3, sharpness = 0.02, maxIter = 4)\n% figure, imshow(I), figure, imshow(S);\n%\n% ==========\n% The Code is created based on the method described in the following paper \n% [1] \"Structure Extraction from Texture via Relative Total Variation\", Li Xu, Qiong Yan, Yang Xia, Jiaya Jia, ACM Transactions on Graphics, \n% (SIGGRAPH Asia 2012), 2012. \n% The code and the algorithm are for non-comercial use only.\n% \n% Author: Li Xu (xuli@cse.cuhk.edu.hk)\n% Date : 08/25/2012\n% Version : 1.0 \n% Copyright 2012, The Chinese University of Hong Kong.\n% \n\n if (~exist('lambda','var'))\n lambda=0.01;\n end \n if (~exist('sigma','var'))\n sigma=3.0;\n end \n if (~exist('sharpness','var'))\n sharpness = 0.02;\n end\n if (~exist('maxIter','var'))\n maxIter=4;\n end \n I = im2double(I);\n x = I;\n sigma_iter = sigma;\n lambda = lambda/2.0;\n dec=2.0;\n for iter = 1:maxIter\n [wx, wy] = computeTextureWeights(x, sigma_iter, sharpness);\n x = solveLinearEquation(I, wx, wy, lambda);\n sigma_iter = sigma_iter/dec;\n if sigma_iter < 0.5\n sigma_iter = 0.5;\n end\n end\n S = x; \nend\n\nfunction [retx, rety] = computeTextureWeights(fin, sigma,sharpness)\n\n fx = diff(fin,1,2);\n fx = padarray(fx, [0 1 0], 'post');\n fy = diff(fin,1,1);\n fy = padarray(fy, [1 0 0], 'post');\n \n vareps_s = sharpness;\n vareps = 0.001;\n\n wto = max(sum(sqrt(fx.^2+fy.^2),3)/size(fin,3),vareps_s).^(-1); \n fbin = lpfilter(fin, sigma);\n gfx = diff(fbin,1,2);\n gfx = padarray(gfx, [0 1], 'post');\n gfy = diff(fbin,1,1);\n gfy = padarray(gfy, [1 0], 'post'); \n wtbx = max(sum(abs(gfx),3)/size(fin,3),vareps).^(-1); \n wtby = max(sum(abs(gfy),3)/size(fin,3),vareps).^(-1); \n retx = wtbx.*wto;\n rety = wtby.*wto;\n\n retx(:,end) = 0;\n rety(end,:) = 0;\n \nend\n\nfunction ret = conv2_sep(im, sigma)\n ksize = bitor(round(5*sigma),1);\n g = fspecial('gaussian', [1,ksize], sigma); \n ret = conv2(im,g,'same');\n ret = conv2(ret,g','same'); \nend\n\nfunction FBImg = lpfilter(FImg, sigma) \n FBImg = FImg;\n for ic = 1:size(FBImg,3)\n FBImg(:,:,ic) = conv2_sep(FImg(:,:,ic), sigma);\n end \nend\n\nfunction OUT = solveLinearEquation(IN, wx, wy, lambda)\n% \n% The code for constructing inhomogenious Laplacian is adapted from \n% the implementaion of the wlsFilter. \n% \n% For color images, we enforce wx and wy be same for three channels\n% and thus the pre-conditionar only need to be computed once. \n% \n [r,c,ch] = size(IN);\n k = r*c;\n dx = -lambda*wx(:);\n dy = -lambda*wy(:);\n B(:,1) = dx;\n B(:,2) = dy;\n d = [-r,-1];\n A = spdiags(B,d,k,k);\n e = dx;\n w = padarray(dx, r, 'pre'); w = w(1:end-r);\n s = dy;\n n = padarray(dy, 1, 'pre'); n = n(1:end-1);\n D = 1-(e+w+s+n);\n A = A + A' + spdiags(D, 0, k, k); \n if exist('ichol','builtin')\n L = ichol(A,struct('michol','on')); \n OUT = IN;\n for ii=1:ch\n tin = IN(:,:,ii);\n [tout, flag] = pcg(A, tin(:),0.1,100, L, L'); \n OUT(:,:,ii) = reshape(tout, r, c);\n end \n else\n OUT = IN;\n for ii=1:ch\n tin = IN(:,:,ii);\n tout = A\\tin(:);\n OUT(:,:,ii) = reshape(tout, r, c);\n end \n end\n \nend", "meta": {"author": "BehnoodRasti", "repo": "HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox", "sha": "effc9ee5970306a2e822b1831c32ab5580c1bbfe", "save_path": "github-repos/MATLAB/BehnoodRasti-HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox", "path": "github-repos/MATLAB/BehnoodRasti-HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox/HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox-effc9ee5970306a2e822b1831c32ab5580c1bbfe/ShallowFE/UFE/MSTV/functions/tsmooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6447179845664421}} {"text": "function cs_star = surfaceConcentration(cs_barrato,jflux,Q,T,param)\n% surfaceConcentration evaluates the concentration of Li-ions at the electrode surfaces.\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% Diffusion coefficients for the solid phase\n[Dps_eff, Dns_eff] = param.SolidDiffusionCoefficientsFunction(T,param);\n\n% Check what kind of solid diffusion model has been chosen.\nif(param.SolidPhaseDiffusion==1) % Two parameters model\n % Evaluates the average surface concentration in both the electrodes.\n % Cathode\n cs_star_p = cs_barrato(1:param.Np)-(param.Rp_p./(Dps_eff.*5)).*jflux(1:param.Np);\n % Anode\n cs_star_n = cs_barrato(param.Np+1:end)-(param.Rp_n./(Dns_eff.*5)).*jflux(param.Np+1:end);\nelseif(param.SolidPhaseDiffusion==2) % Three parameters model\n % Cathode\n cs_star_p = cs_barrato(1:param.Np)+(param.Rp_p./(Dps_eff.*35)).*(-jflux(1:param.Np)+8*Dps_eff.*Q(1:param.Np));\n % Anode\n cs_star_n = cs_barrato(param.Np+1:end)+(param.Rp_n./(Dns_eff.*35)).*(-jflux(param.Np+1:end)+8*Dns_eff.*Q(param.Np+1:end));\nelseif(param.SolidPhaseDiffusion==3) % Full model\n p_indices = param.Nr_p:param.Nr_p:param.Nr_p*param.Np;\n n_indices = param.Nr_n:param.Nr_n:param.Nr_n*param.Nn;\n % If the full model has been used, just take the concentration data at r=Rp\n cs_star_p = cs_barrato(p_indices);\n cs_star_n = cs_barrato(n_indices+p_indices(end));\nend\n% Return the residuals\ncs_star = [cs_star_p;cs_star_n];\n\nend\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/P2D_equations/surfaceConcentration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6447179600963776}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reduce an image applying Gaussian Pyramid.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction IResult = GPReduce(I,displayflag)\n\nif ~exist('displayflag','var')\n\tdisplayflag = 1;\nend\n\nWt = [0.0500 0.2500 0.4000 0.2500 0.0500];\n\ndim = size(I);\nnewdim = ceil(dim*0.5);\nIResult = zeros(newdim,class(I)); % Initialize the array in the beginning ..\nI = single(I);\nm = [-2:2];n=m;\n\nswitch length(dim)\n\tcase 1\n\t\t%% Pad the boundaries.\n\t\tI = [ I(1) ; I(1) ; I ; I(dim(1)); I(dim(1)) ]; % Add two rows towards the beginning and the end.\n\t\tfor i = 0 : newdim(1) -1\n\t\t\tA = I(2*i+m+3).*Wt;;\n\t\t\tIResult(i + 1)= sum(A(:));\n\t\tend\n\tcase 2\n\t\t%% Pad the boundaries.\n\t\tI = [ I(1,:) ; I(1,:) ; I ; I(dim(1),:); I(dim(1),:) ]; % Add two rows towards the beginning and the end.\n\t\tI = [ I(:,1) I(:,1) I I(:,dim(2)) I(:,dim(2)) ]; % Add two columns towards the beginning and the end.\n\t\t\n\t\tWt2 = Wt'*Wt;\n\t\t\n\t\tfor i = 0 : newdim(1) -1\n\t\t\tfor j = 0 : newdim(2) -1\n\t\t\t\tA = I(2*i+m+3,2*j+m+3).*Wt2;\n\t\t\t\tIResult(i + 1, j + 1) = sum(A(:));\n\t\t\tend\n\t\tend\n\n\tcase 3\n\t\tWt3 = ones(5,5,5);\n\t\tfor i = 1:5\n\t\t\tWt3(i,:,:) = Wt3(i,:,:) * Wt(i);\n\t\t\tWt3(:,i,:) = Wt3(:,i,:) * Wt(i);\n\t\t\tWt3(:,:,i) = Wt3(:,:,i) * Wt(i);\n\t\tend\n\t\t\n\t\t%% Pad the boundaries.\n\t\tI2 = zeros(dim+4,class(I));\n\t\tI2(3:2+dim(1),3:2+dim(2),3:2+dim(3)) = I;\n\t\tI2(1,:,:)=I2(3,:,:);I2(1,:,:)=I2(3,:,:);I2(end,:,:)=I2(end-2,:,:);I2(end-1,:,:)=I2(end-2,:,:);\n\t\tI2(:,1,:)=I2(:,3,:);I2(:,2,:)=I2(:,3,:);I2(:,end,:)=I2(:,end-2,:);I2(:,end-1,:)=I2(:,end-2,:);\n\t\tI2(:,:,1)=I2(:,:,3);I2(:,:,2)=I2(:,:,3);I2(:,:,end)=I2(:,:,end-2);I2(:,:,end-1)=I2(:,:,end-2);\n\t\tI=I2; clear I2;\n\n\t\tif( displayflag==1) \n\t\t\tH = waitbar(0,'Progress');\n\t\t\tset(H,'Name','GPReduce ...');\n\t\tend\n\t\tfor k = 0 : newdim(3) - 1\n\t\t\tif( displayflag==1)\n\t\t\t\twaitbar(k/newdim(3),H,sprintf('(%d%%) %d out of %d',round(k/newdim(3)*100),k,newdim(3)));\n\t\t\telse\n\t\t\t\tfprintf('.');\n\t\t\tend\n\t\t\tfor j = 0 : newdim(2) -1\n\t\t\t\tfor i = 0 : newdim(1) -1\n\t\t\t\t\tA = I(2*i+m+3,2*j+m+3,2*k+m+3).*Wt3;\n\t\t\t\t\tIResult(i+1,j+1,k+1) = sum(A(:));\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tif( displayflag==1) \n\t\t\tclose(H);\n\t\telse\n\t\t\tfprintf('\\n');\n\t\tend\nend\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/ImageRegistration/OpticalFlow/GPReduce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6446315299721813}} {"text": "function spline_test04 ( )\n\n%*****************************************************************************80\n%\n%% TEST04 tests BASIS_MATRIX_BETA_UNI, BASIS_MATRIX_TMP.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author\n%\n% John Burkardt\n%\n n = 4;\n ndata = 4;\n nsample = 4;\n tdata = [ -1.0E+00, 0.0E+00, 1.0E+00, 2.0E+00 ]';\n ydata = [ 4.0E+00, 7.0E+00, 12.0E+00, 19.0E+00 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST04\\n' );\n fprintf ( 1, ' BASIS_MATRIX_BETA_UNI sets up the basis matrix\\n' );\n fprintf ( 1, ' for the uniform beta spline.\\n' );\n%\n% First test\n%\n beta1 = 1.0E+00;\n beta2 = 0.0E+00;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BETA1 = %14f\\n', beta1 );\n fprintf ( 1, ' BETA2 = %14f\\n', beta2 );\n\n mbasis = basis_matrix_beta_uni ( beta1, beta2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TDATA, YDATA\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : ndata\n fprintf ( 1, '%12f %12f\\n', tdata(i), ydata(i) );\n end\n\n left = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, Spline(T)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : ndata\n\n if ( i == 0 )\n tlo = tdata(1) - 0.5E+00 * ( tdata(2) - tdata(1) );\n thi = tdata(1);\n elseif ( i < ndata )\n tlo = tdata(i);\n thi = tdata(i+1);\n elseif ( ndata <= i )\n tlo = tdata(ndata);\n thi = tdata(ndata) + 0.5E+00 * ( tdata(ndata) - tdata(ndata-1) );\n end\n\n if ( i < ndata )\n jhi = nsample - 1;\n else\n jhi = nsample;\n end\n\n for j = 0 : jhi\n\n tval = ( ( nsample - j ) * tlo ...\n + ( j ) * thi ) ...\n / nsample;\n\n yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval );\n\n if ( 0 < i & j == 0 )\n mark = '*';\n else\n mark = ' ';\n end\n\n fprintf ( 1, '%c %12f %12f\\n', mark, tval, yval );\n\n end\n\n end\n%\n% Second test\n%\n beta1 = 1.0E+00;\n beta2 = 100.0E+00;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BETA1 = %14f\\n', beta1 );\n fprintf ( 1, ' BETA2 = %14f\\n', beta2 );\n\n mbasis = basis_matrix_beta_uni ( beta1, beta2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TDATA, YDATA\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : ndata\n fprintf ( 1, '%12f %12f\\n', tdata(i), ydata(i) );\n end\n\n left = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, Spline(T)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : ndata\n\n if ( i == 0 )\n tlo = tdata(1) - 0.5E+00 * ( tdata(2) - tdata(1) );\n thi = tdata(1);\n elseif ( i < ndata )\n tlo = tdata(i);\n thi = tdata(i+1);\n elseif ( ndata <= i )\n tlo = tdata(ndata);\n thi = tdata(ndata) + 0.5E+00 * ( tdata(ndata) - tdata(ndata-1) );\n end\n\n if ( i < ndata )\n jhi = nsample - 1;\n else\n jhi = nsample;\n end\n\n for j = 0 : jhi\n\n tval = ( ( nsample - j ) * tlo ...\n + ( j ) * thi ) ...\n / nsample;\n\n yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval );\n\n if ( 0 < i & j == 0 )\n mark = '*';\n else\n mark = ' ';\n end\n\n fprintf ( 1, '%c %12f %12f\\n', mark, tval, yval );\n\n end\n\n end\n%\n% Third test\n%\n beta1 = 100.0E+00;\n beta2 = 0.0E+00;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BETA1 = %14f\\n', beta1 );\n fprintf ( 1, ' BETA2 = %14f\\n', beta2 );\n\n mbasis = basis_matrix_beta_uni ( beta1, beta2 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TDATA, YDATA\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : ndata\n fprintf ( 1, '%12f %12f\\n', tdata(i), ydata(i) );\n end\n\n left = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, Spline(T)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : ndata\n\n if ( i == 0 )\n tlo = tdata(1) - 0.5E+00 * ( tdata(2) - tdata(1) );\n thi = tdata(1);\n elseif ( i < ndata )\n tlo = tdata(i);\n thi = tdata(i+1);\n elseif ( ndata <= i )\n tlo = tdata(ndata);\n thi = tdata(ndata) + 0.5E+00 * ( tdata(ndata) - tdata(ndata-1) );\n end\n\n if ( i < ndata )\n jhi = nsample - 1;\n else\n jhi = nsample;\n end\n\n for j = 0 : jhi\n\n tval = ( ( nsample - j ) * tlo ...\n + ( j ) * thi ) ...\n / nsample;\n\n yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval );\n\n if ( 0 < i & j == 0 )\n mark = '*';\n else\n mark = ' ';\n end\n\n fprintf ( 1, '%c %12f %12f\\n', mark, tval, yval );\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/spline_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6446315290675209}} {"text": "function [I] = corrindex(XData, YData, YDataM, par_number)\n%\n% Function for calculation of the correlation index\n%\n% Inputs: XData: x data\n% YData: y data\n% YDataM: model data\n% par_number: number of model parameters\n% Output: I: correlation index\n%\n% Authors:\n% Ivo Petras (ivo.petras@tuke.sk)\n% Dagmar Bednarova (dagmar.bednarova@tuke.sk)\n%\n% Date: 21/002/2007\n%\nkx=length(XData);\nky=length(YData);\nkym=length(YDataM);\nif kx ~= ky \n disp('Incompatible X and Y data.');\n close all;\nend\nn=kym;\nsey=(sum((YData-YDataM).^2))/(n-par_number);\nsy=var(YData);\nI=(1-(sey./sy))^0.5;\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/31109-total-least-squares-method/corrindex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6446315234544053}} {"text": "function out=mp(x,y)\n%MP multiple precision class constructor.\n% p = mp(x,y) creates a mp object from the matrices x and y,\n% where x contains the double to be converted into an mp object\n% y contains the precision\n% Special calls to mp include:\n% mp('pi',precision) => returns pi to precision (precision is optional)\n\nmaxDoublePrec=16; %digits\nif nargin == 0\n out.rval=[];\n out.ival=[];\n out.precision=[];\n out=class(out,'mp');\nelseif isa(x,'mp')\n %out=x;\n if nargin==1\n out=x;\n else\n for ii=1:numel(x)\n out(ii)=mp(x(ii).rval,y(min(numel(y),ii)));\n if ~isreal(x(ii))\n out(ii)=out(ii)+mp(x(ii).ival,y(min(numel(y),ii)))*i;\n end\n end\n end % if nargin==2\nelse\n mp_defaults\n precision=default_precision;\n out_rval=cell(size(x));\n out_ival=cell(size(x));\n if nargin==2\n precision=double(y(1));\n end % if nargin==2\n if isa(x,'double')\n for ii=1:numel(x)\n [str,exponent]=mpfr_construct_dd(real(x(ii)),precision);\n % throw away anything past maxDoublePrec, set to 0's\n if length(str)>maxDoublePrec\n str(maxDoublePrec+1:end)='0';\n end\n out_rval{ii}=mpExpForm(mpAddDecimal(str),exponent);\n if ~isreal(x(ii))\n [str,exponent]=mpfr_construct_dd(imag(x(ii)),precision);\n % throw away anything past maxDoublePrec, set to 0's\n if length(str)>maxDoublePrec\n str(maxDoublePrec+1:end)='0';\n end\n out_ival{ii}=mpExpForm(mpAddDecimal(str),exponent);\n end\n end % for ii=1:size(x,\n elseif isa(x,'cell')\n for ii=1:numel(x)\n [str,exponent]=mpfr_construct_cd(x{ii},precision);\n out_rval{ii}=mpExpForm(mpAddDecimal(str),exponent);\n end % for ii=1:size(x,\n elseif isa(x,'char')\n out_rval=cell(1);\n out_ival=cell(1);\n if any(strfind(lower(x),'pi'))\n out_rval=mpfr_pi(precision);\n%%% [str,exponent]=mpfr_pi(precision);\n%%% out_rval=mpExpForm(mpAddDecimal(str),exponent);\n else\n [str,exponent]=mpfr_construct_cd(x,precision);\n out_rval{1,1}=mpExpForm(mpAddDecimal(str),exponent);\n end\n end\n out=class(struct('rval',out_rval,...\n 'ival',out_ival,...\n 'precision',precision),'mp');\nend\n\n\n%%%out_rval\n%%%out_rexp\n%%%out_ival\n%%%out_iexp\n\n%'rrrrrrr',kb\n% x=magic(3),s1='023e1',s2='-.002e-1'\n% mp(x)\n\n\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/mp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6444659955741118}} {"text": "function [connmat] = triangle2connectivity(tri, pos)\n\n% TRIANGLE2CONNECTIVITY computes a connectivity-matrix from a triangulation.\n%\n% Use as\n% [connmat] = triangle2connectivity(tri)\n% or\n% [connmat] = triangle2connectivity(tri, pos)\n%\n% The input tri is an Mx3 matrix describing a triangulated surface,\n% containing indices to connecting vertices. The output connmat is a sparse\n% logical NxN matrix, with ones, where vertices are connected, and zeros\n% otherwise.\n%\n% If you specify the vertex positions in the second input argument as Nx3\n% matrix, the output will be a sparse matrix with the lengths of the\n% edges between the connected vertices.\n%\n% See also CHANNELCONNECTIVIY\n\n% Copyright (C) 2015, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% ensure that the vertices are indexed starting from 1\nif min(tri(:))==0,\n tri = tri + 1;\nend\n\n% ensure that the vertices are indexed according to 1:number of unique vertices\ntri = tri_reindex(tri);\n\n% create the unique edges from the triangulation\nedges = [tri(:,[1 2]); tri(:,[1 3]); tri(:,[2 3])];\nedges = double(unique(sort([edges; edges(:,[2 1])],2), 'rows'));\n\n% fill the connectivity matrix\nn = size(edges,1);\nif nargin<2\n % create sparse binary matrix\n connmat = sparse([edges(:,1);edges(:,2)],[edges(:,2);edges(:,1)],true(2*n,1));\nelse\n % create sparse matrix with edge lengths\n dpos = sqrt(sum( (pos(edges(:,1),:) - pos(edges(:,2),:)).^2, 2));\n connmat = sparse([edges(:,1);edges(:,2)],[edges(:,2);edges(:,1)],[dpos(:);dpos(:)]);\nend\n\nfunction [newtri] = tri_reindex(tri)\n\n% this subfunction reindexes tri such that they run from 1:number of unique vertices\nnewtri = tri;\n[srt, indx] = sort(tri(:));\ntmp = cumsum(double(diff([0;srt])>0));\nnewtri(indx) = tmp;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/triangle2connectivity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6444659773559039}} {"text": "function [gamma, loglik, marginals, marginalsT] = bk_ff_fb(prior, transmat, obslik, filter_only, hnodes, ns)\n% BK_FF_FB Fully factored Boyen-Koller version of forwards-backwards\n% [gamma, loglik, marginals, marginalsT] = bk_ff_hmm(prior, transmat, obslik, filter_only, hnodes, ns)\n\nss = length(ns);\nS = length(prior);\nT = size(obslik, 2);\nmarginals = cell(ss,T);\nmarginalsT = cell(ss,T);\nscale = zeros(1,T);\nalpha = zeros(S, T);\n\ntransmat2 = transmat';\nfor t=1:T\n if t==1\n [alpha(:,t), scale(t)] = normalise(prior(:) .* obslik(:,t));\n else\n [alpha(:,t), scale(t)] = normalise((transmat2 * alpha(:,t-1)) .* obslik(:,t));\n end\n [marginals(:,t), marginalsT(:,t)] = project_joint_onto_marginals(alpha(:,t), hnodes, ns);\n alpha(:,t) = combine_marginals_into_joint(marginalsT(:,t), hnodes, ns);\n %fprintf('alpha t=%d\\n', t);\n %celldisp(marginals(1:8,t))\nend\nloglik = sum(log(scale));\n\nif filter_only\n gamma = alpha;\n return;\nend\n\nbeta = zeros(S,T);\ngamma = zeros(S,T);\nt = T;\nbeta(:,t) = ones(S,1);\ngamma(:,t) = normalise(alpha(:,t) .* beta(:,t));\n[marginals(:,t), marginalsT(:,t)] = project_joint_onto_marginals(gamma(:,t), hnodes, ns);\n\nfor t=T-1:-1:1\n b = beta(:,t+1) .* obslik(:,t+1); \n beta(:,t) = normalise((transmat * b));\n [junk, tempT] = project_joint_onto_marginals(beta(:,t), hnodes, ns);\n beta(:,t) = combine_marginals_into_joint(tempT, hnodes, ns);\n %gamma(:,t) = normalise(alpha(:,t) .* beta(:,t));\n %[marginals(:,t), marginalsT(:,t)] = project_joint_onto_marginals(gamma(:,t), hnodes, ns);\nend\n\ngamma2 = zeros(S,T);\nfor t=T-1:-1:1\n b = beta(:,t+1) .* obslik(:,t+1); \n xi(:,:,t) = normalise((transmat .* (alpha(:,t) * b'))); \n if t==T-1\n gamma2(:,T) = sum(xi(:,:,T-1), 1)';\n end\n gamma2(:,t) = sum(xi(:,:,t), 2);\n [marginals(:,t), marginalsT(:,t)] = project_joint_onto_marginals(gamma2(:,t), hnodes, ns);\nend\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/dynamic/@bk_ff_hmm_inf_engine/private/bk_ff_fb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6443937677770534}} {"text": "function H = boxper(sequence,isplot,boxnumber)\n%\n% 'boxper' estimate the hurst parameter of a given sequence with modified\n% periodogram method.\n% \n% Inputs:\n% sequence: the input sequence for estimate \n% isplot: whether display the plot. without a plot if isplot equal to 0 \n% Outputs:\n% H: the estimated hurst coeffeient of the input sequence\n\n% Author: Chu Chen \n% Version 1.0, 03/10/2008\n% chen-chu@163.com\n%\n\nif nargin == 1\n boxnumber = 50;\n isplot = 0;\nend\n\nif nargin == 2\n boxnumber = 50;\nend\n\nif boxnumber < 30 || boxnumber > 100\n error('The input argument boxnumber must be a integer between [30,100]');\nend\n\nn = length(sequence);\nXk = fft(sequence);\nP_origin = abs(Xk).^2/(2*pi*n);\nP = P_origin(1:floor(n/2)+1);\n\ncut_min = ceil(0.001*n/2);\nM = floor(logspace(log10(cut_min),log10(0.1*n-cut_min),boxnumber+1));\nM = unique(M);\nN = length(M)-1;\n\nx = zeros(1,N);\ny = zeros(1,N);\nfor i = 1:N\n m1 = M(i) + cut_min;\n m2 = M(i+1) + cut_min;\n x(i) = log10((pi * (m2 - m1))/(n));\n y(i) = log10(sum(P(m1:m2))/(m2-m1+1));\nend\n\nX = x;\nY = y;\np1 = polyfit(X,Y,1);\nYfit = polyval(p1,X);\nH = (1-(Yfit(end)-Yfit(1))/(X(end)-X(1)))/2;\n\nif isplot ~= 0\n figure,clf,hold on;\n plot(x,y,'b.');\n plot(X,Yfit,'r-','LineWidth',2);\n xlabel('Log10(Frequency)'),ylabel('Log10(Periodogram)'),title('Boxed Periodogram Method');\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/19148-hurst-parameter-estimate/hurst estimator/boxper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6443937628068415}} {"text": "function [q1New,q2New,dq1New,dq2New] = autoGen_heelStrike(q1,q2,dq1,dq2,m,I,d,l)\n%AUTOGEN_HEELSTRIKE\n% [Q1NEW,Q2NEW,DQ1NEW,DQ2NEW] = AUTOGEN_HEELSTRIKE(Q1,Q2,DQ1,DQ2,M,I,D,L)\n\n% This function was generated by the Symbolic Math Toolbox version 6.2.\n% 07-Sep-2015 19:06:42\n\nq1New = q2;\nif nargout > 1\n q2New = q1;\nend\nif nargout > 2\n t2 = d.^2;\n t3 = m.^2;\n t4 = l.^2;\n t5 = I.^2;\n t6 = t2.^2;\n t7 = q1-q2;\n t8 = cos(t7);\n t9 = t3.*t6;\n t10 = t2.*t3.*t4.*(3.0./2.0);\n t11 = I.*m.*t2.*2.0;\n t12 = I.*m.*t4.*2.0;\n t13 = q1.*2.0;\n t18 = q2.*2.0;\n t14 = t13-t18;\n t15 = cos(t14);\n t16 = t5+t9+t10+t11+t12-d.*l.*t2.*t3.*2.0-t2.*t3.*t4.*t15.*(1.0./2.0)-I.*d.*l.*m.*2.0;\n t17 = 1.0./t16;\n dq1New = t17.*(dq2.*t5+dq2.*t3.*t6+I.*dq2.*m.*t2.*2.0-I.*d.*dq2.*l.*m+I.*dq1.*m.*t4.*t8.*2.0-d.*dq2.*l.*t2.*t3+dq1.*t2.*t3.*t4.*t8-I.*d.*dq1.*l.*m.*t8-d.*dq1.*l.*t2.*t3.*t8);\nend\nif nargout > 3\n dq2New = t17.*(dq1.*t5+dq1.*t3.*t6+dq1.*t2.*t3.*t4.*3.0+I.*dq1.*m.*t2.*2.0+I.*dq1.*m.*t4.*2.0-I.*d.*dq1.*l.*m.*3.0-d.*dq1.*l.*t2.*t3.*3.0-d.*dq1.*l.*t3.*t4-dq2.*t2.*t3.*t4.*t8-dq1.*t2.*t3.*t4.*t15+I.*d.*dq2.*l.*m.*t8+d.*dq2.*l.*t2.*t3.*t8+d.*dq1.*l.*t3.*t4.*t15);\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/simpleWalker/autoGen_heelStrike.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.7401743505760727, "lm_q1q2_score": 0.6443937603021438}} {"text": "function term_mat = zpk2term(z,p,k,T)\n%\n% Utility Function: ZPK2TERM\n%\n% The purpose of this function is to convert zero/pole/gain format into\n% the term matrix format used by the environments\n\n% Author: Craig Borghesani\n% Date: 9/5/94\n% Copyright (c) 1999, Prentice-Hall\n\nnarg_vals = nargin;\nif narg_vals==4,\n if ~length(T),\n narg_vals=3;\n end\nend\n\nctz=length(z);\nctp=length(p);\nct=1;\nterm_mat(1,:) = [k,0,NaN,1];\nterm_mat(2,:) = [0,NaN,NaN,2];\n\nif narg_vals==3,\n while ct<=ctz,\n if z(ct)==0,\n term_mat(2,1)=term_mat(2,1)-1;\n ct=ct+1;\n elseif imag(z(ct))==0,\n term_mat=[term_mat;-z(ct),NaN,NaN,5];\n ct=ct+1;\n else\n re=real(z(ct)); im=imag(z(ct));\n wn=sqrt(re^2+im^2); zta=-re/wn;\n term_mat=[term_mat;zta wn NaN 7];\n ct=ct+2;\n end\n end\n ct=1;\n while ct<=ctp,\n if p(ct)==0,\n term_mat(2,1)=term_mat(2,1)+1;\n ct=ct+1;\n elseif imag(p(ct))==0,\n term_mat=[term_mat;-p(ct),NaN,NaN,4];\n ct=ct+1;\n else\n re=real(p(ct)); im=imag(p(ct));\n wn=sqrt(re^2+im^2); zta=-re/wn;\n term_mat=[term_mat;zta wn NaN 6];\n ct=ct+2;\n end\n end\nelse\n while ct<=ctz,\n if z(ct)==0,\n term_mat(3,1)=term_mat(3,1)-1;\n ct=ct+1;\n elseif imag(z(ct))==0,\n if z(ct)==1,\n term_mat(2,2)=term_mat(2,2)+1;\n else\n term_mat=[term_mat;exp(-z(ct)*T),NaN,NaN,2];\n end\n ct=ct+1;\n else\n z(ct)=log(z(ct))/T;\n re=real(z(ct)); im=imag(z(ct));\n wn=sqrt(re^2+im^2); zta=-re/wn;\n term_mat=[term_mat;zta wn NaN 4];\n ct=ct+2;\n end\n end\n ct=1;\n while ct<=ctp,\n if p(ct)==0,\n term_mat(3,1)=term_mat(3,1)+1;\n ct=ct+1;\n elseif imag(p(ct))==0,\n if p(ct)==1,\n term_mat(2,1)=term_mat(2,1)+1;\n else\n term_mat=[term_mat;exp(-p(ct)*T),NaN,NaN,1];\n end\n ct=ct+1;\n else\n p(ct)=log(p(ct))/T;\n re=real(p(ct)); im=imag(p(ct));\n wn=sqrt(re^2+im^2); zta=-re/wn;\n term_mat=[term_mat;zta wn NaN 3];\n ct=ct+2;\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/38866-controls-tutor/contutor5/zpk2term.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6443532565320184}} {"text": "classdef TP4 < PROBLEM\n% \n% Test problem for robust multi-objective optimization\n% delta --- 0.05 --- Maximum disturbance degree\n% H --- 50 --- Number of disturbances\n\n%------------------------------- Reference --------------------------------\n% A. Gaspar-Cunha, J. Ferreira, and G. Recio, Evolutionary robustness\n% analysis for multi-objective optimization: benchmark problems, Structural\n% and Multidisciplinary Optimization, 2014, 49: 771-793.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n delta; % Maximum disturbance degree\n H; % Number of disturbances\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n [obj.delta,obj.H] = obj.ParameterSet(0.05,50);\n obj.M = 2;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n PopObj(:,1) = (exp(PopDec(:,1))-1)/(exp(1)-1);\n g = 1 + 10*mean(PopDec(:,2:end),2);\n h = sin(4*pi*PopDec(:,1))/15 - PopDec(:,1) + 1;\n PopObj(:,2) = h.*g;\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(~,N)\n x = linspace(0,1,N)';\n R(:,1) = (exp(x)-1)/(exp(1)-1);\n R(:,2) = sin(4*pi*x)/15 - x + 1;\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n %% Calculate the metric value\n function score = CalMetric(obj,metName,Population)\n switch metName\n case {'Mean_IGD','Mean_HV','Worst_IGD','Worst_HV'}\n score = feval(metName,Population,obj);\n otherwise\n score = feval(metName,Population,obj.optimum);\n end\n end\n %% Perturb solutions multiple times\n function PopX = Perturb(obj,PopDec,N)\n if nargin < 3; N = obj.H; end\n Delta = repmat(obj.delta.*(obj.upper-obj.lower),N*size(PopDec,1),1);\n w = UniformPoint(N,obj.D,'Latin');\n Dec = 2*Delta.*w(reshape(repmat(1:end,size(PopDec,1),1),1,[]),:) + repmat(PopDec,N,1) - Delta;\n Dec = obj.CalDec(Dec);\n PopX = SOLUTION(Dec,obj.CalObj(Dec),obj.CalCon(Dec));\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/TP/TP4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6443532516000164}} {"text": "function [assigns, totvalue] = auction(valuematrix)\n\n% [assigns, totvalue] = auction(valuematrix)\n%\n% First column is null assignment - any number of objects can be assigned\n% this\n%\n% Author: Paul Horridge\n\nbidincrement = 1e-6; % choose better later\n[nobj, nhyps] = size(valuematrix); % nhyps includes null hypothesis\nprices = zeros(1, nhyps);\nassigns = ones(nobj, 1);\nhyps2obj = zeros(1, nhyps);\nhappy = false(nobj, 1);\n\n% Repeat while someone unhappy\nwhile any(~happy)\n % Find unhappy person\n i = find(~happy, 1, 'first');\n % Get their net values\n netvals = valuematrix(i,:) - prices;\n [bestval, bestj] = max(netvals);\n if netvals(assigns(i)) >= bestval - bidincrement\n % Check if happy\n happy(i) = true;\n else\n % Get second best hypothesis\n nextval = max(netvals([1:bestj-1 bestj+1:end]));\n % Increase price if required\n if bestj > 1\n prices(bestj) = prices(bestj) + bestval - nextval + bidincrement;\n % De-assign original holder if required\n oldi = hyps2obj(bestj);\n if oldi > 0\n assigns(oldi) = 1;\n happy(oldi) = false; \n end\n end\n % Assign best hypothesis to i\n assigns(i) = bestj;\n hyps2obj(bestj) = i;\n happy(i) = true;\n end\nend\ntotvalue = sum(valuematrix((assigns'-1)*nobj + (1:nobj)));\n", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/_internal/optimisation/auctionx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532390079887}} {"text": "%QUATERNION Quaternion class\n% \n% A quaternion is a compact method of representing a 3D rotation that has\n% computational advantages including speed and numerical robustness.\n% A quaternion has 2 parts, a scalar s, and a vector v and is typically \n% written: q = s . \n%\n% A unit-quaternion is one for which s^2+vx^2+vy^2+vz^2 = 1. It can be \n% considered as a rotation by an angle theta about a unit-vector V in space where \n%\n% q = cos (theta/2) < v sin(theta/2)> \n%\n% Q = Quaternion(X) is a unit-quaternion equivalent to X which can be any\n% of:\n% - orthonormal rotation matrix.\n% - homogeneous transformation matrix (rotation part only).\n% - rotation angle and vector\n%\n% Methods::\n% inv inverse of quaterion\n% norm norm of quaternion\n% unit unitized quaternion\n% plot same options as trplot()\n% interp interpolation (slerp) between q and q2, 0<=s<=1\n% scale interpolation (slerp) between identity and q, 0<=s<=1\n% dot derivative of quaternion with angular velocity w\n% R equivalent 3x3 rotation matrix\n% T equivalent 4x4 homogeneous transform matrix\n% double quaternion elements as 4-vector\n% inner inner product of two quaternions\n%\n% Overloaded operators::\n% q1==q2 test for quaternion equality\n% q1~=q2 test for quaternion inequality\n% q+q2 elementwise sum of quaternions\n% q-q2 elementwise difference of quaternions\n% q*q2 quaternion product\n% q*v rotate vector by quaternion, v is 3x1\n% s*q elementwise multiplication of quaternion by scalar\n% q/q2 q*q2.inv\n% q^n q to power n (integer only)\n%\n% Properties (read only)::\n% s real part\n% v vector part\n%\n% Notes::\n% - Quaternion objects can be used in vectors and arrays.\n%\n% References::\n% - Animating rotation with quaternion curves,\n% K. Shoemake,\n% in Proceedings of ACM SIGGRAPH, (San Fran cisco), pp. 245-254, 1985.\n% - On homogeneous transforms, quaternions, and computational efficiency, \n% J. Funda, R. Taylor, and R. Paul, \n% IEEE Transactions on Robotics and Automation, vol. 6, pp. 382-388, June 1990.\n% - Robotics, Vision & Control,\n% P. Corke, Springer 2011.\n%\n% See also trinterp, trplot.\n\n% TODO\n% properties s, v for the vector case\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\n% TODO\n% constructor handles R, T trajectory and returns vector\n% .r, .t on a quaternion vector??\n\nclassdef Quaternion\n\n properties (SetAccess = private)\n s % scalar part\n v % vector part\n end\n\n methods\n\n function q = Quaternion(a1, a2)\n %Quaternion.Quaternion Constructor for quaternion objects\n % \n % Construct a quaternion from various other orientation representations.\n %\n % Q = Quaternion() is the identitity unit-quaternion 1<0,0,0> representing a null rotation.\n %\n % Q = Quaternion(Q1) is a copy of the quaternion Q1\n %\n % Q = Quaternion([S V1 V2 V3]) is a quaternion formed by specifying directly its 4 elements\n %\n % Q = Quaternion(S) is a quaternion formed from the scalar S and zero vector part: S<0,0,0>\n %\n % Q = Quaternion(V) is a pure quaternion with the specified vector part: 0\n %\n % Q = Quaternion(TH, V) is a unit-quaternion corresponding to rotation of TH about the \n % vector V.\n %\n % Q = Quaternion(R) is a unit-quaternion corresponding to the SO(3)\n % orthonormal rotation matrix R (3x3). If R (3x3xN) is a sequence then Q\n % (Nx1) is a vector of Quaternions corresponding to the elements of R.\n %\n % Q = Quaternion(T) is a unit-quaternion equivalent to the rotational part\n % of the SE(3) homogeneous transform T (4x4). If T (4x4xN) is a sequence\n % then Q (Nx1) is a vector of Quaternions corresponding to the elements of\n % T.\n\n if nargin == 0\n q.v = [0,0,0];\n q.s = 1;\n elseif isa(a1, 'Quaternion')\n % Q = Quaternion(q) from another quaternion\n q = a1;\n elseif nargin == 1\n if isvec(a1, 4)\n % Q = Quaternion([s v1 v2 v3]) from 4 elements\n a1 = a1(:);\n q.s = a1(1);\n q.v = a1(2:4)';\n elseif isrot(a1) || ishomog(a1)\n % Q = Quaternion(R) from a 3x3 or 4x4 matrix\n for i=1:size(a1,3)\n q(i) = Quaternion( tr2q(a1(:,:,i)) );\n end\n\n elseif length(a1) == 3\n % Q = Quaternion(v) from a vector\n\n q.s = 0;\n q.v = a1(:)';\n elseif length(a1) == 1\n % Q = Quaternion(s) from a scalar\n q.s = a1(1);\n q.v = [0 0 0];\n else\n error('RTB:Quaternion:badarg', 'unknown dimension of input');\n end\n elseif nargin == 2\n if isscalar(a1) && isvector(a2)\n % Q = Quaternion(theta, v) from vector plus angle\n q.s = cos(a1/2);\n q.v = sin(a1/2)*unit(a2(:)');\n else\n error ('RTB:Quaternion:badarg', 'bad argument to quaternion constructor');\n end\n \n end\n end\n\n function s = char(q)\n %Quaternion.char Convert to string\n %\n % S = Q.char() is a compact string representation of the quaternion's value\n % as a 4-tuple. If Q is a vector then S has one line per element.\n\n if length(q) > 1\n s = '';\n for qq = q;\n s = char(s, char(qq));\n end\n return\n end\n s = [num2str(q.s), ' < ' ...\n num2str(q.v(1)) ', ' num2str(q.v(2)) ', ' num2str(q.v(3)) ' >'];\n end\n\n\n function display(q)\n %Quaternion.display Display quaternion \n %\n % Q.display() displays a compact string representation of the quaternion's value\n % as a 4-tuple. If Q is a vector then S has one line per element.\n %\n % Notes::\n % - This method is invoked implicitly at the command line when the result\n % of an expression is a Quaternion object and the command has no trailing\n % semicolon.\n %\n % See also Quaternion.char.\n\n\n loose = strcmp( get(0, 'FormatSpacing'), 'loose');\n if loose\n disp(' ');\n end\n disp([inputname(1), ' = '])\n if loose\n disp(' ');\n end\n disp(char(q))\n if loose\n disp(' ');\n end\n end\n\n\n function v = double(q)\n %Quaternion.double Convert a quaternion to a 4-element vector\n %\n % V = Q.double() is a 4-vector comprising the quaternion\n % elements [s vx vy vz].\n\n v = [q.s q.v];\n end\n\n function qi = inv(q)\n %Quaternion.inv Invert a unit-quaternion\n %\n % QI = Q.inv() is a quaternion object representing the inverse of Q.\n\n qi = Quaternion([q.s -q.v]);\n end\n\n function qu = unit(q)\n %Quaternion.unit Unitize a quaternion\n %\n % QU = Q.unit() is a unit-quaternion representing the same orientation as Q.\n %\n % See also Quaternion.norm.\n\n qu = q / norm(q);\n end\n\n function n = norm(q)\n %Quaternion.norm Quaternion magnitude\n %\n % QN = Q.norm(Q) is the scalar norm or magnitude of the quaternion Q. \n %\n % Notes::\n % - This is the Euclidean norm of the quaternion written as a 4-vector.\n % - A unit-quaternion has a norm of one.\n %\n % See also Quaternion.inner, Quaternion.unit.\n\n n = norm(double(q));\n end\n\n function n = inner(q1, q2)\n %Quaternion.inner Quaternion inner product\n %\n % V = Q1.inner(Q2) is the inner (dot) product of two vectors (1x4),\n % comprising the elements of Q1 and Q2 respectively.\n %\n % Notes::\n % - Q1.inner(Q1) is the same as Q1.norm().\n %\n % See also Quaternion.norm.\n\n n = double(q1)*double(q2)';\n end\n\n function q = interp(Q1, Q2, r)\n %Quaternion.interp Interpolate quaternions\n %\n % QI = Q1.interp(Q2, S) is a unit-quaternion that interpolates a rotation \n % between Q1 for S=0 and Q2 for S=1.\n %\n % If S is a vector QI is a vector of quaternions, each element\n % corresponding to sequential elements of S.\n %\n % Notes::\n % - This is a spherical linear interpolation (slerp) that can be interpretted \n % as interpolation along a great circle arc on a sphere.\n % - The value of S is clipped to the interval 0 to 1.\n %\n % References::\n % - Animating rotation with quaternion curves,\n % K. Shoemake,\n % in Proceedings of ACM SIGGRAPH, (San Fran cisco), pp. 245-254, 1985.\n %\n % See also Quaternion.scale, ctraj.\n\n q1 = double(Q1);\n q2 = double(Q2);\n \n\n cosTheta = q1*q2';\n % take shortest path along the great circle, patch by Gauthier Gras\n if cosTheta < 0\n q1 = - q1;\n cosTheta = - cosTheta;\n end;\n \n theta = acos(cosTheta);\n count = 1;\n\n % clip values of r\n r(r<0) = 0;\n r(r>1) = 1;\n \n \n q(length(r)) = Quaternion(); % preallocate space for Quaternion vector\n \n for i=1:length(r)\n if theta == 0\n q(i) = Q1;\n else\n q(i) = Quaternion( (sin((1-r(i))*theta) * q1 + sin(r(i)*theta) * q2) / sin(theta) );\n end\n end\n end\n \n \n function q = scale(Q, r)\n %Quaternion.scale Interpolate rotations expressed by quaternion objects\n %\n % QI = Q.scale(S) is a unit-quaternion that interpolates between a null\n % rotation (identity quaternion) for S=0 to Q for S=1. This is a spherical\n % linear interpolation (slerp) that can be interpretted as interpolation\n % along a great circle arc on a sphere.\n %\n % If S is a vector QI is a vector of quaternions, each element\n % corresponding to sequential elements of S.\n %\n % Notes::\n % - This is a spherical linear interpolation (slerp) that can be interpretted \n % as interpolation along a great circle arc on a sphere.\n %\n % See also Quaternion.interp, ctraj.\n\n\n q2 = double(Q);\n\n if any(r<0) || (r>1)\n error('r out of range');\n end\n q1 = [1 0 0 0]; % identity quaternion\n theta = acos(q1*q2');\n\n if length(r) == 1\n if theta == 0\n q = Q;\n else\n q = Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) ).unit;\n end\n else\n count = 1;\n for R=r(:)'\n if theta == 0\n qq = Q;\n else\n qq = Quaternion( (sin((1-r)*theta) * q1 + sin(r*theta) * q2) / sin(theta) ).unit;\n end\n q(count) = qq;\n count = count + 1;\n end\n end\n end\n\n function e = eq(q1, q2)\n %EQ Test quaternion equality\n %\n % Q1==Q2 is true if the quaternions Q1 and Q2 are equal.\n %\n % Notes::\n % - Overloaded operator '=='.\n % - Note that for unit Quaternions Q and -Q are the equivalent\n % rotation, so non-equality does not mean rotations are not\n % equivalent.\n % - If Q1 is a vector of quaternions, each element is compared to \n % Q2 and the result is a logical array of the same length as Q1.\n % - If Q2 is a vector of quaternions, each element is compared to \n % Q1 and the result is a logical array of the same length as Q2.\n % - If Q1 and Q2 are vectors of the same length, then the result \n % is a logical array of the same length.\n %\n % See also Quaternion.ne.\n if (numel(q1) == 1) && (numel(q2) == 1)\n e = all( eq(q1.double, q2.double) );\n elseif (numel(q1) > 1) && (numel(q2) == 1)\n e = zeros(1, numel(q1));\n for i=1:numel(q1)\n e(i) = q1(i) == q2;\n end\n elseif (numel(q1) == 1) && (numel(q2) > 1)\n e = zeros(1, numel(q2));\n for i=1:numel(q2)\n e(i) = q2(i) == q1;\n end\n elseif numel(q1) == numel(q2)\n e = zeros(1, numel(q1));\n for i=1:numel(q1)\n e(i) = q1(i) == q2(i);\n end\n else\n error('RTB:quaternion:badargs');\n end\n end\n\n function e = ne(q1, q2)\n %NE Test quaternion inequality\n %\n % Q1~=Q2 is true if the quaternions Q1 and Q2 are not equal.\n %\n % Notes::\n % - Overloaded operator '~='\n % - Note that for unit Quaternions Q and -Q are the equivalent\n % rotation, so non-equality does not mean rotations are not\n % equivalent.\n % - If Q1 is a vector of quaternions, each element is compared to \n % Q2 and the result is a logical array of the same length as Q1.\n % - If Q2 is a vector of quaternions, each element is compared to \n % Q1 and the result is a logical array of the same length as Q2.\n % - If Q1 and Q2 are vectors of the same length, then the result \n % is a logical array of the same length.\n %\n % See also Quaternion.eq.\n if (numel(q1) == 1) && (numel(q2) == 1)\n e = all( ne(q1.double, q2.double) );\n elseif (numel(q1) > 1) && (numel(q2) == 1)\n e = zeros(1, numel(q1));\n for i=1:numel(q1)\n e(i) = q1(i) ~= q2;\n end\n elseif (numel(q1) == 1) && (numel(q2) > 1)\n e = zeros(1, numel(q2));\n for i=1:numel(q2)\n e(i) = q2(i) ~= q1;\n end\n elseif numel(q1) == numel(q2)\n e = zeros(1, numel(q1));\n for i=1:numel(q1)\n e(i) = q1(i) ~= q2(i);\n end\n else\n error('RTB:quaternion:badargs');\n end\n end\n\n function qp = plus(q1, q2)\n %PLUS Add quaternions\n %\n % Q1+Q2 is the element-wise sum of quaternion elements.\n %\n % Notes::\n % - Overloaded operator '+'\n % - The result is not guaranteed to be a unit-quaternion.\n %\n % See also Quaternion.minus, Quaternion.mtimes.\n\n if isa(q1, 'Quaternion') && isa(q2, 'Quaternion')\n qp = Quaternion(double(q1) + double(q2));\n end\n end\n\n\n function qp = minus(q1, q2)\n %Quaternion.minus Subtract quaternions\n %\n % Q1-Q2 is the element-wise difference of quaternion elements.\n %\n % Notes::\n % - Overloaded operator '-'\n % - The result is not guaranteed to be a unit-quaternion.\n %\n % See also Quaternion.plus, Quaternion.mtimes.\n\n if isa(q1, 'Quaternion') && isa(q2, 'Quaternion')\n\n qp = Quaternion(double(q1) - double(q2));\n end\n end\n\n function qp = mtimes(q1, q2)\n %Quaternion.mtimes Multiply a quaternion object\n %\n % Q1*Q2 is a quaternion formed by the Hamilton product of two quaternions.\n % Q*V is a vector formed by rotating the vector V by the quaternion Q.\n % Q*S is the element-wise multiplication of quaternion elements by the scalar S.\n %\n % Notes::\n % - Overloaded operator '*'\n % - If the two multiplicands are unit-quaternions, the product will be a\n % unit quaternion.\n %\n % See also Quaternion.mrdivide, Quaternion.mpower, Quaternion.plus, Quaternion.minus.\n\n if isa(q1, 'Quaternion') && isa(q2, 'Quaternion')\n %QQMUL Multiply unit-quaternion by unit-quaternion\n %\n % QQ = qqmul(Q1, Q2)\n %\n % Return a product of unit-quaternions.\n %\n % See also: TR2Q\n\n\n % decompose into scalar and vector components\n s1 = q1.s; v1 = q1.v;\n s2 = q2.s; v2 = q2.v;\n\n % form the product\n qp = Quaternion([s1*s2-v1*v2' s1*v2+s2*v1+cross(v1,v2)]);\n\n elseif isa(q1, 'Quaternion') && isa(q2, 'double')\n\n %QVMUL Multiply vector by unit-quaternion\n %\n % VT = qvmul(Q, V)\n %\n % Rotate the vector V by the unit-quaternion Q.\n %\n % See also: QQMUL, QINV\n\n if length(q2) == 3\n qp = q1 * Quaternion([0 q2(:)']) * inv(q1);\n qp = qp.v(:);\n elseif length(q2) == 1\n qp = Quaternion( double(q1)*q2);\n else\n error('quaternion-vector product: must be a 3-vector or scalar');\n end\n\n elseif isa(q2, 'Quaternion') && isa(q1, 'double')\n if length(q1) == 3\n qp = q2 * Quaternion([0 q1(:)']) * inv(q2);\n qp = qp.v;\n elseif length(q1) == 1\n qp = Quaternion( double(q2)*q1);\n else\n error('quaternion-vector product: must be a 3-vector or scalar');\n end\n end\n end\n\n function qp = mpower(q, p)\n %Quaternion.mpower Raise quaternion to integer power\n %\n % Q^N is the quaternion Q raised to the integer power N.\n %\n % Notes::\n % - Overloaded operator '^'\n % - Computed by repeated multiplication.\n % - If the argument is a unit-quaternion, the result will be a\n % unit quaternion.\n %\n % See also Quaternion.mrdivide, Quaternion.mpower, Quaternion.plus, Quaternion.minus.\n\n % check that exponent is an integer\n if (p - floor(p)) ~= 0\n error('quaternion exponent must be integer');\n end\n\n qp = q;\n\n % multiply by itself so many times\n for i = 2:abs(p)\n qp = qp * q;\n end\n\n % if exponent was negative, invert it\n if p<0\n qp = inv(qp);\n end\n end\n\n function qq = mrdivide(q1, q2)\n %Quaternion.mrdivide Quaternion quotient.\n %\n % Q1/Q2 is a quaternion formed by Hamilton product of Q1 and inv(Q2).\n % Q/S is the element-wise division of quaternion elements by the scalar S.\n %\n % Notes::\n % - Overloaded operator '/'\n % - If the dividend and divisor are unit-quaternions, the quotient will be a\n % unit quaternion.\n %\n % See also Quaternion.mtimes, Quaternion.mpower, Quaternion.plus, Quaternion.minus.\n\n if isa(q2, 'Quaternion')\n % qq = q1 / q2\n % = q1 * qinv(q2)\n\n qq = q1 * inv(q2);\n elseif isa(q2, 'double')\n qq = Quaternion( double(q1) / q2 );\n end\n end\n\n\n function plot(Q, varargin)\n %Quaternion.plot Plot a quaternion object \n %\n % Q.plot(options) plots the quaternion as an oriented coordinate frame.\n %\n % Options::\n % Options are passed to trplot and include:\n %\n % 'color',C The color to draw the axes, MATLAB colorspec C\n % 'frame',F The frame is named {F} and the subscript on the axis labels is F.\n % 'view',V Set plot view parameters V=[az el] angles, or 'auto' \n % for view toward origin of coordinate frame\n %\n % See also trplot.\n\n %axis([-1 1 -1 1 -1 1])\n\n trplot( Q.R, varargin{:});\n drawnow\n end\n\n function r = R(q)\n %Quaternion.R Convert to orthonormal rotation matrix\n %\n % R = Q.R() is the equivalent SO(3) orthonormal rotation matrix (3x3). If\n % Q represents a sequence (Nx1) then R is 3x3xN.\n %\n\n r = zeros(3,3,numel(q));\n for i=1:numel(q)\n r(:,:,i) = t2r( q2tr(q(i)) );\n end\n end\n\n function t = T(q)\n %Quaternion.T Convert to homogeneous transformation matrix\n %\n % T = Q.T() is the equivalent SE(3) homogeneous transformation matrix\n % (4x4). If Q represents a sequence (Nx1) then T is 4x4xN.\n %\n % Notes:\n % - Has a zero translational component.\n t = zeros(4,4,numel(q));\n for i=1:numel(q)\n t(:,:,i) = q2tr(q(i));\n end\n end\n\n function qd = dot(q, omega)\n %Quaternion.dot Quaternion derivative\n %\n % QD = Q.dot(omega) is the rate of change of a frame with attitude Q and\n % angular velocity OMEGA (1x3) expressed as a quaternion.\n E = q.s*eye(3,3) - skew(q.v);\n omega = omega(:);\n qd = Quaternion([-0.5*q.v*omega; 0.5*E*omega]);\n end\n end % methods\nend % classdef\n\n%TR2Q Convert homogeneous transform to a unit-quaternion\n%\n% Q = tr2q(T)\n%\n% Return a unit-quaternion corresponding to the rotational part of the\n% homogeneous transform T.\n%\n% See also: Q2TR\n\nfunction q = tr2q(t)\n\n if ishomog(t)\n t = t2r(t);\n end\n qs = sqrt(trace(t)+1)/2.0;\n kx = t(3,2) - t(2,3); % Oz - Ay\n ky = t(1,3) - t(3,1); % Ax - Nz\n kz = t(2,1) - t(1,2); % Ny - Ox\n\n if (t(1,1) >= t(2,2)) && (t(1,1) >= t(3,3)) \n kx1 = t(1,1) - t(2,2) - t(3,3) + 1; % Nx - Oy - Az + 1\n ky1 = t(2,1) + t(1,2); % Ny + Ox\n kz1 = t(3,1) + t(1,3); % Nz + Ax\n add = (kx >= 0);\n elseif (t(2,2) >= t(3,3))\n kx1 = t(2,1) + t(1,2); % Ny + Ox\n ky1 = t(2,2) - t(1,1) - t(3,3) + 1; % Oy - Nx - Az + 1\n kz1 = t(3,2) + t(2,3); % Oz + Ay\n add = (ky >= 0);\n else\n kx1 = t(3,1) + t(1,3); % Nz + Ax\n ky1 = t(3,2) + t(2,3); % Oz + Ay\n kz1 = t(3,3) - t(1,1) - t(2,2) + 1; % Az - Nx - Oy + 1\n add = (kz >= 0);\n end\n\n if add\n kx = kx + kx1;\n ky = ky + ky1;\n kz = kz + kz1;\n else\n kx = kx - kx1;\n ky = ky - ky1;\n kz = kz - kz1;\n end\n nm = norm([kx ky kz]);\n if nm == 0\n q = Quaternion([1 0 0 0]);\n else\n s = sqrt(1 - qs^2) / nm;\n qv = s*[kx ky kz];\n\n q = Quaternion([qs qv]);\n\n end\nend\n\n\n%Q2TR Convert unit-quaternion to homogeneous transform\n%\n% T = q2tr(Q)\n%\n% Return the rotational homogeneous transform corresponding to the unit\n% quaternion Q.\n%\n% See also: TR2Q\n\nfunction t = q2tr(q)\n\n q = double(q);\n s = q(1);\n x = q(2);\n y = q(3);\n z = q(4);\n\n r = [ 1-2*(y^2+z^2) 2*(x*y-s*z) 2*(x*z+s*y)\n 2*(x*y+s*z) 1-2*(x^2+z^2) 2*(y*z-s*x)\n 2*(x*z-s*y) 2*(y*z+s*x) 1-2*(x^2+y^2) ];\n t = eye(4,4);\n t(1:3,1:3) = r;\n t(4,4) = 1;\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/Quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6443340206305503}} {"text": "function x = mono_next_grlex ( m, x )\n\n%*****************************************************************************80\n%\n%% MONO_NEXT_GRLEX: grlex next monomial.\n%\n% Discussion:\n%\n% Example:\n%\n% M = 3\n%\n% # X(1) X(2) X(3) Degree\n% +------------------------\n% 1 | 0 0 0 0\n% |\n% 2 | 0 0 1 1\n% 3 | 0 1 0 1\n% 4 | 1 0 0 1\n% |\n% 5 | 0 0 2 2\n% 6 | 0 1 1 2\n% 7 | 0 2 0 2\n% 8 | 1 0 1 2\n% 9 | 1 1 0 2\n% 10 | 2 0 0 2\n% |\n% 11 | 0 0 3 3\n% 12 | 0 1 2 3\n% 13 | 0 2 1 3\n% 14 | 0 3 0 3\n% 15 | 1 0 2 3\n% 16 | 1 1 1 3\n% 17 | 1 2 0 3\n% 18 | 2 0 1 3\n% 19 | 2 1 0 3\n% 20 | 3 0 0 3\n%\n% Thanks to Stefan Klus for pointing out a discrepancy in a previous\n% version of this code, 05 February 2015.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer X(M), the current monomial.\n% The first item is X = [ 0, 0, ..., 0, 0 ].\n%\n% Output, integer X(M), the next monomial.\n%\n\n%\n% Ensure that 1 <= M.\n%\n if ( m < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_NEXT_GRLEX - Fatal error!' );\n fprintf ( 1, ' M < 1\\n' );\n error ( 'MONO_NEXT_GRLEX - Fatal error!' );\n end\n%\n% Ensure that 0 <= XC(I).\n%\n for i = 1 : m\n if ( x(i) < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_NEXT_GRLEX - Fatal error!' );\n fprintf ( 1, ' X(I) < 0\\n' );\n error ( 'MONO_NEXT_GRLEX - Fatal error!' );\n end\n end\n%\n% Find I, the index of the rightmost nonzero entry of X.\n%\n i = 0;\n for j = m : -1 : 1\n if ( 0 < x(j) )\n i = j;\n break\n end\n end \n%\n% set T = X(I)\n% set X(I) to zero,\n% increase X(I-1) by 1,\n% increment X(M) by T-1.\n%\n if ( i == 0 )\n x(m) = 1;\n return\n elseif ( i == 1 )\n t = x(1) + 1;\n im1 = m;\n elseif ( 1 < i )\n t = x(i);\n im1 = i - 1;\n end\n\n x(i) = 0;\n x(im1) = x(im1) + 1;\n x(m) = x(m) + t - 1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/monomial/mono_next_grlex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.6443340157033077}} {"text": "function xhfd=hfd(x,kmax)\n%function xhfd=hfd(x,kmax)\n%Input:\n%x: (either column or row) vector of length N\n%kmax: maximum value of k\n%Output:\n%xhfd: Higuchi fractal dimension of x\n\nif ~exist('kmax','var')||isempty(kmax),\n kmax=5;\nend;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nx=x(:)';\nN=length(x);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nLmk=zeros(kmax,kmax);\nfor k=1:kmax,\n for m=1:k,\n Lmki=0;\n for i=1:fix((N-m)/k),\n Lmki=Lmki+abs(x(m+i*k)-x(m+(i-1)*k));\n end;\n Ng=(N-1)/(fix((N-m)/k)*k);\n Lmk(m,k)=(Lmki*Ng)/k; % Here is the problem in the code by Mr. Tikkuhirvi & Mr. Aino\n end;\nend;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nLk=zeros(1,kmax);\nfor k=1:kmax,\n Lk(1,k)=sum(Lmk(1:k,k))/k;\nend;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nlnLk=log(Lk);\nlnk=log(1./[1:kmax]);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nb=polyfit(lnk,lnLk,1);\nxhfd=b(1);\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/30119-complete-higuchi-fractal-dimension-algorithm/hfd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6443331737169465}} {"text": "function [tuples,fStar,qStar,u,exitCode]=assign3D(C,maximize,subgradMethod,subgradParams,maxIter,AbsTol,RelTol)\n%%ASSIGN3D Approximate the solution to the operations research axial 3D\n% assignment problem using a dual-primal Lagrangian relaxation \n% technique. Such problems are NP-hard. The optimization problem\n% being solved is\n% minimize (or maximize)\n% \\sum_{i=1}^{n1}\\sum_{j=1}^{n2}\\sum_{k=1}^{n3}C_{i,j,k}*\\rho_{i,j,k}\n% subject to\n% \\sum_{i=1}^{n1}\\sum_{j=1}^{n2}\\rho_{i,j,k}<=1 for all k\n% \\sum_{i=1}^{n1}\\sum_{k=1}^{n3}\\rho_{i,j,k}<=1 for all j\n% \\sum_{j=1}^{n2}\\sum_{k=1}^{n3}\\rho_{i,j,k} =1 for all i\n% \\rho_{i,j,k} = 0 or 1\n% assuming that n1<=n2<=n3, and C is an n1Xn2Xn3 cost matrix.\n% This is equivalent to the optimization problem\n% min (or max) sum_{i} C(i,phi_2(i),phi_3(i))\n% where phi_2 and phi_3 are length n1 arrangements of n2 and n3\n% items over which the minimization is performed.\n%\n%INPUTS: C An n1Xn2Xn3 cost hypermatrix with n1<=n2<=n3. C cannot contain\n% any NaNs and the largest finite element minus the smallest\n% element is a finite quantity (does not overflow) when performing\n% minimization and where the smallest finite element minus the\n% largest element is finite when performing maximization.\n% Forbidden assignments can be given costs of +Inf for\n% minimization and -Inf for maximization. During minimization,\n% there should be no elements with -Inf cost and no elements with\n% +Inf cost during maximization.\n% maximize If true, the minimization problem is transformed into a\n% maximization problem. The default if this parameter is omitted\n% or an empty matrix is passed is false.\n% subgradMethod A parameter indicating the subgradient optimization\n% algorithm to use. Possible values are:\n% 0 Polyak's Method from [2]. (The default if omitted or an empty\n% matrix is passed) In this method, for minimization, the dual\n% variables are updated as uNew=u+gamma*(fStar-q)/norm(g)^2*g,\n% where g is the subgradient, q is the current dual cost, and g\n% is the subgradient vector. gamma is a design parameter.\n% 1 Bragin's Method from [3]. The dual update for minimization is\n% uNew=u+alpha*g\n% where during the first step, alpha=(fStar-q)/norm(g)^2 and for\n% subsequent steps it is\n% alpha=(1-1/(M*k^(1-1/k^r)))*alphaPrev*norm(gPrev)/norm(g)\n% where alphaPrev is alpha for the previous step, k is the step\n% number (starting at 0), gPrev is the subgradient before the\n% current step and M and r are design parameters.\n% 2 Bertsekas' Heuristic Method from [4]. The update is\n% uNew=u+alpha*g\n% where alpha=((1+a/beta^b)*qMax-q)/norm(g)^2 where qMax is the\n% highest dual cost value encountered thus far (when\n% minimizing), a and b are design parameters, and beta is a\n% value that increases or decreases in the algorithm depending\n% on whether or not there was an improvement in the best dual\n% cost found after the last step.\n% 3 Shor's Space Dilation Algorithm from [5].\n% The update is\n% uNew=u+alpha*H*g;\n% where alpha=(2*M/(M+1))*(fStar-q)/norm(d), d=g and H is a\n% matrix that also depends on M and d, which is a design\n% parameter. Also, after NR iterations, the recursive turms that\n% go into H reset.\n% 4 The r Space Dilation Algorithm from [5]. This is the same as 3\n% except d=g-gPrev except for the first iteration and if\n% g=gPrev, in which case d=g.\n% subgradParams This is a structure that takes the design parameters for\n% the selected cubgradient algorithm. Possible fields of the\n% structure as well as default values depend on the selected\n% subgradient method and are:\n% Method 0: 'gamma' with default 1.\n% Method 1: 'M' and 'r' with defaults 2.8 and 0.06.\n% Method 2: 'a and 'b' with defaults 0.3 and 1.5.\n% Method 3,4: 'M', 'NR', and 'normBound' with defaults 2, n3, and\n% eps(). normBound is such that if norm(B.'*d) in the\n% computation of the matrix H is <= normBound, then B\n% is reset to the identity matrix.\n% maxIter The maximum number of iterations to perform. The default value\n% if this parameter is omitted or an empty matrix is passed is 20.\n% AbsTol The absolute duality gap to use for convergence determiniation.\n% Convergence is declared if (fStar-qStar)<=AbsTol, where if\n% minimizing, fStar is the smallest value of the primal function\n% found and qStar is the highest value of the dual cost function\n% found. The default if omitted or an empty matrix is passed is\n% 1e-10.\n% RelTol The relative duality gap to use for convergence determiniation.\n% Convergence is declared if (fStar-qStar)<=RelTol*abs(qStar). The\n% default if omitted or an empty matrix is passed is 0.05.\n%\n%OUTPUTS: tuples A 3Xn1 matrix where tuples(:,i) is the ith assigned tuple\n% in C as described above. An empty matrix is returned if\n% the problem is infeasible or the heuristic to obtain a\n% feasible solution failed.\n% fStar The cost of the assignment in tuples. This is the sum of\n% the values of the assigned elements in C.\n% qStar The value of the best dual solution found. The absolute\n% duality gap is fStar-qStar and the relative duality gap is\n% abs(fStar-qStar)/abs(qStar)\n% u The n3X1 vector of dual variables.\n% exitCode A parameter indicating how the algorithm terminated.\n% Possible values are:\n% -3 A non-finite number arose in the dual variables, so the\n% algorithm stopped.\n% -2 The algorithm did not converge within the alotted\n% number of iterations. However, a valid feasible\n% assignment was found.\n% -1 A subproblem in computing the dual or in obtaining a\n% feasible primal solution was infeasible.The output\n% tuples will be an empty matrix.\n% >=0 Values that are zero or positive indicate the\n% convergence was obtained and the returned value is the\n% number of iterations.\n%\n%This function implements the algorithm of [1], but modified so that it\n%does not have any unconstrained indices and offering different subgradient\n%methods. We are solving the \"operations research\" 3D assignment problem\n%rather than the \"data fusion\" 3D assignment problem of [1].\n%\n%EXAMPLE:\n%Here is an example using a random problem:\n% n1=10;\n% n2=12;\n% n3=15;\n% C=randn(n1,n2,n3);\n% maximize=false;\n% [tuples,fStar,qStar,u,exitCode]=assign3D(C,maximize)\n%\n%REFERENCES:\n%[1] K. Pattipati, S. Deb, Y. Bar-Shalom, and R. B. Washburn Jr., \"A\n% new relaxation algorithm and passive sensor data association,\" IEEE\n% Transactions on Automatic Control, vol. 37, no. 2, pp. 198-213, Feb.\n% 1992.\n%[2] B. T. Polyak, \"Minimization of unsmooth functionals,\" USSR\n% Computational Mathematics and Mathematical Physics, vol. 9, no. 3, pp.\n% 14-29, 1969.\n%[3] M. A. Bragin, P. B. Luh, J. H. Yan, N. Yu, and G. A. Stern,\n% \"Convergence of the surrogate Lagrangian relaxation method,\" Journal\n% of Optimization Theory and Applications, vol. 164, no. 1, pp. 173-201,\n% Jan. 2015.\n%[4] D. P. Bertsekas, Nonlinear Programming, 3rd ed. Belmont, MA: Athena\n% Scientific, 2016, Chapter 7.5.\n%[5] N. Z. Shor, \"Utilization of the operation of space dilation in the\n% minimization of convex functions,\" Cybernetics, vol. 6, no. 1, pp. 7-\n% 15, Dec. 1972.\n%\n%February 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(maximize))\n maximize=false; \nend\n\nif(nargin<3||isempty(subgradMethod))\n subgradMethod=0; \nend\n\nif(nargin<4)\n subgradParams=[];\nend\n\nif(nargin<5||isempty(maxIter))\n maxIter=20;\nend\n\nif(nargin<6||isempty(AbsTol))\n AbsTol=1e-10;\nend\n\nif(nargin<7||isempty(RelTol))\n RelTol=0.05;\nend\n\nnVals=size(C);\n\n%Deal with the special case of C being scalar.\nif(isscalar(C))\n tuples=[1;1;1];\n fStar=C(1);\n qStar=fStar;\n u=0;\n exitCode=0;\n return;\nend\n\nif(isempty(C))%The empty matrix special case.\n tuples=[];\n fStar=0;\n qStar=0;\n u=[];\n exitCode=0;\n return;\nend\n\nif(maximize)\n C=-C;\nend\n\nif(length(nVals)<3||~(nVals(1)<=nVals(2)&&nVals(2)<=nVals(3)))\n error('It is required that size(C,1)<=size(C,2)<=size(C,3)')\nend\n\nn1=nVals(1);\nn2=nVals(2);\nn3=nVals(3);\n\nif((n1==n2)&&(n2==n3))\n unconstU=true;\nelse\n unconstU=false;\nend\n\n%Get the parameters and initial values for the chosen subgradient method.\nswitch(subgradMethod)\n case 0%Polyak's method\n gammaParam=1;\n \n if(nargin>3&&~isempty(subgradParams))\n if(isfield(subgradParams,'gamma'))\n gammaParam=subgradParams.gamma;\n end\n end\n case 1%Bragin's Method\n M=2.8;\n r=0.06;\n gNormPrev=[];\n alphaPrev=[];\n \n if(nargin>3&&~isempty(subgradParams))\n if(isfield(subgradParams,'M'))\n M=subgradParams.M;\n end\n \n if(isfield(subgradParams,'r'))\n r=subgradParams.r;\n end\n end\n case 2%Bertsekas' Heuristic Method\n a=0.3;\n b=1.5;\n beta=1;%Initialize\n \n if(nargin>3&&~isempty(subgradParams))\n if(isfield(subgradParams,'a'))\n a=subgradParams.a;\n end\n \n if(isfield(subgradParams,'b'))\n b=subgradParams.b;\n end\n end\n case 3%Shor's Space Dilation Algorithm.\n NR=n3;\n M=2;\n rho=(M-1)/(M+1);\n normBound=eps();\n\n B=eye(n3,n3);%Allocate and initialize\n dPrev=[];\n\n if(nargin>3&&~isempty(subgradParams))\n if(isfield(subgradParams,'NR'))\n NR=subgradParams.NR;\n end\n\n if(isfield(subgradParams,'M'))\n M=subgradParams.M;\n end\n\n if(isfield(subgradParams,'normBound'))\n normBound=subgradParams.normBound;\n end\n end\n case 4%The r Space Dilation Algorithm.\n NR=n3;\n M=2;\n rho=(M-1)/(M+1);\n normBound=eps();\n \n B=eye(n3,n3);%Allocate and initialize\n gPrev=[];\n dPrev=[];\n \n if(nargin>3&&~isempty(subgradParams))\n if(isfield(subgradParams,'NR'))\n NR=subgradParams.NR;\n end\n \n if(isfield(subgradParams,'M'))\n M=subgradParams.M;\n end\n \n if(isfield(subgradParams,'normBound'))\n normBound=subgradParams.normBound;\n end\n end\n otherwise\n error('Invalid subgradient method specified.')\nend\n\nu=zeros(n3,1);%Allocate and initialize the dual variables.\n%Allocate space for the return tuples.\ntuples=zeros(3,n1);\n\n%qStar is the best (maximum) dual cost encountered thus far.\nqStar=-Inf;\n\n%fStar is the best (minimum) feasible primal cost encountered\n%thus far.\nfStar=Inf;\n%If the loop exits without convergence, then exitCode is not modified.\nexitCode=-2;\nfor k=0:(maxIter-1)\n%%%%%%\n%DUAL COST AND SUBGRADIENT UPDATE. SEE FIG. 3 IN [1].\n%%%%%%\n %Note that d3=C;\n [d2,gamma2]=min(bsxfun(@plus,C,reshape(u,[1,1,n3])),[],3);\n \n %gamma1 is the columns for rows (nonzero elements in omega).\n [gamma1, ~, minVal]=assign2D(d2,false);\n \n %If the subproblem is infeasible.\n if(isempty(gamma1))\n tuples=[];\n fStar=[];\n qStar=[];\n u=[];\n exitCode=-1;\n return\n end\n\n q=minVal-sum(u);%The dual cost.\n \n %Keep track of the maximum q value. This is used for testing\n %convergence. \n if(q>qStar)\n qStar=q;\n\n %The duality gap.\n costGap=fStar-qStar;\n \n %The correctness of this on the first iterations requires proper\n %handling of NaNs.\n if(costGap<=AbsTol||(costGapqStarPrev, then qStar will be set to q,\n %so the comparison q \n% Multiobjective steepest descent\n% step --- 0.1 --- Step size\n\n%------------------------------- Reference --------------------------------\n% X. Liu and A. C. Reynolds, A multiobjective steepest descent method with\n% applications to optimal well control, Computational Geosciences, 2016,\n% 20: 355-374.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB Platform\n% for Evolutionary Multi-Objective Optimization [Educational Forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n function main(Algorithm,Problem)\n %% Parameter setting\n step = Algorithm.ParameterSet(0.1);\n \n %% Generate random population\n Population = Problem.Initialization(Problem.N);\n Archive = UpdateArchive(Population,Problem.N);\n step0 = step;\n \n %% Optimization\n while Algorithm.NotTerminated(Archive)\n for i = 1 : Problem.N\n gk = FiniteDifference(Problem,Population(i)); \n gk1 = norm(gk(:,1));\n gk2 = norm(gk(:,2));\n if gk1 <= gk2\n gs = gk(:,1);\n gl = gk(:,2);\n else\n gs = gk(:,2);\n gl = gk(:,1);\n end\n if gs'*(gs-gl) <= 0\n d = -gs/norm(gs);\n else\n D = (((norm(gl).^2-gs'*gl)/(norm(gs).^2-gs'*gl))*(-gs))-gl;\n d = D/norm(D);\n end\n Offspringdec = Population(i).dec+step*d';\n Offspring = Problem.Evaluation(Offspringdec);\n Archive = UpdateArchive([Archive,Offspring],Problem.N);\n if ~any(Offspring.obj0)\n df = Problem.CalConGrad(X.dec)';\n else\n df = Problem.CalObjGrad(X.dec)';\n end\nend\n\nfunction P = UpdateArchive(P,N)\n P = P(NDSort(P.objs,P.cons,1)==1);\n if length(P) > N\n Choose = true(1,length(P));\n Dis = pdist2(P.objs,P.objs);\n Dis(logical(eye(length(Dis)))) = inf;\n while sum(Choose) > N\n Remain = find(Choose);\n Temp = sort(Dis(Remain,Remain),2);\n [~,Rank] = sortrows(Temp);\n Choose(Remain(Rank(1))) = false;\n end\n P = P(Choose);\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/MOSD/MOSD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6443331489029963}} {"text": "% This script compares three elliptical extended object trackig methods.\n% It gives Fig.2 in\n% S. Yang and M. Baum Extended Kalman Filter for Extended Object Tracking.\n% Proceedings of the 2017 IEEE International Conference on Acoustics, Speech,\n% and Signal Processing (ICASSP), New Orleans, USA, 2017.\n\n\nclose all\nclc\nclear\ndbstop warning\nset(0,'defaulttextinterpreter','latex')\n\n%% parameters\nmotionmodel = {'NCV'};\n% nr of measurements we get follows a possion distribution\npossion_lambda = 5;\nH = [1 0 0 0; 0 1 0 0]; % matrix maps kinematic state into position\nH_velo = [zeros(2,2),eye(2)];\n% parameters for EKF\nC_h = diag([1/4, 1/4]);\nC_v = 0.2*diag([100^2,20^2]);\n\n\n%% generate ground truth\n[gt_kin,gt_par, time_steps, delta_t] =get_ground_truth;\n\n%% setting prior\nhat_r0 = [100,100,5,-8]'; % kinematic state: position and velocity\nhat_p0 = [-pi/3,200,90]'; % shape variable: orientation and semi-axes lengths\nhat_x0 = [hat_r0; hat_p0];\n\nC_r0 = blkdiag( 900*eye(2),16*eye(2));\nC_p0 = blkdiag(0.02*eye(1),400*eye(2));\nC_x0 = blkdiag(C_r0,C_p0);\n\n\n\nAr = [eye(2),delta_t*eye(2); zeros(2,2),eye(2)];\nAp = eye(3);\n\nC_w_r = blkdiag(100*eye(2),eye(2)); % process noise covariance for kinematic state\nC_w_p = blkdiag(0.04,0.5*eye(2)); % process noise covariance for shape variable\n\nhat_r_EKF = [100,100,5,-8]'; % kinematic state: position and velocity\nhat_p_EKF = [-pi/3,200,90]';\nCr_EKF = C_r0;\nCp_EKF = C_p0;\n\n% parameters for SOEKF\nsgh1 = 1/4;\nsgh2 = 1/4;\nC_w = blkdiag(C_w_r, C_w_p);\nAx = blkdiag(Ar,Ap);\n\nhat_x_SOEKF = hat_x0;\nCx_SOEKF = C_x0;\n\n[ f_g_ekf2, f_jacobian_ekf2, f_hessian_ekf2] = get_jacobian_hessian(motionmodel,C_h);\n\n\n% parameters for Random Matrix\nalpha = 50;\ntau = 10;\nT = 10;\nconst_z = 1/4;\nhat_x_RMM = hat_r0;\nhat_X_RMM = get_random_matrix_state(hat_p0);\nCx_RMM = C_r0;\n\nfigure;\n\nhold on\n\nfor t = 1:time_steps\n N = poissrnd(possion_lambda);\n while N == 0\n N = poissrnd(possion_lambda);\n end\n disp(['time step:' num2str(t) ', ' num2str(N) ' measurements']);\n \n %% ------------------get measurements------------------------------------\n gt_cur_par = gt_par(:,t);\n gt_velo = H_velo*gt_kin(:,t);\n gt_rot = [cos(gt_cur_par(3)), -sin(gt_cur_par(3)); sin(gt_cur_par(3)), cos(gt_cur_par(3))];\n gt_len = gt_cur_par(4:5);\n y = zeros(2,N);\n for n = 1:N\n h_noise(n,:) = -1 + 2.*rand(1,2);\n while norm(h_noise(n,:)) > 1\n h_noise(n,:) = -1 + 2.*rand(1,2);\n end\n y(:,n) = H*gt_kin(:,t) + gt_rot*diag(gt_len)*h_noise(n,:)'+ mvnrnd([0 0], C_v, 1)';\n end\n %% update RMM\n meas_mean = mean(y,2);\n meas_spread = (N - 1) * cov(y');\n [hat_x_RMM, hat_X_RMM, C_x_RMM, alpha_update]...\n = updateRMM(hat_x_RMM, hat_X_RMM, Cx_RMM, alpha,meas_mean, ...\n meas_spread, C_v,N,H,const_z);\n \n [~, len_RMM,ang_RMM] = get_random_matrix_ellipse(hat_X_RMM); \n rmm_par = [H*hat_x_RMM; ang_RMM;len_RMM];\n %% update EKF and SOEKF\n for n = 1:N\n [hat_x_SOEKF, Cx_SOEKF] = updateSOEKF(hat_x_SOEKF, Cx_SOEKF, y(:,n),...\n f_g_ekf2, f_jacobian_ekf2, f_hessian_ekf2, C_v, C_h);\n [ hat_r_EKF, Cr_EKF,hat_p_EKF, Cp_EKF ] = updateEKF(hat_r_EKF, Cr_EKF, hat_p_EKF, Cp_EKF, y(:,n), C_v, C_h);\n \n end\n \n \n %% visulization udpated shapes\n if mod(t,3)==1\n meas_points=plot( y(1,:)/1000, y(2,:)/1000, '.k','lineWidth',0.5);\n hold on\n gt_plot = plot_extent([gt_cur_par(1:2)/1000; gt_cur_par(3);gt_cur_par(4:5)/1000], '-','k',1);\n axis equal\n \n est_plot_rmm = plot_extent([rmm_par(1:2)/1000;rmm_par(3);rmm_par(4:5)/1000],'-','g',1);\n est_plot_ekf2 = plot_extent([hat_x_SOEKF(1:2)/1000;hat_x_SOEKF(5);hat_x_SOEKF(6:7)/1000],'-', 'r', 1);\n est_plot_ekf = plot_extent([H*hat_r_EKF/1000;hat_p_EKF(1);hat_p_EKF(2:3)/1000],'-', 'b', 1);\n end\n \n \n %% predict RMM\n [hat_x_RMM, hat_X_RMM,Cx_RMM, alpha] = predictRMM(....\n hat_x_RMM, hat_X_RMM, C_x_RMM, alpha_update,Ar,C_w_r,T,tau);\n if alpha_update<=2\n error('alpha<2')\n end\n %% predict SOEKF\n [hat_x_SOEKF,Cx_SOEKF] = predictSOEKF(Ax,hat_x_SOEKF,Cx_SOEKF,C_w);\n %% predict EKF\n [hat_r_EKF,Cr_EKF, hat_p_EKF,Cp_EKF] = predictEKF(Ar,Ap, hat_r_EKF, hat_p_EKF, Cr_EKF, Cp_EKF,C_w_r, C_w_p);\n \nend\nlegend([meas_points,gt_plot,est_plot_rmm, est_plot_ekf2,est_plot_ekf],...\n {'measurement','ground truth','random matrix','SOEKF','EKF'})\nbox on\ngrid on\nylim([-3200 1200]/1000)\nxlim([-200 8000]/1000)\n", "meta": {"author": "Fusion-Goettingen", "repo": "ExtendedObjectTracking", "sha": "716c66f078162f7891a40e5ef664643fd74b9101", "save_path": "github-repos/MATLAB/Fusion-Goettingen-ExtendedObjectTracking", "path": "github-repos/MATLAB/Fusion-Goettingen-ExtendedObjectTracking/ExtendedObjectTracking-716c66f078162f7891a40e5ef664643fd74b9101/MEM_EKF/simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6443212265878394}} {"text": "function [path, totalCost, farthestPreviousHop, farthestNextHop] = dijkstra(n, netCostMatrix, s, d, farthestPreviousHop, farthestNextHop)\n% path: the list of nodes in the path from source to destination;\n% totalCost: the total cost of the path;\n% farthestNode: the farthest node to reach for each node after performing\n% the routing;\n% n: the number of nodes in the network;\n% s: source node index;\n% d: destination node index;\n\n\n% clear;\n% noOfNodes = 50;\n% rand('state', 0);\n% figure(1);\n% clf;\n% hold on;\n% L = 1000;\n% R = 200; % maximum range;\n% netXloc = rand(1,noOfNodes)*L;\n% netYloc = rand(1,noOfNodes)*L;\n% for i = 1:noOfNodes\n% plot(netXloc(i), netYloc(i), '.');\n% text(netXloc(i), netYloc(i), num2str(i));\n% for j = 1:noOfNodes\n% distance = sqrt((netXloc(i) - netXloc(j))^2 + (netYloc(i) - netYloc(j))^2);\n% if distance <= R\n% matrix(i, j) = 1; % there is a link;\n% line([netXloc(i) netXloc(j)], [netYloc(i) netYloc(j)], 'LineStyle', ':');\n% else\n% matrix(i, j) = inf;\n% end;\n% end;\n% end;\n% \n% \n% activeNodes = [];\n% for i = 1:noOfNodes,\n% % initialize the farthest node to be itself;\n% farthestPreviousHop(i) = i; % used to compute the RTS/CTS range;\n% farthestNextHop(i) = i;\n% end;\n% \n% [path, totalCost, farthestPreviousHop, farthestNextHop] = dijkstra(noOfNodes, matrix, 1, 15, farthestPreviousHop, farthestNextHop);\n% path\n% totalCost\n% if length(path) ~= 0\n% for i = 1:(length(path)-1)\n% line([netXloc(path(i)) netXloc(path(i+1))], [netYloc(path(i)) netYloc(path(i+1))], 'Color','r','LineWidth', 0.50, 'LineStyle', '-.');\n% end;\n% end;\n% hold off;\n% return;\n \n\n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% all the nodes are un-visited;\nvisited(1:n) = 0;\n\ndistance(1:n) = inf; % it stores the shortest distance between each node and the source node;\nparent(1:n) = 0;\n\ndistance(s) = 0;\nfor i = 1:(n-1),\n temp = [];\n for h = 1:n,\n if visited(h) == 0 % in the tree;\n temp=[temp distance(h)];\n else\n temp=[temp inf];\n end\n end;\n [t, u] = min(temp); % it starts from node with the shortest distance to the source;\n visited(u) = 1; % mark it as visited;\n for v = 1:n, % for each neighbors of node u;\n if ( ( netCostMatrix(u, v) + distance(u)) < distance(v) )\n distance(v) = distance(u) + netCostMatrix(u, v); % update the shortest distance when a shorter path is found;\n parent(v) = u; % update its parent;\n end; \n end;\nend;\n\npath = [];\nif parent(d) ~= 0 % if there is a path!\n t = d;\n path = [d];\n while t ~= s\n p = parent(t);\n path = [p path];\n \n if netCostMatrix(t, farthestPreviousHop(t)) < netCostMatrix(t, p)\n farthestPreviousHop(t) = p;\n end;\n if netCostMatrix(p, farthestNextHop(p)) < netCostMatrix(p, t)\n farthestNextHop(p) = t;\n end;\n\n t = p; \n end;\nend;\n\ntotalCost = distance(d);\n\nreturn;", "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/5550-dijkstra-shortest-path-routing/dijkstra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6443002149383185}} {"text": "% Fig. 6.82 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclf\nclear all;\n%close all;\n\nnumS=[1 11 10 0];\ndenS=[1 11 60 100];\nw=logspace(-1,2,100);\nsysS=tf(numS,denS);\n[m,p]=bode(sysS,w);\nloglog(w,squeeze(m));\naxis([.1 100 .01 10])\n\nhold on\n% add line at mag = 1\nw2=[.1 100];\nmcl=[1 1];\nloglog(w2,mcl,'r')\n\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 6.82 Sensitivity Function for Example 6.24');\nbodegrid;\nhold off\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig6_82.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6443002118502582}} {"text": "function imchi=sskkimbook2(omega,rechi,omega1,imchi1)\n%The program inputs are the vector of the frequency\n%(or energy) components, the vector of the real\n% part of the susceptibility\n%under examination, anchor point, the value of the\n%imaginary part at the anchor point.\n%The two vectors must have the same length \n%and the frequency vector omega must be equispaced. \n%If not, apply MATLAB functions such as interp.\n%Note that the anchor point must be situated in one of the values\n%of the vector omega.\n%This function uses the function kkimbook2 \n%The output is the estimate of the\n%real part as obtained by using SSKK relations.\n%This software is distributed under the GNU licence agreement\n%by Valerio Lucarini\n%email: lucarini@alum.mit.edu\n%University of Camerino\n%Department of Mathematics and Computer Science\n%Camerino, Italy\n\nif size(omega,1)>size(omega,2);\nomega=omega';\nend; if size(rechi,1)>size(rechi,2);\nrechi=rechi';\nend;\n%Here the program rearranges the two vectors so that,\n%whichever their initial shape, they become row vectors.\ng=size(omega,2);\n%Size of the vectors.%\nk=0;\nfor j=1:g;\nif omega(j)==omega1;\nk=j;\nend;\nend;\n%Determination of the anchor point.\nimchi=kkimbook2(omega,rechi,0);\n%Application of K-K relations\nimchi=imchi+omega1^(-1)*omega.^(1)*(imchi1-imchi(k));\n%The subtracted relation upgrades the estimate obtained\n%with K-K relations.", "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/8135-tools-for-data-analysis-in-optics-acoustics-signal-processing/sskkimbook2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6442606236361217}} {"text": "function M = oned_bilinear ( kernel, phi, test, w_g )\n\n%*****************************************************************************80\n%\n%% ONE_BILINEAR evaluates a bilinear form.\n%\n% Discussion:\n%\n% This function computes integral ( kernel * phi * test }\n%\n% The calculation that is carried out is equivalent to:\n%\n% [ n_gauss, n_test ] = size ( test );\n% [ n_gauss, n_dof ] = size ( phi );\n%\n% M = zeros ( n_test, n_dof );\n% for i = 1 : n_test\n% for j = 1 : n_dof\n% M(i,j) = ( kernel' .* test(:,i)' ) * ( phi(:,j) .* w_g );\n% end\n% end\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Parameters:\n%\n% Input, real KERNEL(N_GAUSS), the kernel function in the integral,\n% evaluated at the Gauss points.\n%\n% Input, real PHI(N_GAUSS,N_DOF), the element test functions evaluated\n% at the Gauss points.\n%\n% Input, real TEST(N_GAUSS,N_TEST), the test functions evaluated at the\n% Gauss points. \n%\n% Input, real W_G(N_GAUSS,1), a column vector of Gauss weights.\n%\n% Output, real M(N_TEST,N_DOF), the bilinear form.\n%\n M = test' * diag ( kernel .* w_g ) * phi;\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/stochastic_gradient_nd_noise/oned_bilinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6442606176408677}} {"text": "function yawm = mag_compass_update(m_n, dec, inc, DCMnb, roll, pitch)\n% magh_update: calculates magnetic heading angle (yaw) from magnetometer data.\n%\n% INPUT\n% mag, 1x3 magnetic flux density (Tesla).\n% dec, magnetic declination angle (rad).\n% inc, magnetic inclination angle (rad).\n% DCMnb, 3x3 DCM nav-to-body.\n% roll, roll angle (rad).\n% pitch, pitch angle (rad).\n%\n% OUTPUT\n% yawm, yaw angle from magnetometer data.\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved. \n% \n% This file is part of NaveGo, an open-source MATLAB toolbox for \n% simulation of integrated navigation systems.\n% \n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL) \n% version 3 as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Lesser General Public \n% License along with this program. If not, see \n% .\n%\n% Reference: \n%\n% Paul D. Groves. Principles of GNSS, Inertial, and\n% Multisensor Integrated Navigation Systems. Second Edition.\n% Eq. 6.2 to 6.6, page 219.\n%\n% NOAA, Magnetic Field Calculators. \n% https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml\n%\n% Version: 002\n% Date: 2021/03/20\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego \n\nB = norm( m_n ); % Magnitude of the flux density\n \nD = [ cos(dec) * cos(inc); sin(dec) * cos(inc); sin(inc); ];\n\nm_b = ( DCMnb * D * B ) ;\n\nx = -m_b(2) * cos(roll) + m_b(3) * sin(roll) ;\ny = m_b(1) * cos(pitch) + m_b(2) * sin(roll) * sin(pitch) ...\n + m_b(3) * cos(roll) * sin(pitch) ;\n\nyawm = correct_yaw (atan2(x , y) + dec); % Four-quadrant arctangent function\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/ins/mag_compass_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.6442606140867513}} {"text": "function [x, cost, info, options] = rlbfgs(problem, x0, options)\n% Riemannian limited memory BFGS solver for smooth objective functions.\n% \n% function [x, cost, info, options] = rlbfgs(problem)\n% function [x, cost, info, options] = rlbfgs(problem, x0)\n% function [x, cost, info, options] = rlbfgs(problem, x0, options)\n% function [x, cost, info, options] = rlbfgs(problem, [], options)\n%\n%\n% This is a Riemannian limited memory BFGS solver (quasi-Newton method), \n% which aims to minimize the cost function in the given problem structure.\n% It requires access to the gradient of the cost function.\n%\n% Parameter options.memory can be used to specify the number of iterations\n% the algorithm remembers and uses to approximate the inverse Hessian of\n% the cost. Default value is 30.\n% For unlimited memory, set options.memory = Inf.\n%\n%\n% For a description of the algorithm and theorems offering convergence\n% guarantees, see the references below.\n%\n% The initial iterate is x0 if it is provided. Otherwise, a random point on\n% the manifold is picked. To specify options whilst not specifying an\n% initial iterate, give x0 as [] (the empty matrix).\n%\n% The two outputs 'x' and 'cost' are the last reached point on the manifold\n% and its cost.\n% \n% The output 'info' is a struct-array which contains information about the\n% iterations:\n% iter (integer)\n% The iteration number. The initial guess is 0.\n% cost (double)\n% The corresponding cost value.\n% gradnorm (double)\n% The (Riemannian) norm of the gradient.\n% time (double)\n% The total elapsed time in seconds to reach the corresponding cost.\n% stepsize (double)\n% The size of the step from the previous to the new iterate.\n% accepted (Boolean)\n% true if step is accepted in the cautious update. 0 otherwise.\n% And possibly additional information logged by options.statsfun.\n% For example, type [info.gradnorm] to obtain a vector of the successive\n% gradient norms reached at each iteration.\n%\n% The options structure is used to overwrite the default values. All\n% options have a default value and are hence optional. To force an option\n% value, pass an options structure with a field options.optionname, where\n% optionname is one of the following and the default value is indicated\n% between parentheses:\n%\n% tolgradnorm (1e-6)\n% The algorithm terminates if the norm of the gradient drops below\n% this. For well-scaled problems, a rule of thumb is that you can\n% expect to reduce the gradient norm by 8 orders of magnitude\n% (sqrt(eps)) compared to the gradient norm at a \"typical\" point (a\n% rough initial iterate for example). Further decrease is sometimes\n% possible, but inexact floating point arithmetic will eventually\n% limit the final accuracy. If tolgradnorm is set too low, the\n% algorithm may end up iterating forever (or at least until another\n% stopping criterion triggers).\n% maxiter (1000)\n% The algorithm terminates if maxiter iterations were executed.\n% maxtime (Inf)\n% The algorithm terminates if maxtime seconds elapsed.\n% minstepsize (1e-10)\n% The minimum norm of the tangent vector that points from the current\n% point to the next point. If the norm is less than minstepsize, the \n% program will terminate.\n% memory (30)\n% The number of previous iterations the program remembers. This is used \n% to approximate the inverse Hessian at the current point. Because of\n% difficulty of maintaining a representation of operators in terms of\n% coordinates, a recursive method is used. The number of steps in the\n% recursion is at most options.memory. This parameter can take any\n% integer value >= 0, or Inf, which is taken to be options.maxiter. If\n% options.maxiter has value Inf, then it will take value 10000 and a\n% warning will be displayed.\n% strict_inc_func (@(t) 1e-4*t)\n% The Cautious step needs a real function that has value 0 at t = 0,\n% and is strictly increasing. See details in Wen Huang's paper\n% \"A Riemannian BFGS Method without Differentiated Retraction for \n% Nonconvex Optimization Problems\"\n% statsfun (none)\n% Function handle to a function that will be called after each\n% iteration to provide the opportunity to log additional statistics.\n% They will be returned in the info struct. See the generic Manopt\n% documentation about solvers for further information. statsfun is\n% called with the point x that was reached last.\n% stopfun (none)\n% Function handle to a function that will be called at each iteration\n% to provide the opportunity to specify additional stopping criteria.\n% See the generic Manopt documentation about solvers for further\n% information.\n% verbosity (2)\n% Integer number used to tune the amount of output the algorithm\n% generates during execution (mostly as text in the command window).\n% The higher, the more output. 0 means silent. 3 and above includes a\n% display of the options structure at the beginning of the execution.\n% debug (false)\n% Set to true to allow the algorithm to perform additional\n% computations for debugging purposes. If a debugging test fails, you\n% will be informed of it, usually via the command window. Be aware\n% that these additional computations appear in the algorithm timings\n% too, and may interfere with operations such as counting the number\n% of cost evaluations, etc. (the debug calls get storedb too).\n% storedepth (2)\n% Maximum number of different points x of the manifold for which a\n% store structure will be kept in memory in the storedb for caching.\n% If memory usage is an issue, you may try to lower this number.\n% Profiling may then help to investigate if a performance hit was\n% incurred as a result.\n% ls_initial_scale (@(gradnorm) 1/gradnorm)\n% A function handle that takes as input a real number (a gradient norm)\n% and outputs a real number for how to scale the initialization of\n% line-search.\n%\n%\n% Please cite the Manopt paper as well as the research paper:\n% @InBook{Huang2016,\n% title = {A {R}iemannian {BFGS} Method for Nonconvex Optimization Problems},\n% author = {Huang, W. and Absil, P.-A. and Gallivan, K.A.},\n% year = {2016},\n% publisher = {Springer International Publishing},\n% editor = {Karas{\\\"o}zen, B{\\\"u}lent and Manguo{\\u{g}}lu, Murat and Tezer-Sezgin, M{\\\"u}nevver and G{\\\"o}ktepe, Serdar and U{\\u{g}}ur, {\\\"O}m{\\\"u}r},\n% address = {Cham},\n% booktitle = {Numerical Mathematics and Advanced Applications ENUMATH 2015},\n% pages = {627--634},\n% doi = {10.1007/978-3-319-39929-4_60}\n% }\n%\n% We point out that, at the moment, this implementation of RLBFGS can be\n% slower than the implementation in ROPTLIB by Wen Huang et al. referenced\n% above. For the purpose of comparing to their work, please use their\n% implementation.\n\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Changshuo Liu, July 19, 2017.\n% Contributors: Nicolas Boumal\n% Change log: \n%\n% Nov. 27, 2017 (Wen Huang):\n% Changed the default strict_inc_func to @(t) 1e-4*t from @(t) t.\n%\n% Jan. 18, 2018 (NB):\n% Corrected a bug related to the way the line search hint was defined\n% by default.\n%\n% Aug. 2, 2018 (NB):\n% Using the new storedb.remove features to keep storedb lean, and\n% reduced the default value of storedepth from 30 to 2 as a result.\n%\n% Aug. 2, 2022 (sfrcorne):\n% Added option ls_initial_scale, with default setting to ensure\n% the method is invariant to positive scaling of the cost function.\n\n\n % Verify that the problem description is sufficient for the solver.\n if ~canGetCost(problem)\n warning('manopt:getCost', ...\n 'No cost provided. The algorithm will likely abort.');\n end\n if ~canGetGradient(problem) && ~canGetApproxGradient(problem)\n % Note: we do not give a warning if an approximate gradient is\n % explicitly given in the problem description, as in that case the user\n % seems to be aware of the issue.\n warning('manopt:getGradient:approx', ...\n ['No gradient provided. Using an FD approximation instead (slow).\\n' ...\n 'It may be necessary to increase options.tolgradnorm.\\n' ...\n 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']);\n problem.approxgrad = approxgradientFD(problem);\n end\n \n % This solver uses linesearch_hint as a line search algorithm. By\n % default, try a step size of 1, so that if the BFGS approximation of\n % the Hessian (or inverse Hessian) is good, then the iteration is close\n % to a Newton step.\n if ~canGetLinesearch(problem)\n problem.linesearch = @(x, d) 1;\n end\n \n % Local defaults for the program\n localdefaults.minstepsize = 1e-10;\n localdefaults.maxiter = 1000;\n localdefaults.tolgradnorm = 1e-6;\n localdefaults.memory = 30;\n localdefaults.strict_inc_func = @(t) 1e-4*t;\n localdefaults.ls_max_steps = 25;\n localdefaults.ls_initial_scale = @(gradnorm) 1/gradnorm;\n localdefaults.storedepth = 2;\n \n % Merge global and local defaults, then merge w/ user options, if any.\n localdefaults = mergeOptions(getGlobalDefaults(), localdefaults);\n if ~exist('options', 'var') || isempty(options)\n options = struct();\n end\n options = mergeOptions(localdefaults, options);\n \n % To make sure memory in range [0, Inf)\n options.memory = max(options.memory, 0);\n if options.memory == Inf\n if isinf(options.maxiter)\n options.memory = 10000;\n warning('rlbfgs:memory', ['options.memory and options.maxiter' ...\n ' are both Inf; options.memory has been changed to 10000.']);\n else\n options.memory = options.maxiter;\n end\n end\n \n M = problem.M;\n \n \n timetic = tic();\n \n \n % Create a random starting point if no starting point is provided.\n if ~exist('x0', 'var')|| isempty(x0)\n xCur = M.rand();\n else\n xCur = x0;\n end\n \n % Create a store database and get a key for the current x\n storedb = StoreDB(options.storedepth);\n key = storedb.getNewKey();\n \n % __________Initialization of variables______________\n % Number of iterations since the last restart\n k = 0; \n % Total number of BFGS iterations\n iter = 0; \n \n % This cell stores step vectors which point from x_{t} to x_{t+1} for t\n % indexing the last iterations, capped at options.memory.\n % That is, it stores up to options.memory of the most recent step\n % vectors. However, the implementation below does not need step vectors \n % in their respective tangent spaces at x_{t}'s. Rather, it requires\n % them transported to the current point's tangent space by vector\n % transport. For details regarding the requirements on the the vector\n % transport, see the reference paper by Huang et al.\n % In this implementation, those step vectors are iteratively \n % transported to the current point's tangent space after every\n % iteration. Thus, at every iteration, vectors in sHistory are in the\n % current point's tangent space.\n sHistory = cell(1, options.memory);\n \n % This cell stores the differences for latest t's of the gradient at\n % x_{t+1} and the gradient at x_{t}, transported to x_{t+1}'s tangent\n % space. The memory is also capped at options.memory.\n yHistory = cell(1, options.memory);\n \n % rhoHistory{t} stores the reciprocal of the inner product between\n % sHistory{t} and yHistory{t}.\n rhoHistory = cell(1, options.memory);\n \n % Scaling of direction given by getDirection for acceptable step\n alpha = 1; \n \n % Norm of the step\n stepsize = 1;\n \n % Stores whether the step is accepted by the cautious update check.\n accepted = true;\n \n % Query the cost function and its gradient\n [xCurCost, xCurGradient] = getCostGrad(problem, xCur, storedb, key);\n \n xCurGradNorm = M.norm(xCur, xCurGradient);\n \n % Scaling of initial matrix, Barzilai-Borwein.\n scaleFactor = options.ls_initial_scale(xCurGradNorm);\n \n % Line-search statistics for recording in info.\n lsstats = [];\n \n % Flag to control restarting scheme to avoid infinite loops (see below)\n ultimatum = false;\n \n % Save stats in a struct array info, and preallocate.\n stats = savestats();\n info(1) = stats;\n info(min(10000, options.maxiter+1)).iter = [];\n \n if options.verbosity >= 2\n fprintf(' iter cost val grad. norm alpha\\n');\n end\n \n % Main iteration\n while true\n\n % Display iteration information\n if options.verbosity >= 2\n fprintf('%5d %+.16e %.8e %.4e\\n', ...\n iter, xCurCost, xCurGradNorm, alpha);\n end\n \n % Start timing this iteration\n timetic = tic();\n \n % Run standard stopping criterion checks\n [stop, reason] = stoppingcriterion(problem, xCur, options, ...\n info, iter+1);\n \n % If none triggered, run specific stopping criterion check\n if ~stop \n if stats.stepsize < options.minstepsize\n % To avoid infinite loop and to push the search further\n % in case BFGS approximation of Hessian is off towards\n % the end, we erase the memory by setting k = 0;\n % In this way, it starts off like a steepest descent.\n % If even steepest descent does not work, then it is \n % hopeless and we will terminate.\n if ~ultimatum\n if options.verbosity >= 2\n fprintf(['stepsize is too small, restarting ' ...\n 'the bfgs procedure at the current point.\\n']);\n end\n k = 0;\n ultimatum = true;\n else\n stop = true;\n reason = sprintf(['Last stepsize smaller than ' ...\n 'minimum allowed; options.minstepsize = %g.'], ...\n options.minstepsize);\n end\n else\n % We are not in trouble: lift the ultimatum if it was on.\n ultimatum = false;\n end\n end \n \n if stop\n if options.verbosity >= 1\n fprintf([reason '\\n']);\n end\n break;\n end\n\n \n % Compute BFGS direction\n p = getDirection(M, xCur, xCurGradient, sHistory,...\n yHistory, rhoHistory, scaleFactor, min(k, options.memory));\n\n % Execute line-search\n [stepsize, xNext, newkey, lsstats] = ...\n linesearch_hint(problem, xCur, p, xCurCost, ...\n M.inner(xCur, xCurGradient, p), ...\n options, storedb, key);\n \n % Record the BFGS step-multiplier alpha which was effectively\n % selected. Toward convergence, we hope to see alpha = 1.\n alpha = stepsize/M.norm(xCur, p);\n step = M.lincomb(xCur, alpha, p);\n \n \n % Query cost and gradient at the candidate new point.\n [xNextCost, xNextGrad] = getCostGrad(problem, xNext, storedb, newkey);\n \n % Compute sk and yk\n sk = M.transp(xCur, xNext, step);\n yk = M.lincomb(xNext, 1, xNextGrad, ...\n -1, M.transp(xCur, xNext, xCurGradient));\n\n % Computation of the BFGS step is invariant under scaling of sk and\n % yk by a common factor. For numerical reasons, we scale sk and yk\n % so that sk is a unit norm vector.\n norm_sk = M.norm(xNext, sk);\n sk = M.lincomb(xNext, 1/norm_sk, sk);\n yk = M.lincomb(xNext, 1/norm_sk, yk);\n \n inner_sk_yk = M.inner(xNext, sk, yk);\n inner_sk_sk = M.norm(xNext, sk)^2; % ensures nonnegativity\n \n \n % If the cautious step is accepted (which is the intended\n % behavior), we record sk, yk and rhok and need to do some\n % housekeeping. If the cautious step is rejected, these are not\n % recorded. In all cases, xNext is the next iterate: the notion of\n % accept/reject here is limited to whether or not we keep track of\n % sk, yk, rhok to update the BFGS operator.\n cap = options.strict_inc_func(xCurGradNorm);\n if inner_sk_sk ~= 0 && (inner_sk_yk / inner_sk_sk) >= cap\n \n accepted = true;\n \n rhok = 1/inner_sk_yk;\n \n scaleFactor = inner_sk_yk / M.norm(xNext, yk)^2;\n \n % Time to store the vectors sk, yk and the scalar rhok.\n % Remember: we need to transport all vectors to the most\n % current tangent space.\n \n % If we are out of memory\n if k >= options.memory\n \n % sk and yk are saved from 1 to the end with the most \n % current recorded to the rightmost hand side of the cells\n % that are occupied. When memory is full, do a shift so\n % that the rightmost is earliest and replace it with the\n % most recent sk, yk.\n for i = 2 : options.memory\n sHistory{i} = M.transp(xCur, xNext, sHistory{i});\n yHistory{i} = M.transp(xCur, xNext, yHistory{i});\n end\n if options.memory > 1\n sHistory = sHistory([2:end, 1]);\n yHistory = yHistory([2:end, 1]);\n rhoHistory = rhoHistory([2:end 1]);\n end\n if options.memory > 0\n sHistory{options.memory} = sk;\n yHistory{options.memory} = yk;\n rhoHistory{options.memory} = rhok;\n end\n \n % If we are not out of memory\n else\n \n for i = 1:k\n sHistory{i} = M.transp(xCur, xNext, sHistory{i});\n yHistory{i} = M.transp(xCur, xNext, yHistory{i});\n end\n sHistory{k+1} = sk;\n yHistory{k+1} = yk;\n rhoHistory{k+1} = rhok;\n \n end\n \n k = k + 1;\n \n % The cautious step is rejected: we do not store sk, yk, rhok but\n % we still need to transport stored vectors to the new tangent\n % space.\n else\n \n accepted = false;\n \n for i = 1 : min(k, options.memory)\n sHistory{i} = M.transp(xCur, xNext, sHistory{i});\n yHistory{i} = M.transp(xCur, xNext, yHistory{i});\n end\n \n end\n \n % Update variables to new iterate.\n storedb.removefirstifdifferent(key, newkey);\n xCur = xNext;\n key = newkey;\n xCurGradient = xNextGrad;\n xCurGradNorm = M.norm(xNext, xNextGrad);\n xCurCost = xNextCost;\n \n % iter is the number of iterations we have accomplished.\n iter = iter + 1;\n \n % Make sure we don't use too much memory for the store database\n % (this is independent from the BFGS memory.)\n storedb.purge();\n \n \n % Log statistics for freshly executed iteration\n stats = savestats();\n info(iter+1) = stats; \n \n end\n\n \n % Housekeeping before we return\n info = info(1:iter+1);\n x = xCur;\n cost = xCurCost;\n\n if options.verbosity >= 1\n fprintf('Total time is %f [s] (excludes statsfun)\\n', ...\n info(end).time);\n end\n\n \n % Routine in charge of collecting the current iteration stats\n function stats = savestats()\n stats.iter = iter;\n stats.cost = xCurCost;\n stats.gradnorm = xCurGradNorm;\n if iter == 0\n stats.stepsize = NaN;\n stats.time = toc(timetic);\n stats.accepted = NaN;\n else\n stats.stepsize = stepsize;\n stats.time = info(iter).time + toc(timetic);\n stats.accepted = accepted;\n end\n stats.linesearch = lsstats;\n stats = applyStatsfun(problem, xCur, storedb, key, options, stats);\n end\n\nend\n\n\n\n\n% BFGS step, see Wen's paper for details. This function takes in a tangent\n% vector g, and applies an approximate inverse Hessian P to it to get Pg.\n% Then, -Pg is returned.\n%\n% Theory requires the vector transport to be isometric and to satisfy the\n% locking condition (see paper), but these properties do not seem to be\n% crucial in practice. If your manifold provides M.isotransp, it may be\n% good to do M.transp = M.isotransp; after loading M with a factory.\n%\n% This implementation operates in the tangent space of the most recent\n% point since all vectors in sHistory and yHistory have been transported\n% there.\nfunction dir = getDirection(M, xCur, xCurGradient, sHistory, yHistory, ...\n rhoHistory, scaleFactor, k)\n \n q = xCurGradient;\n \n inner_s_q = zeros(1, k);\n \n for i = k : -1 : 1\n inner_s_q(1, i) = rhoHistory{i} * M.inner(xCur, sHistory{i}, q);\n q = M.lincomb(xCur, 1, q, -inner_s_q(1, i), yHistory{i});\n end\n \n r = M.lincomb(xCur, scaleFactor, q);\n \n for i = 1 : k\n omega = rhoHistory{i} * M.inner(xCur, yHistory{i}, r);\n r = M.lincomb(xCur, 1, r, inner_s_q(1, i)-omega, sHistory{i});\n end\n \n dir = M.lincomb(xCur, -1, r);\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/solvers/bfgs/rlbfgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6442101513309025}} {"text": "function y = vl_nnpdist(x, x0, p, varargin)\n%VL_NNPDIST CNN p-distance from target.\n% VL_NNPDIST(X, X0, P) computes the P distance raised of each feature\n% vector in X to the corresponding feature vector in X0:\n%\n% Y(i,j,1) = (SUM_d (X(i,j,d) - X0(i,j,d))^P)^(1/P)\n%\n% X0 should have the same size as X; the outoput Y has the same\n% height and width as X, but depth equal to 1. Optionally, X0 can\n% be a 1 x 1 x D x N array, in which case the same target feature\n% vector in X0 is compared to all feature vectors in X.\n%\n% Setting the `noRoot` option to `true` does not take the 1/P power\n% in the formula, computing instead\n%\n% Y(i,j,1) = SUM_d (X(i,j,d) - X0(i,j,d))^P\n%\n% For example, `vl_nnpdist(x, x0, 2, 'noRoot', true)` computes the\n% squared L2 distance.\n%\n% DZDX = VL_NNPDISTP(X, X0, P, DZDY) computes the derivative of the\n% block projected onto DZDY. DZDX and DZDY have the same dimensions\n% as X and Y, respectively.\n%\n% VL_NNPDIST(___, 'OPT', VAL, ...) accepts the following options:\n%\n% `NoRoot`:: `false`\n% If set to true, compute the P-distance to the P-th power.\n%\n% `Epsilon`:: 1e-6\n% When computing derivatives, quantities that are divided in are\n% lower boudned by this value. For example, the L2 distance is\n% not smooth at the origin; this option prevents the\n% derivative from diverging.\n%\n% `Aggregate`:: false\n% Instead of returning one scalar for each spatial location in\n% the inputs, sum all of them into a single scalar.\n%\n% `InstanceWeights``:: `[]`\n% Optionally weight individual instances. This parameter can be\n% eigther a scalar or a weight mask, one for each pixel in the\n% input tensor.\n\n% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% -------------------------------------------------------------------------\n% Parse options\n% -------------------------------------------------------------------------\n\nopts.noRoot = false ;\nopts.epsilon = 1e-6 ;\nopts.aggregate = false ;\nopts.instanceWeights = [] ;\nbackMode = numel(varargin) > 0 && ~ischar(varargin{1}) ;\nif backMode\n dzdy = varargin{1} ;\n opts = vl_argparse(opts, varargin(2:end)) ;\nelse\n dzdy = [] ;\n opts = vl_argparse(opts, varargin) ;\nend\n\n% -------------------------------------------------------------------------\n% Parse options\n% -------------------------------------------------------------------------\n\nd = bsxfun(@minus, x, x0) ;\n\nif ~isempty(dzdy) && ~isempty(opts.instanceWeights)\n dzdy = bsxfun(@times, opts.instanceWeights, dzdy) ;\nend\n\nif ~opts.noRoot\n if isempty(dzdy)\n if p == 1\n y = sum(abs(d),3) ;\n elseif p == 2\n y = sqrt(sum(d.*d,3)) ;\n else\n y = sum(abs(d).^p,3).^(1/p) ;\n end\n else\n if p == 1\n y = bsxfun(@times, dzdy, sign(d)) ;\n elseif p == 2\n y = max(sum(d.*d,3), opts.epsilon).^(-0.5) ;\n y = bsxfun(@times, bsxfun(@times, dzdy, y), d) ;\n elseif p < 1\n y = sum(abs(d).^p,3).^((1-p)/p) ;\n y = bsxfun(@times, bsxfun(@times, dzdy, y), max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n else\n y = max(sum(abs(d).^p,3), opts.epsilon).^((1-p)/p) ;\n y = bsxfun(@times, bsxfun(@times, dzdy, y), abs(d).^(p-1) .* sign(d)) ;\n end\n end\nelse\n if isempty(dzdy)\n if p == 1\n y = sum(abs(d),3) ;\n elseif p == 2\n y = sum(d.*d,3) ;\n else\n y = sum(abs(d).^p,3) ;\n end\n else\n if p == 1\n y = bsxfun(@times, dzdy, sign(d)) ;\n elseif p == 2\n y = bsxfun(@times, 2 * dzdy, d) ;\n elseif p < 1\n y = bsxfun(@times, p * dzdy, max(abs(d), opts.epsilon).^(p-1) .* sign(d)) ;\n else\n y = bsxfun(@times, p * dzdy, abs(d).^(p-1) .* sign(d)) ;\n end\n end\nend\n\nif isempty(dzdy)\n if ~isempty(opts.instanceWeights)\n y = bsxfun(@times, opts.instanceWeights, y) ;\n end\n if opts.aggregate\n y = sum(sum(y)) ;\n end\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/识别算法/DAIN-master/matconvnet/matlab/vl_nnpdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6441969688421968}} {"text": "function [ abd, info ] = cpbfa ( abd, lda, n, m )\n\n%*****************************************************************************80\n%\n%% CPBFA factors a complex hermitian positive definite band matrix.\n%\n% Discussion:\n%\n% CPBFA is usually called by CPBCO, but it can be called\n% directly with a saving in time if RCOND is not needed.\n%\n% Band storage:\n%\n% If A is a hermitian positive definite band matrix,\n% the following program segment will set up the input.\n%\n% m = (band width above diagonal)\n% do j = 1, n\n% i1 = max ( 1, j-m )\n% do i = i1, j\n% k = i-j+m+1\n% abd(k,j) = a(i,j)\n% end do\n% end do\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2007\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, complex ABD(LDA,N); the matrix to be factored.\n% The columns of the upper triangle are stored in the columns of ABD\n% and the diagonals of the upper triangle are stored in the rows of ABD.\n%\n% Input, integer LDA, the leading dimension of ABD.\n% LDA must be at least M+1.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer M, the number of diagonals above the main diagonal.\n% 0 <= M < N.\n%\n% Output, integer INFO.\n% 0, for normal return.\n% K, if the leading minor of order K is not positive definite.\n%\n% Output, complex ABD(LDA,N); an upper triangular matrix R, stored in\n% band form, so that A = hermitian(R)*R.\n%\n info = 0;\n\n for j = 1 : n\n\n s = 0.0;\n ik = m + 1;\n jk = max ( j - m, 1 );\n mu = max ( m + 2 - j, 1 );\n\n for k = mu : m\n t = abd(k,j) - abd(ik:ik+k-mu-1,jk)' * abd(mu:mu+k-mu-1,j);\n t = t / abd(m+1,jk);\n abd(k,j) = t;\n s = s + real ( t * conj ( t ) );\n ik = ik - 1;\n jk = jk + 1;\n end\n\n s = real ( abd(m+1,j) ) - s;\n\n if ( s <= 0.0 | imag ( abd(m+1,j) ) ~= 0.0 )\n info = j;\n break\n end\n\n abd(m+1,j) = sqrt ( s );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_c/cpbfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6441969599755407}} {"text": "% Script file: microphone.m\n%\n% Purpose: \n% This program plots the gain pattern of a cardioid \n% microphone. \n%\n% Record of revisions:\n% Date Programmer Description of change\n% ==== ========== =====================\n% 01/15/07 S. J. Chapman Original code \n%\n% Define variables:\n% g -- Microphone gain constant\n% gain -- Gain as a function of angle\n% theta -- Angle from microphone axis (radians)\n\n% Calculate gain versus angle\ng = 0.5;\ntheta = 0:pi/20:2*pi;\ngain = 2*g*(1+cos(theta));\n\n% Plot gain\npolar (theta,gain,'r-');\ntitle ('\\bfGain versus angle \\theta');\n", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/《Matlab编程》源码/chap3/microphone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6441924465278114}} {"text": "function Xr = pcaRandVec( U, mu, vars, k, n, hypershpere, show )\n% Generate random vectors in PCA subspace.\n%\n% Used to generate random vectors from the subspace spanned by the first k\n% principal components. The points generated come from the gaussian\n% distribution from within the subspace. Can optionally generate points on\n% the subspace that are also on a hypershpere centered on the origin. This\n% may be useful if the original data points were all from a hypershpere --\n% for example they were normalized via imNormalize. Set the optional\n% hypershpere flag to 1 to generate points only on the hypersphere.\n%\n% USAGE\n% Xr = pcaRandVec( U, mu, vars, k, n, [hypershpere], [show] )\n%\n% INPUTS\n% U - returned by pca.m\n% mu - returned by pca.m\n% vars - returned by pca.m\n% k - number of principal coordinates to use\n% n - number of points to generate\n% hypershpere - [0] generate points on hypersphere (see above)\n% show - [1] figure to use for display (no display if == 0)\n%\n% OUTPUTS\n% Xr - resulting randomly generated vectors\n%\n% EXAMPLE\n%\n% See also PCA IMNORMALIZE\n%\n% Piotr's Image&Video Toolbox Version 2.0\n% Copyright 2012 Piotr Dollar. [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\nif( nargin<6 || isempty(hypershpere) ); hypershpere=0; end\nif( nargin<7 || isempty(show) ); show=0; end\n\nsiz1 = size(mu); nd = ndims(mu);\nsizX = [siz1, n]; D = prod(siz1);\n\n% generate random vectors inside of subspace.\nC = diag( vars(1:k).^-1 );\nYr = C * randn(k,n);\nUk = U(:,1:k);\nXr = Uk * Yr;\n\nif(hypershpere)\n % The final point must lie on hypershpere. Need to scale each element xr\n % of Xr so that after adding it to mu the resulting vector has length D.\n % So need to find k>0 such that (k*xr + mu) has length D. To find k\n % simply solve the quadratic equation induced by ||(k*xr + mu)||=D,\n % choosing the root such that k>0. Note that the mean of resulting\n % vector will not necessarily be 0, but the variance will pretty much be\n % 1! Regardless, renomralize at the end.\n muv = mu(:); muMag = dot(muv,muv);\n for i=1:n\n xr = Xr(:,i);\n rs = roots( [dot(xr,xr), 2 * dot(xr,muv), muMag-D] );\n Xr(:,i) = muv + max(rs)*xr;\n end\n Xr = reshape( Xr, sizX );\n Xr = fevalArrays( Xr, @imNormalize );\nelse\n % simply add the mean to reshaped Xr\n Xr = reshape( Xr, sizX );\n muRep = repmat(mu, [ones(1,nd), n ] );\n Xr = Xr + muRep;\nend\n\n% optionaly show resulting vectors\nif(show && (nd==2 || nd==3)); figure(show); montage2(Xr); end\n\n\n\n%%% Little test - see if eigenvectors induced by randomly generated vectors\n%%% are the same as the original eigenvectors. Assumes [U,mu,vars] exist.\n% Xr = pcaRandVec( U, mu, vars, 3, 100 );\n% [ Ur, mur, varsr ] = pca( Xr );\n% ind = 3;\n% Uim = reshape( U(:,ind), [ size(mu,1), size(mu,2) ] );\n% Uimr = reshape( Ur(:,ind), [ size(mu,1), size(mu,2) ] );\n% if( sum(abs(Uim-Uimr))>sum(abs(Uim+Uimr))) Uimr=Uimr*-1; end; %sign?\n% clf; subplot(3,1,1); im( Uim ); subplot(3,1,2); im( Uimr );\n% subplot(3,1,3); im( Uim - Uimr);\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/SketchTokens-master/toolbox/classify/pcaRandVec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6441924374875501}} {"text": "function [out] = saturation_10(p1,p2,p3,S,In)\n%saturation_10 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Saturation excess flow from a store with different degrees \n% of saturation (min-max exponential variant)\n% Constraints: -\n% @(Inputs): p1 - maximum contributing fraction area [-]\n% p2 - minimum contributing fraction area [-]\n% p3 - exponentia scaling parameter [-]\n% S - current storage [mm]\n% In - incoming flux [mm/d]\n\nout = min(p1,p2+p2.*exp(p3.*S)).*In;\n\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/saturation_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.644172834283365}} {"text": "function [xc,good,bad,type] = cornerfinder(xt,I,wintx,winty,wx2,wy2);\n\n%[xc] = cornerfinder(xt,I);\n%\n%Finds the sub-pixel corners on the image I with initial guess xt\n%xt and xc are 2xN matrices. The first component is the x coordinate\n%(horizontal) and the second component is the y coordinate (vertical)\n% \n%Based on Harris corner finder method\n%\n%Finds corners to a precision below .1 pixel!\n%Oct. 14th, 1997 - UPDATED to work with vertical and horizontal edges as well!!!\n%Sept 1998 - UPDATED to handle diverged points: we keep the original points\n%good is a binary vector indicating wether a feature point has been properly\n%found.\n%\n%Add a zero zone of size wx2,wy2\n%July 15th, 1999 - Bug on the mask building... fixed + change to Gaussian mask with higher\n%resolution and larger number of iterations.\n\n\n% California Institute of Technology\n% (c) Jean-Yves Bouguet -- Oct. 14th, 1997\n\n\n\nline_feat = 1; % set to 1 to allow for extraction of line features.\n\nxt = xt';\nxt = fliplr(xt);\n\n\nif nargin < 4,\n winty = 5;\n if nargin < 3,\n wintx = 5;\n end;\nend;\n\n\nif nargin < 6,\n wx2 = -1;\n wy2 = -1;\nend;\n\n\n%mask = ones(2*wintx+1,2*winty+1);\nmask = exp(-((-wintx:wintx)'/(wintx)).^2) * exp(-((-winty:winty)/(winty)).^2);\n\n\n% another mask:\n[X,Y] = meshgrid(-winty:winty,-wintx:wintx);\nmask2 = X.^2 + Y.^2;\nmask2(wintx+1,winty+1) = 1;\nmask2 = 1./mask2;\n%mask - mask2;\n\n\nif (wx2>0) & (wy2>0),\n if ((wintx - wx2)>=2)&((winty - wy2)>=2),\n mask(wintx+1-wx2:wintx+1+wx2,winty+1-wy2:winty+1+wy2)= zeros(2*wx2+1,2*wy2+1);\n end;\nend;\n\noffx = [-wintx:wintx]'*ones(1,2*winty+1);\noffy = ones(2*wintx+1,1)*[-winty:winty];\n\nresolution = 0.005;\n\nMaxIter = 10;\n\n[nx,ny] = size(I);\nN = size(xt,1);\n\nxc = xt; % first guess... they don't move !!!\n\ntype = zeros(1,N);\n\n\nfor i=1:N,\n \n v_extra = resolution + 1; \t\t% just larger than resolution\n \n compt = 0; \t\t\t\t% no iteration yet\n \n while (norm(v_extra) > resolution) & (compt 0, \t\t\t% the sub pixel\n\t vIx = [itIx 1-itIx 0]'; \t% accuracy.\n else\n\t vIx = [0 1+itIx -itIx]';\n end;\n if itIy > 0,\n\t vIy = [itIy 1-itIy 0];\n else\n\t vIy = [0 1+itIy -itIy];\n end;\n\n \n % What if the sub image is not in?\n \n if (crIx-wintx-2 < 1), xmin=1; xmax = 2*wintx+5;\n elseif (crIx+wintx+2 > nx), xmax = nx; xmin = nx-2*wintx-4;\n else\n\t xmin = crIx-wintx-2; xmax = crIx+wintx+2;\n end;\n\n if (crIy-winty-2 < 1), ymin=1; ymax = 2*winty+5;\n elseif (crIy+winty+2 > ny), ymax = ny; ymin = ny-2*winty-4;\n else\n\t ymin = crIy-winty-2; ymax = crIy+winty+2;\n end;\n \n \n SI = I(xmin:xmax,ymin:ymax); % The necessary neighborhood\n SI = conv2(conv2(SI,vIx,'same'),vIy,'same');\n SI = SI(2:2*wintx+4,2:2*winty+4); % The subpixel interpolated neighborhood\n [gy,gx] = gradient(SI); \t\t% The gradient image\n gx = gx(2:2*wintx+2,2:2*winty+2); % extraction of the useful parts only\n gy = gy(2:2*wintx+2,2:2*winty+2); % of the gradients\n \n px = cIx + offx;\n py = cIy + offy;\n \n gxx = gx .* gx .* mask;\n gyy = gy .* gy .* mask;\n gxy = gx .* gy .* mask;\n \n \n bb = [sum(sum(gxx .* px + gxy .* py)); sum(sum(gxy .* px + gyy .* py))];\n \n a = sum(sum(gxx));\n b = sum(sum(gxy));\n c = sum(sum(gyy));\n \n dt = a*c - b^2;\n \n xc2 = [c*bb(1)-b*bb(2) a*bb(2)-b*bb(1)]/dt;\n \n \n %keyboard;\n \n if line_feat,\n \n\t G = [a b;b c];\n\t [U,S,V] = svd(G);\n\t \n\t %keyboard;\n\t \n\t % If non-invertible, then project the point onto the edge orthogonal:\n\t \n\t if (S(1,1)/S(2,2) > 50),\n\t % projection operation:\n\t xc2 = xc2 + sum((xc(i,:)-xc2).*(V(:,2)'))*V(:,2)';\n\t type(i) = 1;\n\t end;\n \n end;\n \n \n %keyboard;\n \n% G = [a b;b c];\n% [U,S,V] = svd(G);\n\n\n% if S(1,1)/S(2,2) > 150,\n%\t bb2 = U'*bb;\n%\t xc2 = (V*[bb2(1)/S(1,1) ;0])';\n% else\n%\t xc2 = [c*bb(1)-b*bb(2) a*bb(2)-b*bb(1)]/dt;\n% end;\n \n \n %if (abs(a)> 50*abs(c)),\n%\t xc2 = [(c*bb(1)-b*bb(2))/dt xc(i,2)];\n% elseif (abs(c)> 50*abs(a))\n%\t xc2 = [xc(i,1) (a*bb(2)-b*bb(1))/dt];\n% else\n%\t xc2 = [c*bb(1)-b*bb(2) a*bb(2)-b*bb(1)]/dt;\n% end;\n \n %keyboard;\n \n v_extra = xc(i,:) - xc2;\n \n xc(i,:) = xc2;\n \n% keyboard;\n\n compt = compt + 1;\n \n end\nend;\n\n\n% check for points that diverge:\n\ndelta_x = xc(:,1) - xt(:,1);\ndelta_y = xc(:,2) - xt(:,2);\n\n%keyboard;\n\n\nbad = (abs(delta_x) > wintx) | (abs(delta_y) > winty);\ngood = ~bad;\nin_bad = find(bad);\n\n% For the diverged points, keep the original guesses:\n\nxc(in_bad,:) = xt(in_bad,:);\n\nxc = fliplr(xc);\nxc = xc';\n\nbad = bad';\ngood = good';\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/cornerfinder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6440412110677497}} {"text": "function h=entropyDist(npd)\n%\n% Compute entropy estimate using nearest neighbor estimate\n%\n\n% Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt\n\nCe = .57721566490153286;\n\npts = getPoints(npd);\n\n[N1,N2] = size(pts);\n[tmp,D] = knn(npd,pts,2);\n\nSr = N1* pi^(N1/2) / gamma((N1/2) + 1);\nh = N1/N2 * sum( log(D) ) + log(Sr * (N2-1)/N1 ) + Ce;\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/render_pipeline/kde/matlab_kde_package/private/entropyDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6440412016837852}} {"text": "function [C,nc] = graph_coloring(A,nc)\n % GRAPH_COLORING Color a graph given an adjacency matrix. This heuristic is\n % designed to efficiently find a conservative coloring (i.e., using too many\n % colors). It does *not* attempt to find the minimal coloring. It is best used\n % when the provided nc is a few more than the optimal coloring. For example,\n % planar graphs can be colored with 4 colors, (slow) heuristics for finding the\n % optimal coloring will often find 6 colors, but this function will very\n % quickly find a 7-coloring (nc=7). On such a graph, if you passed nc=4, this\n % function will likely waste time attemping to find a 4-coloring, 5-coloring,\n % 6-coloring, and then very quickly find a 7-coloring. It is designed to give\n % up searching for parsimonious colorings and increase the number of colors\n % (throwing a warning).\n %\n % [C,nc] = graph_coloring(A,nc)\n %\n % Inputs:\n % A #V by #V adjacency matrix\n % nc desired number of colors (for planar/triangle meshes, 7 is a fast\n % choice; for tetrahedral meshes, 13 appears to often be fast)\n % Outputs:\n % C #V list of color ids into (1:nc)\n % nc effective number of colors >= input nc\n\n n = size(A,1);\n [FI,FJ] = find(triu(A,1));\n % always marking the higher valence vertex as bad definitely makes things\n % worse 50x.\n %\n % if nc is much greater than optimal, always marking the lower valence vertex\n % doesn't much effect. But for nc close to optimal, this seems to make a very\n % big difference (300x)\n val = sum(A,2);\n swap = val(FI)max_outer\n error('Failed to converge.\\n');\n end\n end\n if nc ~= onc\n warning('Had to increasing number of colors')\n end\n\n %V2C = sparse(1:n,C,1,n,nc);\n % find all edges with the same color\n %A*V2C;\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/matrix/graph_coloring.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6439631263496407}} {"text": "function rule_num = lyness_rule_num ( )\n\n%*****************************************************************************80\n%\n%% LYNESS_RULE_NUM returns the number of Lyness quadrature rules.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% James Lyness, Dennis Jespersen,\n% Moderate Degree Symmetric Quadrature Rules for the Triangle,\n% Journal of the Institute of Mathematics and its Applications,\n% Volume 15, Number 1, February 1975, pages 19-32.\n%\n% Parameters:\n%\n% Output, integer RULE_NUM, the number of rules.\n%\n rule_num = 21;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_lyness_rule/lyness_rule_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.6439631094144789}} {"text": "function p = mstud_lpdf(x, mu, Cov, nu)\n% p = mstud_lpdf(x, mu, Cov, nu)\n\nD = length(x);\n\nx = x(:);\nmu = mu(:);\n\ninvCov = inv(Cov);\n\np = gammaln((D+nu)/2);\np = p - gammaln(nu/2);\np = p - D/2 * log(nu * pi);\np = p - 0.5 * log(det(Cov));\np = p + -(D+nu)/2 * log(1 + 1/nu*(x-mu)'*invCov*(x-mu));", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/distributions/mstud_lpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475730993027, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.6439042819105542}} {"text": "function [cl, cp, cs] = dtiComputeWestinShapes(eigVal, denominator)\n%\n% [cl, cp, cs] = dtiComputeWestinShapes(eigVal, [denominator='lsum'])\n% Computes Westin's shape indices\n%'denominator' is a parameter allowing to choose an appropriate definition\n%for Westin shapes.\n%\n% denominator='lsum' (default):\n% cl = (lambda_1 - lambda_2) / (lambda_1 + lambda_2 + lambda_3)\n% cp = 2 * (lambda_2 - lambda_3) / (lambda_1 + lambda_2 + lambda_3)\n% cs = 3 * lambda_3 / (lambda_1 + lambda_2 + lambda_3)\n%\n% This was the originial formulation described in:\n%\n% C-F. Westin, S. Peled, H. Gubbjartsson, R. Kikinis, and F.A. Jolesz.\n% Geometrical diffusion measures for MRI from tensor basis analysis.\n% In Proceedings 5th Annual ISMRM, 1997.\n%\n% denominator='l1':\n%\n% In later work, Westin et. al. adopted a simpler normalization\n% formulation (e.g., see Westin et. al. 2002 Med. Image Anal.; PMID:\n% 12044998) where the constants are dropped and the denominator is simply\n% lambda_1. This definition produces cl+cp+cs=1 which is convenient for\n% tensor shape representation in barycentric coordinates.\n% In practice, the two methods produce very similar maps.\n% cl = (lambda_1 - lambda_2) / (lambda_1)\n% cp = 2 * (lambda_2 - lambda_3) / (lambda_1)\n% cs = 3 * lambda_3 / (lambda_1)\n%\n% eigVal: XxYxZx3 or nx3xN array of tensor eigenvalues. Or, you can pass\n% the dt6 array (XxYxZx6) and we'll compute the eigenvalues for you.\n%\n%\n% HISTORY:\n% 2004.07.22 RFD (bobd@stanford.edu) & ASH wrote it.\n% 2007.01.02 SHC made changes to allow nx3xN format.\n% 2009.01.05 EIR added option of using a more recent definition of Westin shapes\n\nif ~exist('denominator', 'var')\n denominator='lsum';\nend\n\n\nif size(eigVal,4)==6\n [eigVec, eigVal] = dtiEig(eigVal);\n clear eigVec;\nend\n\n% Check inputs\nswitch ndims(eigVal)\n case 2,\n Ind = 1; % Data in indexed nx6 format\n eigVal = shiftdim(eigVal, -2);\n case 3,\n if size(eigVal,2)==6 && size(eigVal,3)~=6\n Ind = 1; % Data in indexed nx6xN format\n eigVal = shiftdim(eigVal, -2);\n else\n Ind = 2; % Data in XxYx6 format\n eigVal = shiftdim(eigVal, -1);\n end\n otherwise,\n Ind = 0; % Data in XxYxZx6xN format\nend\n\nepsilon = 1e-10;\nswitch denominator\n case 'lsum'\n denum=sum(eigVal,4);\n\n case 'l1'\n denum=eigVal(:, :, :, 1);\n otherwise fprintf('Wrong denominator option');\nend\n\nnz = denum>epsilon;\n\n% Avoid divide-by-zero (we'll replace these values with zeros below).\ndenum(~nz) = 1;\n\ncl = (eigVal(:,:,:,1)-eigVal(:,:,:,2))./denum;\ncp = 2*(eigVal(:,:,:,2)-eigVal(:,:,:,3))./denum;\ncs = 3*eigVal(:,:,:,3)./denum;\n\nif strcmp(denominator,'l1')\n cp=cp./2;\n cs=cs./3;\nend\n\n\n\ncl(~nz) = 0; cp(~nz) = 0; cs(~nz) = 0;\ncl(cl>1.0) = 1.0;\ncp(cp>1.0) = 1.0;\ncs(cs>1.0) = 1.0;\ncl(cl<0.0) = 0.0;\ncp(cp<0.0) = 0.0;\ncs(cs<0.0) = 0.0;\n\n% Adjust output\nswitch Ind\n case 1,\n cl = shiftdim(cl, 2);\n cp = shiftdim(cp, 2);\n cs = shiftdim(cs, 2);\n case 2,\n cl = shiftdim(cl, 1);\n cp = shiftdim(cp, 1);\n cs = shiftdim(cs, 1);\nend\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/tensor/dtiComputeWestinShapes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6436108293159895}} {"text": "function [AA, aa, pp, rankA, p] = rowReduce(A, a, mode, printLevel)\n% Eliminates dependent rows from `A` & `a` where :math:`A x = a`\n%\n% USAGE:\n%\n% [AA, aa, pp, rankA, p] = rowReduce(A, a)\n%\n% INPUT:\n% A: from :math:`A x = a`\n%\n% OPTIONAL INPUT:\n% a: from :math:`A x = a`\n%\n% mode: If mode=1, LUSOL operates on A itself.\n% If mode=2, LUSOL operates on A'.\n%\n% printLevel\n%\n% OUTPUT:\n% AA: row reduced `A`\n% aa: row reduced `a` i.e. `aa = a(pp)`\n% pp: 1:rankA indices of independent rows\n% rankA: rank of `A`\n% p: row permutation which leaves first `1:rankA` rows independent and\n% last rows dependent\n%\n% .. Author: - Ronan Fleming, with linear algebra advice from Michael Saunders\n% Dept of Management Science and Engineering (MS&E) Stanford University\n\nif ~exist('a','var') %create a if not provided\n a=sparse(size(A,1),1);\nelse\n if size(A,1)~=length(a)\n error('Dimensions of A and a are inconsistent');\n end\nend\n\nif ~exist('mode','var')\n mode=1;\nend\n\nif ~exist('printLevel','var')\n printLevel=1;\nend\n\n[mlt,nlt]=size(A);\narchstr = computer('arch');\narchstr = lower(archstr);\n%archstr='';%bypass until issue with lusol tolerance sorted.\nswitch archstr\n case {'glnx86','glnxa64','maci64'}\n %Eliminate dependent rows\n [AA,aa,p,rankA] = lusolCondense(A,a,mode,printLevel-1);\n if ~(nnz(A)>0 && rankA==0) && printLevel>0\n fprintf('%s',['Eliminated ' int2str(mlt-rankA) ' dependent rows, using lusol.']);\n end\n pp=p(1:rankA);\n %case {'PCWIN','PCWIN64'}\n otherwise\n [AA, aa, pp, rankA, p] = qrRowReduce(A,a, printLevel);\nend\n\nif nnz(A)>0 && rankA==0\n %backup in case something has gone wrong with lusolCondense\n [AA, aa, pp, rankA, p] = qrRowReduce(A, a, printLevel);\nend\n\nfprintf('\\n')\nend\n\nfunction [AA, aa, pp, rankA, p] = qrRowReduce(A, a, printLevel)\n [mlt,nlt]=size(A);\n A=full(A);\n %Eliminate dependent rows\n [Q,R,P] = qr(A');\n [p,q,s] = find(P);\n s = diag(R);\n tol = 1e-8;\n rankA = length(find(abs(s) > tol));\n % nnz(abs(diag(R))>1.e-15)\n AA = sparse(A(p(1:rankA),:));\n pp = p(1:rankA);\n aa = sparse(a(pp));\n if printLevel>0\n fprintf('%s',['Eliminated ' int2str(mlt-rankA) ' dependent rows, using qr factorisation.']);\n end\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/subspaces/rowReduce/rowReduce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6436108190294523}} {"text": "%% Trend-Cycle tutorial: Predicting recessions\n% Authors: Filippo Ferroni and Fabio Canova\n% Date: 27/05/2020, revised 15/12/2020\n\nclose all; clc; clear all;\n\naddpath ../../cmintools/\naddpath ../../bvartools/\n\n% predicting recession and the start of a recession in the euro area. \n% use recession indicator constructed with example_2_dating.m; regressors \n% labor productivity, commodity prices, long term rates or spread.\n\n\n \n% Euro area AWM DATABASE: Quarterly\n [a,b,~] = xlsread('awm19up18.xlsx');\n % names of variables\n varnames = b(1,2:end);\n\n % time convention: Q1 = .00 and Q4 =0.75\n time = 1970 : .25 : 2017.75;\n time_start = find(time==1970.50); \n time_start1 = find(time==1999.50); \n time_end = find(time==2017.75);\n time_break = find(time==2007.75);\n \n \n % The CREDIT DATA: Quartely\n [e,f,~]=xlsread('ECB_Credit_gaps.xlsx');\n varnames2= f(1,2:end);\n\n % real GDP, real consumption, real investment, GDP defl, HICP, \n % short and long term interest rate, commodity prices, \n % labor productivity, total employment, credit to NFC to GDP \n yy = [a(:,1) a(:,2) a(:,4) a(:,7) a(:,19) a(:,33) a(:,34) ...\n a(:,35) a(:,42) a(:,29) e(time_start-2:time_end,25)]; \n % names: YER PCR ITR YED HICP STN LTN COMPR LPROD LNN\n\n % data transformations:\n % 1. the log of output, consumption,investment\n ddata(:,1:3) = log(yy(time_start+1 : time_end,1:3));\n % 2. the log/log difference of GDP deflator index and CPI\n %ddata(:,4:5) = log(yy(time_start+1 : time_end,4:5));\n ddata(:,4:5) = diff(log(yy(time_start : time_end,4:5)))*400;\n % 3. the level of short and long term interest rate\n ddata(:,6:7) = yy(time_start +1 : time_end,6:7);\n % 4. the log/log difference of commodity prices\n ddata(:,8) = log(yy(time_start+1 : time_end,8));\n %ddata(:,8) = diff(log(yy(time_start : time_end,8)))*400;\n % 5. the taking the log of labor productivity and employment\n ddata(:,9:10) = log(yy(time_start+1 : time_end,9:10));\n %ddata(:,9) = diff(log(yy(time_start+1 : time_end,9)));\n %ddata(:,10) = log(yy(time_start+1 : time_end,10));\n\n % 6. spread\n ddata(:,11)= ddata(:,7)-ddata(:,6);\n % data for credit to GDP starts only at time_start1 (1999:25)\n ddata(:,12) = yy(time_start+1:time_end,11);\n endd=length(ddata); \n\n % cc=ones(time_end-time_start,1); % constant\n % pick log labor productivity, log commodity prices, long term rate\n % z=ddata(:,[9 8 7]);\n % pick log labor productivity, log commodity prices, spread\n z=ddata(:, [9 8 11]);\n \nload Eurorec\n% recind has the recession indicator created with dating_exa.m\nx=recind;\n\n% use contemporanous values\n% [estimator,cov_Hessian,ME1,ME2,ME_std] = probit(x,z);\n\n% use one period lagged values \nzz=zeros(size(z,1), size(z,2));\nzz(2:length(z),:)=z(1:length(z)-1,:);\ntimeplot = time(time_start:time_end-1);\n\n% Estimate Probit model and the marginal effects\n[estimator,cov_Hessian,ME1,ME2,ME1_std] = probit(x,zz);\n\n% prediction\npz=[ones(length(zz),1) zz];\npx=normpdf(pz*estimator);\nhalf=0.5*ones(length(z),1);\n\nplot(timeplot,px,'r-.','Linewidth',2); hold on; \nplot(timeplot,half,'b:','Linewidth',2); hold on; \nplot(timeplot,x,'k-','Linewidth',2); hold off; axis tight;\nlegend('predition','halfline', 'actual')\npause\n\nclose all;\n\n% do estimation recursively: predicting the beginning of a recession\n% which is the same as predicting a peak\n% recession dates\n%rec1b = find(time==1974.00);\n%rec1e = find(time==1975.25);\n%[estimator1,cov_Hessian1,ME11,ME21,ME11_std] = probit(x(1:rec1b),zz(1:rec1b,:));\n\nrec2b = find(time==1980.00);\nrec2e = find(time==1984.25);\ndisp('Predicting 1980 recession')\n[estimator2,cov_Hessian2,ME12,ME22,ME12_std] = probit(x(1:rec2b),zz(1:rec2b,:));\npz2=[ones(rec2b,1) zz(1:rec2b,:)];\npx2=normpdf(pz2*estimator2);\nhalf2=0.5*ones(rec2b,1);\n\nplot(timeplot(1:rec2b),x(1:rec2b),'k-','Linewidth',2); hold on; \nplot(timeplot(1:rec2b),half2(1:rec2b),'b:','Linewidth',2); hold on; \nplot(timeplot(1:rec2b),px2(1:rec2b),'r-.','Linewidth',2); hold off;axis tight;\nlegend('actual', 'halfline', 'predition')\npause\n\n\nclose all;\n\nrec3b = find(time==1992.00);\nrec3e = find(time==1993.75);\ndisp('Predicting 1992 recession')\n[estimator3,cov_Hessian3,ME13,ME23,ME13_std] = probit(x(1:rec3b),zz(1:rec3b,:));\npz3=[ones(rec3b,1) zz(1:rec3b,:)];\npx3=normpdf(pz3*estimator3);\nhalf3=0.5*ones(rec3b,1);\n\nplot(timeplot(1:rec3b),x(1:rec3b),'k-','Linewidth',2); hold on; \nplot(timeplot(1:rec3b),half3(1:rec3b),'b:','Linewidth',2); hold on; \nplot(timeplot(1:rec3b),px3(1:rec3b),'r-.','Linewidth',2); hold off; axis tight;\nlegend('actual', 'halfline','predition')\npause\nclose all;\n\nrec4b = find(time==2001.00);\nrec4e = find(time==2002.75);\ndisp('Predicting 2001 recession')\n[estimator4,cov_Hessian4,ME14,ME24,ME14_std] = probit(x(1:rec4b),zz(1:rec4b,:));\npz4=[ones(rec4b,1) zz(1:rec4b,:)];\npx4=normpdf(pz4*estimator4);\nhalf4=0.5*ones(rec4b,1);\n\nplot(timeplot(1:rec4b),x(1:rec4b),'k-','Linewidth',2); hold on; \nplot(timeplot(1:rec4b),half4(1:rec4b),'b:','Linewidth',2); hold on; \nplot(timeplot(1:rec4b),px4(1:rec4b),'r-.','Linewidth',2); hold off; axis tight;\nlegend('actual', 'halfline','predition')\npause\nclose all;\n\n\nrec5b = find(time==2008.00);\nrec5e = find(time==2009.50);\ndisp('Predicting 2008 recession')\n[estimator5,cov_Hessian5,ME15,ME25,ME15_std] = probit(x(1:rec5b),zz(1:rec5b,:));\npz5=[ones(rec5b,1) zz(1:rec5b,:)];\npx5=normpdf(pz5*estimator5);\nhalf5=0.5*ones(rec5b,1);\n\nplot(timeplot(1:rec5b),x(1:rec5b),'k-','Linewidth',2); hold on; \nplot(timeplot(1:rec5b),half5(1:rec5b),'b:','Linewidth',2); hold on; \nplot(timeplot(1:rec5b),px5(1:rec5b),'r-.','Linewidth',2); hold off; axis tight;\nlegend('actual', 'halfline', 'predition')\npause\nclose all;\n\n\nrec6b = find(time==2011.25);\nrec6e = find(time==2013.00);\ndisp('Predicting 2011 recession')\n[estimator6,cov_Hessian6,ME16,ME26,ME16_std] = probit(x(1:rec6b),zz(1:rec6b,:));\npz6=[ones(rec6b,1) zz(1:rec6b,:)];\npx6=normpdf(pz6*estimator6);\nhalf6=0.5*ones(rec6b,1);\n\nplot(timeplot(1:rec6b),x(1:rec6b),'k-','Linewidth',2); hold on; \nplot(timeplot(1:rec6b),half6(1:rec6b),'b:','Linewidth',2); hold on; \nplot(timeplot(1:rec6b),px6(1:rec6b),'r-.','Linewidth',2); hold off; axis tight;\nlegend('actual', 'halfline', 'predition')\n \n \nreturn\n \n \n ", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/examples/Trend-Cycle-Dating tutorial/example_3_recession_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6435589026450433}} {"text": "% By Roger Aarenstrup, roger.aarenstrup@mathworks.com\n% 2006-08-18\n%\n% This is a state-space DC motor model of a\n% Maxon RE25 10 Watt, precious metal brushes, 118743\n% \n% This model also have a weak connection to a load.\n%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The full dc motor model %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Vin is the input voltage to the motor\n% i is the motor current\n% th_m is the rotor angle, theta\n% dth_m is the rotor angular velocity sometimes called omega\n% th_l is the load angle\n% dth_l is the load angular velocity\n\n% Controller Sample Time\nTs = 100e-6;\n\n% PARAMETERS DC MOTOR\nRm = 2.06; % Motor resistance (ohm)\nLm = 0.000238; % motor inductance (Henrys)\nKb = 1/((406*2*pi)/60); % Back EMF constant (Volt-sec/Rad)\nKt = 0.0235; % Torque constand (Nm/A)\nJm = 1.07e-6; % Rotor inertia (Kg m^2)\nbm = 12e-7; % MEchanical damping (linear model of\n % friction: bm * dth)\n% PARAMETERS LOAD\nJl = 10.07e-6; % Load inertia (10 times the rotor)\nbl = 12e-6; % Load damping (friction)\nKs = 100; % Spring constant for connection rotor/load\nb = 0.0001; % Spring damping for connection rotor/load\n\n% SYSTEM MATRICES\n%\n% States: [i dth_m th_m dth_l th_l]' \n% Input: Vin the motor voltage\n% Outputs: same as states\n%\nAfull = [-Rm/Lm -Kb/Lm 0 0 0;\n Kt/Jm -(bm+b)/Jm -Ks/Jm b/Jm Ks/Jm;\n 0 1 0 0 0;\n 0 b/Jl Ks/Jl -(b+bl)/Jl -Ks/Jl;\n 0 0 0 1 0];\n \nBfull = [1/Lm 0 0 0 0]';\n\nCfull = [0 1 0 0 0;\n 0 0 1 0 0;\n 0 0 0 1 0;\n 0 0 0 0 1];\n\nDfull = [0 0 0 0]';\n\nsys_full = ss(Afull, Bfull, Cfull, Dfull);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The reduced dc motor model for current control %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% SYSTEM MATRICES\n%\n% States: [dth_m th_m dth_l th_l]' \n% Input: I The current to the dc motor\n% Outputs: same as states\n%\nAred = [ -(bm+b)/Jm -Ks/Jm b/Jm Ks/Jm;\n 1 0 0 0;\n b/Jl Ks/Jl -(b+bl)/Jl -Ks/Jl;\n 0 0 1 0];\n \nBred = [Kt/Jm 0 0 0]';\n\nCred = eye(4);\n\nDred = [0 0 0 0]';\n\nsys_red = ss(Ared, Bred, Cred, Dred);\n\n% Discrete version of the model (as seen from the controller)\nsys_red_d = c2d(sys_red, Ts, 'zoh');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 1 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% The discrete poles of the closed loop system\ndpole1 = exp(-2*pi*Ts*[20 22 24 26]);\n\n% Calculate the control parameters\nL1 = place(sys_red_d.a, sys_red_d.b, dpole1);\n\n% Keep the static gain of the closed loop system to 1\nF=feedback(sys_red_d, L1); % The closed loop system, F.\nKstatic = freqresp(F, 0); % Get the static gain of F.\nKstat = 1/Kstatic(4); % It is the fourth output (load position)\n\n% The above commands requires toolboxes, incase you don't have them\n% you can simulate the system with a unit step is see the output static\n% gain. Kstat will be the inverse of that.\n\n% to verify the pole placement\n%pzmap(F);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 2 - Integrator %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% The discrete poles of the closed loop system\ndpole2 = exp(-2*pi*Ts*[20 22 24 26 5]); \n\n% We only consider one output here\nCred_one = [0 1 0 0];\n\n% Calculate the control parameters\nAint = [sys_red_d.a [0 0 0 0]';\n -Cred_one 1];\n \nBint= [sys_red_d.b' 0]';\n\nCint = [Cred_one 0];\n\nDint = [0]';\n\nsys_int_d2 = ss(Aint, Bint, Cint, Dint, Ts);\n\n% Controllability VS Observability analysis\n%ob = obsv(sys_int_d2.a, sys_int_d2.c);\n%cr = ctrb(sys_int_d2.a, sys_int_d2.b);\n%rank(ob)\n%rank(cr)\n\n[L2, a, m] = place(sys_int_d2.a, sys_int_d2.b, dpole2);\n\n% Feed Forward gain\nKff = L2(5)/(dpole2(5) - 1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 3 - Observer %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% These should be about twice as fast as the state feedback\n% for the controller.\ndpole3 = exp(-2*pi*Ts*[1400 1450 1500 1550]);\n%dpole3 = [-0.3 -0.33 -0.35 -0.37];\n\n% Recalculate the reduced model with one ouput\nCred2 = [0 1 0 0];\n\nDred2 = 0;\n\nsys_red2 = ss(Ared, Bred, Cred2, Dred2);\n\n% Discrete version of the model (as seen from the controller)\nsys_red_d2 = c2d(sys_red2, Ts, 'zoh');\n\nset(sys_red_d2, 'inputname', {'Um'}, ...\n 'outputname', {'Enc_out'});\n\n% Calculate the observer state feedback\nK = place(sys_red_d2.a', sys_red_d2.c', dpole3);\n\n% Put the observer together\nAobs = [sys_red_d2.a-K'*sys_red_d2.c];\nBobs = [sys_red_d2.b K'];\nCobs = eye(4);\nDobs = [0 0 0 0; 0 0 0 0]';\n\nobserver = ss(Aobs, Bobs, Cobs, Dobs, Ts, 'inputname', {'Ue', 'Enc_in'}, ...\n 'outputname', {'dth_m', 'th_m', 'dth_l', 'th_l'});\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% State-space controller design attempt 4 - The Servo Case %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nKinv = (Jl+Jm)/Kt;\n\ndpole4 = exp(-2*pi*Ts*[200 204 220 224 300]);\n[L3, a, m] = place(sys_int_d2.a, sys_int_d2.b, dpole4);\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/12137-pid-and-state-feedback-control-of-dc-motors/dc_motor_demo/3_mbd_project/c_controller/controller_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6435589018758835}} {"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 pathS = MC_VG_S(S0,r,d,T,nu,theta,sigma,NTime,NSim,NBatches)\n% discretization of Variance Gamma process\n% using subordination\n\npathS = zeros(NSim,NTime+1,NBatches); % create the output\nlnS = zeros(NSim,NTime+1); % used per batch\ndT = T / NTime; % delta time\nomegaT = -1/nu * log(1-theta(1)*nu ...\n - nu*sigma(1)^2/2); % martingale correction \nlnS(:,1) = log(S0); % Set the starting spot price\n\nfor l = 1 : NBatches % batch loop\n % G = nu * gamrnd(dT/nu,1,NSim,NTime);\n % dW = randn(NSim,NTime);\n for m=2:NTime+1 % time loop\n G = nu * gamrnd(dT/nu,1,NSim,1); % Gamma subordinator\n dW = randn(NSim,1); % Gaussians\n lnS(:,m) = lnS(:,m-1) ... % log VG\n + (r-d-omegaT) * dT ...\n + theta(1) * G + sqrt(G) * sigma .* dW;\n end\n \n pathS(:,:,l) = exp(lnS); % simulated paths\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/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/MC_VG_S.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6435588981968948}} {"text": "%% demo code\n% reconstruction of retrospective subsampled Shepp-Logan phantom\n\n% set paths\naddpath(genpath(pwd));\naddpath(genpath(['..',filesep,'CS_LAB_matlab']));\n\n%% ------------------------------------------\n% 1.) load data: phantom (2 slices, 1 channel)\n% -------------------------------------------\ndImg = phantom('Modified Shepp-Logan',256);\ndKSpace = fftnshift(dImg,1:2);\n\n\n%% --------------------------\n% 2.) create subsampling mask\n% ---------------------------\nif(ispc), sExt = '.exe'; else sExt = ''; end\nsystem(['.',filesep,'sampling',filesep,'Subsample',sExt,sprintf(' %d %d %d %d', 256, 1, 4, 1)]);\niMask = readSamplingMaskFromFile(['.',filesep,'samplingPattern.txt']);\n\n\n%% -------------------------\n% 3.) apply subsampling mask\n% --------------------------\n% k-Space dimensions\n% cell array: NSlice x NChannels x NRepetitions x NAverages\n% each cell: 2D: yPhase x xFreq x (nTime/nPhases)\n% 3D: yPhase x xFreq x zPhase\n% 4D: yPhase x xFreq x zPhase x nTime/nPhases\ndKSpaceSub = {dKSpace .* repmat(iMask,[1 256])};\n\n\n%% --------------------\n% 4.) reconstruct image\n% ---------------------\n% set some recon parameters\npara.cstype = 'FOCUSS';\npara.transformation = 'fft';\npara.lambda = 1e-12;\npara.lambdaTV = 1e-6;\npara.measPara.dim = [size(dKSpaceSub{1}), 1, 1, 1];\npara.measPara.LCall = ones(1,4);\npara.measPara.dimension = '2D';\npara.espresso.state = false;\npara.espresso.direction = 'off';\npara.espresso.pfn = 1;\npara.flagOversampling = logical([0 0 0]);\npara.postproc.turnImage = false;\npara.postproc.FreqOversamplingCorr = false;\npara.prop.flagPlot = false;\n\n% CS reconstruction\ndCSRecon = CS_reconstruction(dKSpaceSub, para);\n\n% zero-padded reconstruction\ndZeropadded = abs(ifftnshift(dKSpaceSub{1}));\n\n\n%% ------------------\n% 5.) compare results\n% -------------------\nfigure;\nsubplot(1,3,1)\nimagesc(dImg); colormap('gray');\naxis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';\ntitle('original')\nsubplot(1,3,2)\nimagesc(dZeropadded); colormap('gray');\naxis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';\ntitle('zero-padded recon')\nsubplot(1,3,3)\nimagesc(dCSRecon); colormap('gray');\naxis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';\ntitle('CS recon')", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_GUI/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6435588981968947}} {"text": "%% DEMO_visualization_von_mises_plasticity_01\n% Below is a demonstration for:\n%\n% * Visualization of a Von Mises yield surface in 3D\n\n%%\n\nclear; close all; clc\n\n%% Plot settings. \n\nfontSizeAxis=25;\nfontSizeText=35;\ncolorSet=viridis(3);\nlineWidth1=1;\nlineWidth2=3;\nlineWidthAxis=3;\nf=2;\n\n%% Control parameters\n\nsy=1; %Yield stress\ntau_octahedral=sy*sqrt(2/3); %Octahedral shear stress = cylinder radius\n\n%% \n% Create ellipsoids\nt=linspace(0,2*pi,1000); %Angular coordinates\nx=tau_octahedral*cos(t); \ny=tau_octahedral*sqrt(3).*sin(t);\nz=zeros(size(x));\nv=[x(:) y(:) z(:)]; %Ellipse coordinates\n\n%Make cylinder \"slices\" ellipses by rotating above ellipse\nR12=euler2DCM([0 0 (45/180)*pi]);\nv12=v*R12; \n\nR13_1=euler2DCM([0 (90/180)*pi 0]);\nR13_2=euler2DCM([(135/180)*pi 0 0]);\nv13=v*R13_1*R13_2; \n\nR23_1=euler2DCM([(90/180)*pi 0 0]);\nR23_2=euler2DCM([0 (-45/180)*pi 0 ]);\nv23=v*R23_1*R23_2; \n\n%%\n% Creating cylinder data\n\n% Creating input structure\ninputStruct.cylRadius=tau_octahedral;\ninputStruct.numRadial=250;\ninputStruct.cylHeight=2*sqrt(2)*tau_octahedral;\ninputStruct.numHeight=10;\ninputStruct.meshType='quad';\n[F,V,C]=patchcylinder(inputStruct);\nQ=euler2DCM([0 pi/2 0]);\nV=V*Q;\n\nR1=euler2DCM([0 asin(1/sqrt(3)) 0]);\nR2=euler2DCM([0 0 -(45/180)*pi]);\nV=V*R1*R2;\n\n[x1,y1]=meshgrid(-f*sy:1:f*sy);\nz1=zeros(size(x1));\n\n[x2,z2]=meshgrid(-f*sy:1:f*sy);\ny2=zeros(size(x2));\n\n[y3,z3]=meshgrid(-f*sy:1:f*sy);\nx3=zeros(size(y3));\n\n%%\n%Visualize\nhf=cFigure; hold on;\n\nh4=gpatch(F,V,'rw','none',0.5);\nsurf(x1,y1,z1,'EdgeColor','k','faceColor',1*ones(1,3),'EdgeAlpha',0.5,'FaceAlpha',0.1,'LineWidth',lineWidth1);\nsurf(x2,y2,z2,'EdgeColor','k','faceColor',1*ones(1,3),'EdgeAlpha',0.5,'FaceAlpha',0.1,'LineWidth',lineWidth1);\nsurf(x3,y3,z3,'EdgeColor','k','faceColor',1*ones(1,3),'EdgeAlpha',0.5,'FaceAlpha',0.1,'LineWidth',lineWidth1);\n\nh1=quiverVec([0 0 0],[1 0 0],sy,colorSet(1,:));\nh2=quiverVec([0 0 0],[0 1 0],sy,colorSet(2,:));\nh3=quiverVec([0 0 0],[0 0 1],sy,colorSet(3,:));\n\nh5=plotV([-1 -1 -1; 1 1 1],'k--','LineWidth',lineWidth2); %Hydrostatic axis\n\nh6=plotV(v12,'r-','LineWidth',lineWidth2);\nh6.Color=(colorSet(1,:)+colorSet(2,:))/2;\n\nh7=plotV(v13,'r-','LineWidth',lineWidth2);\nh7.Color=(colorSet(1,:)+colorSet(3,:))/2;\n\nh8=plotV(v23,'r-','LineWidth',lineWidth2);\nh8.Color=(colorSet(2,:)+colorSet(3,:))/2;\n\nhAxis=gca;\nhAxis.XRuler.FirstCrossoverValue = 0; % X crossover with Y axis\nhAxis.YRuler.FirstCrossoverValue = 0; % Y crossover with X axis\nhAxis.ZRuler.FirstCrossoverValue = 0; % Z crossover with X axis\nhAxis.XRuler.SecondCrossoverValue = 0; % X crossover with Z axis\nhAxis.YRuler.SecondCrossoverValue = 0; % Y crossover with Z axis\nhAxis.ZRuler.SecondCrossoverValue = 0; % Z crossover with Y axis\n\ntext(0.5+f*sy,0,0,'$\\sigma_1$','Interpreter','Latex','FontSize',fontSizeText);\ntext(0,0.5+f*sy,0,'$\\sigma_2$','Interpreter','Latex','FontSize',fontSizeText);\ntext(0,0,0.5+f*sy,'$\\sigma_3$','Interpreter','Latex','FontSize',fontSizeText);\n\nxticks(-f*sy:0.5:f*sy);\nyticks(-f*sy:0.5:f*sy);\nzticks(-f*sy:0.5:f*sy);\n\nlegend([h1 h2 h3 h4 h5 h6 h7 h8],{'$\\sigma_1$ axis','$\\sigma_2$ axis','$\\sigma_3$ axis',...\n 'Von Mises yield surface',...\n 'Hydrostatic line',...\n 'yield ellipse $\\sigma_3=0$','yield ellipse $\\sigma_2=0$','yield ellipse $\\sigma_1=0$'...\n },'Interpreter','Latex');\n\naxis tight; axis equal; axis vis3d; view(3); %box on; \ncamlight headlight; \naxis(f*sy*[-1 1 -1 1 -1 1])\nset(gca,'FontSize',fontSizeAxis,'LineWidth',lineWidthAxis);\ngdrawnow;\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_visualization_von_mises_plasticity_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6434828029756687}} {"text": "%s = rand('twister');\n%rand('twister', s);\n\nlen = 200; % number of 1st level observations (time points within subjects)\nsub = 20; % number of second-level units (subjects)\n\nfixed_slope = 0.5; % population fixed-effect slope\nfixed_int = 0.3; % pop. fixed-effect intercept\n\nrand_slope = 0.5; % 'true' random effect standard dev: slope\nrand_int = 0.5; % 'true' random effect standard dev: intercept\n\nnoise_sigma = 0.5; % measurement error/unexplained std of 1st level observations\nbetween_sigma = 0.5; % measurement error/unexplained std of 2nd level covariate\n\n% Generate simulated data\n% 1) create predictors\nx = zeros(len,sub);\ny = x;\nx(11:20,:) = 1; \nx(111:120,:) = 1; \n\n% 2) Create instances of effects for each subject\nc = normrnd(fixed_slope, rand_slope, sub, 1); % slope between-subjects variations\nd = normrnd(fixed_int, rand_int, sub, 1); % intercept between-subjects variations\n\n% 3) Create a between-ss covariate that is related to the slope but not the\n% intercept\ncovt = scale(c + normrnd(0, between_sigma, sub, 1), 1);\n\n% 4) Create a between-ss covariate that is related to the intercept but not the\n% intercept\ncovti = scale(d + normrnd(0, between_sigma, sub, 1), 1);\n\ncorrcoef([c d covt covti])\n\n% Add between-subjects error (random effects) and measurement noise\n% (within-subjects error)\n\nfor i=1:sub\n y(:,i) = d(i) + c(i) .* x(:,i) + normrnd(0, noise_sigma, len, 1);\nend\n\n%% Run the model - without a 2nd-level covariate\nout = igls(y, x); % for igls\nfprintf('\\t\\t%s\\t%s\\t%s\\t\\n', 'Effect', 'Intercept', 'Slope');\ndisp('True random-effect variances:'); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', [rand_slope rand_int]);\n\ndisp('Input random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', std([d c]))\n\ndisp('Est. random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', sqrt(out.betastar)');\n\n%% Run the model - with an unrelated 2nd-level covariate\nout = igls(y, x, 'covariate', (1:20)'); % for igls\nfprintf('\\t\\t%s\\t%s\\t%s\\t\\n', 'Effect', 'Intercept', 'Slope');\ndisp('True random-effect variances:'); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', [rand_slope rand_int]);\n\ndisp('Input random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', std([d c]))\n\ndisp('Est. random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', sqrt(out.betastar)');\n\n%% Run the model - with a 2nd-level covariate related to slope\nout = igls(y, x, 'covariate', covt); % for igls\nfprintf('\\t\\t%s\\t%s\\t%s\\t\\n', 'Effect', 'Intercept', 'Slope');\ndisp('True random-effect variances:'); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', [rand_slope rand_int]);\n\ndisp('Input random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', std([d c]))\n\ndisp('Est. random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', sqrt(out.betastar)');\n\n%% Run the model - with a 2nd-level covariate related to intercept\nout = igls(y, x, 'covariate', covti); % for igls\nfprintf('\\t\\t%s\\t%s\\t%s\\t\\n', 'Effect', 'Intercept', 'Slope');\ndisp('True random-effect variances:'); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', [rand_slope rand_int]);\n\ndisp('Input random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', std([d c]))\n\ndisp('Est. random-effect variances: '); \nfprintf('\\t\\t\\t%3.3f\\t%3.3f\\n', sqrt(out.betastar)');\n\n%%\nclear *pvals* *fpr*\n\nmytype = 'i';\niterations = 200;\n\nlen = 100; sub = 10;\n\nfixpvals = zeros(iterations, 2);\nrandpvals = zeros(iterations, 2);\nLRTrandpvals = zeros(iterations, 2);\nchic = zeros(iterations, 1);\nchid = zeros(iterations, 1);\n\nc_fixed = 0; % slope pop. average\nd_fixed = 0; % intercept pop. average\nc_rand = 0; % slope std across Ss\nd_rand = 0; % intercept std.\nnoise_std = 2.0; % within-subjects noise std\n\nx = zeros(len,sub);\ny = x;\nx(1:2:end,:) = 1; % create signal\n\n% --------------------------------------------------------------------------\n% This block: No true random effects, so test false positive rate for\n% p_randvariance\n\nverbstr = 'noverbose';\n\nfor i = 1:iterations\n \n \n c = normrnd(c_fixed,c_rand,sub,1); % slope between-subjects variations\n d = normrnd(d_fixed,d_rand,sub,1); % intercept between-subjects variations\n \n % Add between-subjects error (random effects) and measurement noise\n % (within-subjects error)\n y = zeros(len, sub); \n for s = 1:sub\n y(:,s) = d(s) + c(s) .* x(:,s) + normrnd(0,noise_std,len,1);\n end\n out = igls(y, x, 'type', mytype, verbstr); % for igls\n \n fpr_converged(i) = out.isconverged;\n \n \n fpr_betastar(i, :) = out.betastar';\n \n fixpvals(i, :) = out.p;\n randpvals(i, :) = out.p_randvariance'; %[out.p_randvariance_d out.p_randvariance_c];\n \n LRTrandpvals(i, :) = out.pLRT_randvariance';\n \n if mod(i, 10) == 0, fprintf(1, '%3.0f ', i); end\n \n verbstr = 'noverbose';\nend\nfprintf('\\n')\n\n%pvals_fpr = pvals;\nalph = .1;\n\nfixfpr = sum(fixpvals < alph) ./ iterations;\nrandfpr = sum(randpvals < alph) ./ iterations;\nLRTfpr = sum(LRTrandpvals < alph) ./ iterations;\n\nfprintf('\\tfixed\\t\\trand fx\\t\\t\\n');\nfprintf('TPR/FPR @ alpha = %3.3f:\\t%3.5f\\t%3.5f\\t%3.5f\\t%3.5f\\t%3.5f\\t%3.5f\\n', alph, fixfpr, randfpr, LRTfpr);", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/Iterative_Generalized_Least_Squares/igls_sim_fpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6434666713391762}} {"text": "classdef OrthogonalLeastSquares < handle\n %CSOLSAPPROX Implements OLS algorithm for sparse approximation\n \n properties\n % Maximum residual norm\n MaxResNorm = 1e-4\n % Indicates if we should stop on exceeding residual norm\n StopOnResidualNorm = true\n % Indicates if we should stop when residual norm stops improving\n StopOnResNormStable = true\n % Maximum number of iterations for approximation\n MaxIters\n Verbose = false\n % Minimum Sparsity\n MinK = 4\n % Ignored atom (which won't be considered in identification step)\n IgnoredAtom = -1\n end\n \n properties(SetAccess=private)\n % The dictionary\n Dict\n % Ambient signal dimensions\n N\n % Number of atoms in dictionary\n D\n % Sparsity level of representations (may be negative)\n K\n % Result of a solver\n result\n end\n \n methods\n function self = OrthogonalLeastSquares(Dict, K)\n % We assume that all the columns in dictionary are normalized.\n if isa(Dict, 'spx.dict.Operator')\n self.Dict = Dict;\n elseif ismatrix(Dict)\n self.Dict = spx.dict.MatrixOperator(Dict); \n else\n error('Unsupported operator.');\n end\n [self.N, self.D] = size(Dict);\n if ~exist('K', 'var')\n % No sparsity level has been pre-specified.\n K = -1;\n end\n self.K = K;\n % Maximum number of iterations\n maxIter = self.N;\n if K > 0\n % We have to consider pre-specified sparsity level\n maxIter = K;\n end\n self.MaxIters = maxIter;\n if K > 0 && self.MinK >= K\n self.MinK = 0;\n end\n end\n \n\n function result = solve(self,y)\n % Uses QR factorization to implement the OLS \n\n % Initialization\n % Solves approximation problem using OLS\n d = self.D;\n n = self.N;\n r = y;\n min_k = self.MinK;\n dict = self.Dict;\n % Active indices \n omega = [];\n if self.StopOnResNormStable\n oldResNorm = norm(r);\n end\n maxIter = self.MaxIters;\n % Create space for storing the Q R factors\n Q = zeros(n, maxIter);\n R = zeros(maxIter);\n % zr stores projections of y along the directions\n % in Q. \n % Since vectors in Q are orthonormal, \n % hence computing projections is as easy as \n % taking inner product.\n % This also simplifies the process of updating\n % the residual as the residual is orthogonal \n % to the vectors selected in Q so far.\n zr = [];\n\n ignored_atom = self.IgnoredAtom;\n % Convert the dictionary into a matrix\n dict = double(dict);\n\n for iter=1:maxIter\n % The Q part of previous iteration\n QLast = Q(:, 1:iter-1); % n * (k - 1)\n % The Orthogonal Projector\n OrthoProjector = eye(n) - QLast * QLast';\n % Orthogonalize the remaining atoms of the dictionary\n qdict = OrthoProjector * dict;\n % Normalize the columns\n qdict = spx.norm.normalize_l2(qdict);\n % Compute inner products\n innerProducts = qdict' * r;\n % Mark the inner products of already selected columns as 0.\n innerProducts(omega) = 0;\n innerProducts = abs(innerProducts);\n if ignored_atom > 0\n % forcefully ignore this atom\n innerProducts(ignored_atom) = 0;\n end \n % Find the highest inner product\n [~, index] = max(innerProducts);\n % Add this index to support\n omega = [omega, index];\n % Pick the new atom from the dictionary\n new_atom = dict(:, index);\n % Orthogonalize the new atom\n %Compute projections to previously selected vectors in Q\n projections = QLast'* new_atom;\n % Remove the projection\n new_q = new_atom - QLast * projections;\n % Normalize\n norm_q = norm(new_q);\n new_q = new_q / norm_q;\n % Place it \n Q(:, iter) = new_q;\n % Update R\n R(1:iter-1, iter) = projections;\n R(iter, iter) = norm_q;\n % Compute the projection of y on new q.\n zr(iter) = new_q' * y;\n % Let us update the residual.\n r = r - zr(iter) * new_q;\n if self.StopOnResidualNorm || self.StopOnResNormStable\n resNorm = norm(r);\n if resNorm < self.MaxResNorm && iter > min_k\n break;\n end\n if self.StopOnResNormStable\n change = abs(oldResNorm - resNorm);\n if change/oldResNorm < .01 && iter > min_k\n % No improvement\n break;\n end\n end\n end\n end\n % Estimate\n z = zeros(d, 1);\n % We need to use back-substitution with R to get z from zr.\n opts.UT = true;\n tmp = linsolve(R(1:iter,1:iter), zr(1:iter)', opts);\n z(omega)= tmp;\n % Solution vector\n result.z = z;\n % Residual obtained\n result.r = r;\n % residual norm\n result.rnorm = resNorm;\n % Number of iterations\n result.iterations = iter;\n % Solution support\n result.support = omega;\n self.result = result;\n end\n \n end\n\nend\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+pursuit/+single/OrthogonalLeastSquares.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6434666611574752}} {"text": "function fem1d_bvp_linear_test02 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_BVP_LINEAR_TEST02 carries out test case #2.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/fem1d_bvp_linear/fem1d_bvp_linear_test02.m\n%\n% Discussion:\n%\n% Use A2, C2, F2, EXACT2, EXACT_UX2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dianne O'Leary,\n% Scientific Computing with Case Studies,\n% SIAM, 2008,\n% ISBN13: 978-0-898716-66-5,\n% LC: QA401.O44.\n%\n n = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_BVP_LINEAR_TEST02\\n' );\n fprintf ( 1, ' Solve -( A(x) U''(x) )'' + C(x) U(x) = F(x)\\n' );\n fprintf ( 1, ' for 0 < x < 1, with U(0) = U(1) = 0.\\n' );\n fprintf ( 1, ' A2(X) = 1.0\\n' );\n fprintf ( 1, ' C2(X) = 2.0\\n' );\n fprintf ( 1, ' F2(X) = X * ( 5 - X ) * exp ( X )\\n' );\n fprintf ( 1, ' U2(X) = X * ( 1 - X ) * exp ( X )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', n );\n%\n% Geometry definitions.\n%\n x_first = 0.0;\n x_last = 1.0;\n x = linspace ( x_first, x_last, n );\n x = x(:);\n\n u = fem1d_bvp_linear ( n, @a2, @c2, @f2, x );\n\n uexact = exact2 ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X U Uexact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %4d %8f %8f %8f %8e\\n', ...\n i, x(i), u(i), uexact(i), abs ( u(i) - uexact(i) ) );\n end\n\n e1 = l1_error ( n, x, u, @exact2 );\n e2 = l2_error_linear ( n, x, u, @exact2 );\n h1s = h1s_error_linear ( n, x, u, @exact_ux2 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' l1 norm of error = %g\\n', e1 );\n fprintf ( 1, ' L2 norm of error = %g\\n', e2 );\n fprintf ( 1, ' Seminorm of error = %g\\n', h1s );\n\n return\nend\nfunction value = a2 ( x )\n\n%*****************************************************************************80\n%\n%% A2 evaluates A function #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of A(X).\n%\n value = 1.0;\n\n return\nend\nfunction value = c2 ( x )\n\n%*****************************************************************************80\n%\n%% C2 evaluates C function #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of C(X).\n%\n value = 2.0;\n\n return\nend\nfunction value = exact2 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT2 evaluates exact solution #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of U(X).\n%\n value = x .* ( 1.0 - x ) .* exp ( x );\n\n return\nend\nfunction value = exact_ux2 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT_UX2 evaluates the derivative of exact solution #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX(X).\n%\n value = ( 1.0 - x - x .* x ) .* exp ( x );\n\n return\nend\nfunction value = f2 ( x )\n\n%*****************************************************************************80\n%\n%% F2 evaluates right hand side function #2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n value = x .* ( 5.0 - x ) .* exp ( x );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_bvp_linear/fem1d_bvp_linear_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6431961812443507}} {"text": "function varargout = projPointOnPolyline(point, poly, varargin)\n%PROJPOINTONPOLYLINE Compute position of a point projected on a polyline.\n%\n% POS = projPointOnPolyline(POINT, POLYLINE)\n% Compute the position of the orthogonal projection of a point on a\n% polyline.\n% POINT is a 1-by-2 row vector containing point coordinates\n% POLYLINE is a N-by-2 array containing coordinates of polyline vertices\n% POS is the position of the point on the polyline, between 0 and the\n% number of vertices of the polyline. POS can be a non-integer value, in\n% this case, the integer part corresponds to the polyline edge index\n% (between 0 and Nv-1), and the floating-point part corresponds to the\n% relative position on i-th edge (between 0 and 1, 0: edge start, 1: edge\n% end).\n%\n% When POINT is an array of points, returns a column vector with as many\n% rows as the number of points.\n%\n% POS = projPointOnPolyline(POINT, POLYLINE, CLOSED)\n% Specifies if the polyline is closed or not. CLOSED can be one of:\n% 'closed' -> the polyline is closed\n% 'open' -> the polyline is open\n% a column vector of logical with the same number of elements as the\n% number of points -> specify individually if each polyline is\n% closed (true=closed).\n%\n% [POS, DIST] = projPointOnPolyline(...)\n% Also returns the distance between POINT and POLYLINE.\n%\n% Example\n% poly = [10 10; 20 10;20 20;10 20];\n% projPointOnPolyline([15 0], poly)\n% ans =\n% 0.5000\n% projPointOnPolyline([0 16], poly)\n% ans =\n% 3.0000\n%\n% See also \n% points2d, polygons2d, polylinePoint, projPointOnPolygon\n% distancePointPolyline\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@nantes.inra.fr\n% Created: 2009-04-30, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009-2022 INRA - Cepia Software Platform\n\n% check if input polyline is closed or not\nclosed = false;\nif ~isempty(varargin)\n var = varargin{1};\n if strcmp('closed', var)\n closed = true;\n elseif strcmp('open', var)\n closed = false;\n elseif islogical(var)\n closed = var;\n end\nend\n\n% closes the polyline if necessary\nif closed\n poly = [poly ; poly(1,:)];\nend\n\n% number of points\nNp = size(point, 1);\n\n% allocate memory results\npos = zeros(Np, 1);\nminDist = inf*ones(Np, 1);\n\n% iterate on points\nfor p = 1:Np\n % build set of edges\n edges = [poly(1:end-1, :) poly(2:end, :)];\n \n % compute distance between current point and all edges\n [dist, edgePos] = distancePointEdge(point(p, :), edges);\n \n % update distance and position if necessary\n [minDist(p), edgeIndex] = min(dist);\n pos(p) = edgeIndex - 1 + edgePos(edgeIndex); \nend\n\n% process output arguments\nif nargout <= 1\n varargout{1} = pos;\nelseif nargout == 2\n varargout{1} = pos;\n varargout{2} = minDist;\nend\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/polygons2d/projPointOnPolyline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6431961617340181}} {"text": "%GIKINE Shoulder inverse kinematics of HAL-like right shoulder\n%\n% Computes the inverse kinematics of the right shoulder which is the \n% same kinematically as a HAL object. This function is mainly useful \n% for procedures which require many, many calls, so time can be saved \n% by not referencing a HAL object.\n%\n% Copyright (C) Bryan Moutrie, 2013-2014\n% Licensed under the GNU Lesser General Public License\n% see full file for full statement\n%\n% Syntax:\n% (1) [q1, q2] = gikine(Tg, Tu)\n%\n% Outputs:\n% q1 : First family of solutions (mx3 matrix where m = size(Tu,3))\n% q2 : Second family of solutions (mx3 matrix where m = size(Tu,3))\n%\n% Inputs:\n% Tg : Transformation matrix of the shoulder frame. x, y, z point to\n% the right, above, and behind the person. Translation is\n% shoulder center of rotation\n% Tu : Transformation matrix of the upper arm frame. May be a 4x4xm\n% series of frames (or higher order, which is compressed to 3D)\n%\n% See also HAL HAL.gikine HAL.ikine wikine\n\n% LICENSE STATEMENT:\n%\n% This file is part of pHRIWARE.\n% \n%% pHRIWARE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as \n% published by the Free Software Foundation, either version 3 of \n% the License, or (at your option) any later version.\n%\n% pHRIWARE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public \n% License along with pHRIWARE. If not, see .\n%\n% RTB LIBRARY:\n%\n% Copyright (C) 199q3-2014, by Peter I. Corke\n% http://www.petercorke.com\n% Released under the GNU Lesser General Public license,\n% Modified 16/7/2014 (HAL is a subclass of SerialLink)\n\nfunction [q1, q2] = gikine(Tg, Tu)\n\nRg = Tg(1:3,1:3);\ngRu0 = [0 0 -1; 0 1 0; 1 0 0]';\nu0R = (Rg*gRu0)';\n\nu0Ru = reshape(u0R*reshape(Tu(1:3,1:3,:),3,[]),3,3,[]);\n\n%-X,Z,Y Tait-Bryan angles\n\n% Family 1:\nq1(:,1) = squeeze(atan2(-u0Ru(3,2,:),u0Ru(2,2,:)));\nq1(:,2) = squeeze(asin(-u0Ru(1,2,:)));\nq1(:,3) = squeeze(atan2(-u0Ru(1,3,:),u0Ru(1,1,:)));\n\n% Make -pi values pi so that they are deemed within joint limits\nfix = q1 <= (-pi+1e-4);\nq1(fix) = pi;\n\n% Family 2:\nq2(:,1) = squeeze(atan2(u0Ru(3,2,:),-u0Ru(2,2,:)));\nq2(:,2) = pi-q1(:,2);\nq2(:,3) = squeeze(atan2(u0Ru(1,3,:),-u0Ru(1,1,:)));\nend", "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/contrib/pHRIWARE/Functions/gikine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6431641989419151}} {"text": "function [azimuth, dist]=indirectRhumbProblem(latLonStart,latLonEnd,height,useHeightApprox,a,f,numSteps4Circ)\n%INDIRECTRHUMBPROBLEM Given a starting and ending latitude and longitude on\n% a reference ellipsoid, determine the heading (in\n% radians East of North) and the distance one must\n% travel on the shortest constant-heading course to go\n% from the starting point to the stopping point. A\n% constant heading course follows a rhumb line\n% (loxodrome) and is usually not the shortest path\n% between two points.\n%\n%INPUTS: latLonStart A 2X1 vector of the starting ellipsoidal latitude\n% (North) and longitude (East) in radians. This cannot\n% be a pole.\n% latLonEnd A 2X1 vector of the ending ellipsoidal latitude\n% (North) and longitude (East) in radians.\n% height The height above the reference ellipsoid at which the\n% trajectory should be determined. This changes the\n% distance traveled, but not the azimuthal angle of\n% departure. If this parameter is omitted, then the\n% default value of 0 is used.\n% useHeightApprox If true, and the height is not zero, then an\n% approximation is made for how dist scales with\n% altitude. Specifically, an equiatorial trajectory will\n% scale as (a+height)/a. Thus, this scaling factor is\n% applied to any trajectory to scale dist with altitude.\n% If height is false, a significantly slower iterative\n% optimization technique is used. The default value is\n% true. The difference made when useHeightApprox=false is\n% can generally be assumed to be less than 80m. This\n% parameter is ignored if height=0.\n% a The semi-major axis of the reference ellipsoid. If\n% this argument is omitted, the value in\n% Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the reference ellipsoid. If\n% this argument is omitted, the value in\n% Constants.WGS84Flattening is used.\n% numSteps4Circ If height!=0 then an algorithm propagating a state\n% in ECEF coordinates around the curved Earth is used to\n% solve the direct geodetic problem as a step in solving\n% the indirect geodetic problem. This parameter\n% determines the number of steps that would be needed in\n% the direct geodetic problem for a target that\n% circumnavigates the globe around the equator. The\n% default value if this parameter is not provided is\n% 2000. A value of 6000 appears to be about the best\n% number for overall precision. Reducing the number of\n% steps will speed up the function. This parameter is not\n% used if height=0.\n%\n%OUTPUTS: azimuth The constant heading in radians East of North that one\n% must travel to go on a constant-heading course from\n% latLonStart to latLonEnd.\n% dist The distance that one must travel on a constant-heading\n% course to go from latLonStart to latLonEnd.\n%\n%If height=0, the algorithm is mostly taken from [1]. However, a formula\n%using isometric latitudes, which are described in Chapter 3 of [2] to get\n%the azimuth angle was used, because it is simpler. The formula is also\n%explicitly mentioned in Equation 3 of [3]. However, the expression for\n%computing the distance from that paper is only for a sphere, not for an \n%ellipsoid, which is why the Carlton-Wippern distance computation using an\n%incomplete elliptic integral of the second kind is preferred.\n%\n%When the azimuth found by the technique is very close to +/-pi/2 (when one\n%is traveling at nearly a constant latitude), the distance computation\n%switches to assume that the latitude is indeed constant even if\n%latLonStart(1)!=latLonStart(2). This avoid precision problems that arise\n%as a very small number is multiplied by a very large number. However, this\n%reduces the accuracy of the method.\n%\n%Generally, calling directRhumbProblem or directRhumbProbGen with the\n%azimuth and dist returned by this function will return latLonStart.\n%However, if the stopping point is at a pole, then directRhumbProblem will\n%correctly return a polar location, but the longitude will generally be\n%wrong.\n%\n%When height!=0, the algorithm can be significantly slower if no\n%approximation is used. Around the equator, the distance scales as\n%(a+height)/a*dist as one changes the ellipsoidal height. This scaling\n%applied to dist in non-equatorial trajectories is the approximation if\n%useHeightApprox=true. When useHeightApprox=false, the approximate value\n%is used to determine the bounds around which the fminbnd function\n%searches. The maximum error in the approximation is expected to be less\n%than 80m. The search region for the value of dist used in the fminbnd\n%function was set to 0.9*dist to 1.1*dist, where dist is the distance\n%obtained after scaling the distance from the zero-altitude solution.\n%\n%EXAMPLE:\n%A trajectory that crosses the international date line and and goes from\n%the Northern hemisphere to the southern hemisphere. We also compute the\n%reverse path and show that the azimuth angles in each direction are\n%consistent with each other. We then plot the trajectory on an image of the\n%spherical Earth.\n% N=100;\n% latStart=degMinSec2Rad(37,47.5);\n% lonStart=degMinSec2Rad(-122,-27.8);\n% latEnd=degMinSec2Rad(-33,-51.7);\n% lonEnd=degMinSec2Rad(151,12.7);\n% \n% latLonStart=[latStart;lonStart];\n% latLonEnd=[latEnd;lonEnd];\n% [azimuth,dist]=indirectRhumbProblem(latLonStart,latLonEnd);\n% [azEnd,distRev]=indirectRhumbProblem(latLonEnd,latLonStart);\n% \n% %If the forward and reverse estimates agree, then these values will\n% %ideally be zero.\n% azimuth-(-azEnd)\n% dist-distRev\n% \n% distVals=linspace(0,dist,N);\n% latLonWayPoints=directRhumbProblem(latLonStart,azimuth,distVals);\n% \n% %Show that the approximate direct algorithm reaches nearly the same\n% %endpoint as the indirect algorithm.\n% xEndWay=ellips2Cart([latLonWayPoints(:,end);0]);\n% xEnd=ellips2Cart([latLonEnd;0]);\n% max(abs(xEndWay-xEnd))\n% max(abs(wrapRange(latLonWayPoints(:,end)-latLonEnd,-pi,pi)))\n% \n% xStartCart=ellips2Cart([latLonStart;0]);\n% xEndCart=ellips2Cart([latLonEnd;0]);\n% %The path is displayed slightly above the Earth's surface to make it\n% %easier to see.\n% pathPoints=ellips2Cart([latLonWayPoints;0.02*ones(1,N)]);\n% \n% figure(1)\n% clf\n% hold on\n% plotMapOnEllipsoid([]);\n% scatter3(xStartCart(1),xStartCart(2),xStartCart(3),100,'filled')\n% scatter3(xEndCart(1),xEndCart(2),xEndCart(3),100,'filled')\n% plot3(pathPoints(1,:),pathPoints(2,:),pathPoints(3,:),'-r','linewidth',4)\n%\n%REFERENCES:\n%[1] K. C. Carlton-Wippern, \"On loxodromic navigation,\" Journal of\n% Navigation, vol. 45, no. 2, pp. 292-297, May 1992.\n%[2] J. P. Snyder, \"Map projections- a working manual,\" U.S. Geological\n% Survey, Tech. Rep. 1395, 1987.\n%[3] J. Alexander, \"Loxodromes: A rhumb way to go,\" Mathematics Magazine,\n% vol. 77, no. 5, pp. 349-356, Dec. 2004.\n%\n%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<7||isempty(numSteps4Circ))\n numSteps4Circ=2000; \nend\n\nif(nargin<6||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<5||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(nargin<4||isempty(useHeightApprox))\n useHeightApprox=true; \nend\n\nif(nargin<3||isempty(height))\n height=0; \nend\n\n%Extract the components\nlatStart=latLonStart(1);\nlonStart=latLonStart(2);\nlatEnd=latLonEnd(1);\nlonEnd=latLonEnd(2);\n\n%The first numerical eccentricity of the ellipsoid.\ne=sqrt(2*f-f^2);\n\n%Convert the ellipsoidal latitudes to reduced co-latitudes. A co-latitude\n%is pi/2 minus the latitude. Also, \nnu1=pi/2-ellipsLat2ReducedLat(latStart,f);\nnu2=pi/2-ellipsLat2ReducedLat(latEnd,f);\n\n%Though not mentioned in the above papers, the difference in the longitudes\n%must be wrapped to the range of -pi/pi or else one will get useless\n%results when crossing the -pi/pi boundary.\nnum=wrapRange(lonEnd-lonStart,-pi,pi,false);\n%Equation 11 in the paper provides an expression to get the azimuth.\n%however, it is simpler if one just uses isometric latitudes.\nval1=ellipsLat2IsoLat(latStart,f);\nval2=ellipsLat2IsoLat(latEnd,f);\n\nif(~isfinite(val1))\n warning('The starting point is located at a geographic pole. Azimuth values will be inaccurate.')\nend\n\nif(isfinite(val1)||isfinite(val2))\n %This will properly return 0 and pi for infinite values of val1 when\n %val2 is finite and vice versa, which corresponds to headings to or\n %from a pole.\n denom=val2-val1;\n azimuth=atan2(num,denom);\nelse%If neither is finite, then that is the case where one is going from\n %pole to pole. In such an instance, just set the heading to 0, if going\n %North, and pi, if going South.\n \n if(latStart>latEnd)\n azimuth=pi;\n else\n azimuth=0;\n end\nend\n\n%The distance \nif(abs(abs(azimuth)-pi/2)>2e-8)\n %Equation 12 in the paper.\n dist=a*abs(sec(azimuth))*abs(ellipIntInc2Kind(nu2,e^2)-ellipIntInc2Kind(nu1,e^2));\nelse\n %Equation 14b in the paper.\n dist=a*abs(sin(nu1))*abs(wrapRange(lonEnd-lonStart,-pi,pi));\nend\n\n%If a non-zero height is given, then iterate over the direct rhumb\n%problem at height to determine the solution.\nif(height~=0)\n endCart=ellips2Cart([latLonEnd;height],a,f);\n\n %The approximate scaling for the height.\n dist=((a+height)/a)*dist;\n \n %If a computationally-intensive but more precise algorithm to search\n %for the true distance at altitude should be used instead of a\n %simple approximation of scaling the distance.\n if(useHeightApprox==false)\n %Assume that the correct height-adjusted distance is within 10% of the\n %scaled distance value.\n distFun=@(distCur)distCostFunc(distCur,endCart,latLonStart,azimuth,height,a,f,numSteps4Circ);\n dist=fminbnd(distFun,0.9*dist,1.1*dist);\n end\nend\nend\n\nfunction cost=distCostFunc(distCur,endCart,latLonStart,azStart,height,a,f,numSteps4Circ)\n latLonCalc=directRhumbProbGen(latLonStart,azStart,distCur,height,false,a,f,numSteps4Circ);\n cost=norm(ellips2Cart([latLonCalc;height],a,f)-endCart);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Navigation/indirectRhumbProblem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6431641931141091}} {"text": "% Fast Inter-Harmonic Reconstruction as a pre-process for LPC-based\n% spectral envelope estimation.\n%\n%\n% Description\n% This technique reconstructs inter-harmonics of the voice signal,\n% as a pre-process for an efficient spectral envelope estimation in\n% high-pitched voices. The technique is fully described in [1].\n\n%\n% Inputs\n% wave : [samples] [Nx1] input signal (speech signal)\n% Fs : [Hz] [1x1] sampling frequency\n% f0 : F0 estimate (a 0 value is for an unvoiced frame)\n% order : Order used for the LP analysis\n%\n%\n% Outputs\n% LP : LP coefficients\n% Energy : energy of the frame\n% \n%\n% Example\n% Please see the HOWTO_envelope.m example file.\n% Please see http://tcts.fpms.ac.be/~drugman/Toolbox/ for more details.\n%\n% References\n% [1] T.Drugman, Y. Stylianou, \"Fast Inter-Harmonic Reconstruction for\n% Spectral Envelope Estimation in High-Pitched Voices\", vol. 21, pp.\n% 1418-1422, IEEE Signal Processing Letters, 2014.\n% http://tcts.fpms.ac.be/~drugman/files/SPL-FIHR.pdf\n%\n% Copyright (c) 2014 Toshiba Cambridge Research Laboratory\n%\n% License\n% This code will be part of the GLOAT toolbox with the following\n% licence:\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% This function will also be part of the Covarep project: http://covarep.github.io/covarep\n%\n% Author\n% Thomas Drugman thomas.drugman@umons.ac.be\n\nfunction [LP,Energy] = env_fihr(Seg,Fs,F0_local,order)\n\n\nF0_target=100;\n% F0* in the paper. Here set to 100 Hz.\n\nEnergy=sum(Seg.^2);\n\nif F0_local>0\n \n TmpSignal=ones(1,length(Seg));\n t_tmp=1:length(TmpSignal);\n \n I=ceil(F0_local/F0_target);\n for k=1:I-1\n W=(I-k)/I;\n % We use here a linear weighting function. Other functions are\n % possible, as long as they meet the properties mentioned in\n % the paper.\n TmpSignal=TmpSignal+2*W*cos(2*pi*(k/I)*F0_local/Fs*t_tmp);\n \n % Equation (2) in the paper\n end\n \n Seg2=Seg.*TmpSignal';\nelse\n Seg2=Seg;\nend\n\nLP=lpc(Seg2,order);\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/envelope/env_fihr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519543581257}} {"text": "function [ a_lu, info ] = r8pbu_fa ( n, mu, a )\n\n%*****************************************************************************80\n%\n%% R8PBU_FA factors a R8PBU matrix.\n%\n% Discussion:\n%\n% The R8PBU storage format is for a symmetric positive definite band matrix.\n%\n% To save storage, only the diagonal and upper triangle of A is stored,\n% in a compact diagonal format that preserves columns.\n%\n% The diagonal is stored in row MU+1 of the array.\n% The first superdiagonal in row MU, columns 2 through N.\n% The second superdiagonal in row MU-1, columns 3 through N.\n% The MU-th superdiagonal in row 1, columns MU+1 through N.\n%\n% The matrix A must be a positive definite symmetric band matrix.\n%\n% Once factored, linear systems A*x=b involving the matrix can be solved\n% by calling R8PBU_SL. No pivoting is performed. Pivoting is not necessary\n% for positive definite symmetric matrices. If the matrix is not positive\n% definite, the algorithm may behave correctly, but it is also possible\n% that an illegal divide by zero will occur.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 October 1998\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Bunch, Moler, Stewart,\n% LINPACK User's Guide,\n% SIAM, Philadelphia, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer MU, the number of superdiagonals of the matrix.\n% MU must be at least 0, and no more than N-1.\n%\n% Input, real A(MU+1,N), the N by N matrix, stored in LINPACK\n% positive definite symmetric band matrix storage.\n%\n% Output, real A_LU(MU+1,N), information describing a factored form\n% of the matrix, that can be used to solve linear systems\n% A*x=b, using R8PBU_SL.\n%\n% Output, integer INFO, singularity flag.\n% 0, the matrix is nonsingular.\n% nonzero, the matrix is singular.\n%\n info = 0;\n a_lu(1:mu+1,1:n) = a(1:mu+1,1:n);\n\n for j = 1 : n\n\n ik = mu + 1;\n jk = max ( j - mu, 1 );\n mm = max ( mu + 2 - j, 1 );\n\n s = 0.0;\n\n for k = mm : mu\n\n a_lu(k,j) = ( a_lu(k,j) - a_lu(ik:ik+k-mm-1,jk)' * a_lu(mm:k-1,j) )...\n / a_lu(mu+1,jk);\n\n s = s + a_lu(k,j) * a_lu(k,j);\n\n ik = ik - 1;\n jk = jk + 1;\n\n end\n\n s = a_lu(mu+1,j) - s;\n\n if ( s <= 0.0 )\n info = j;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8PBU_FA - Fatal error!\\n' );\n fprintf ( 1, ' Nonpositive pivot on step %d\\n', info );\n return;\n end\n\n a_lu(mu+1,j) = sqrt ( s );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8pbu_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6431519533804076}} {"text": "function model = ml_trainrvm(varargin)\n% Learn a probabilistic (non-)linear model, via the Relevance Vector Machine.\n% Model = ml_trainrvm(Trials, Targets, Options...)\n%\n% The Relevance Vector Machine [1] is a Bayesian equivalent to the popular Support Vector Machines\n% (SVMs) [2]. RVMs can be used for general-purpose linear or non-linear (kernelized) classification\n% or regression, and produce state-of-the-art results in most cases. Various kernels are supplied,\n% where the rbf kernel is usually the best initial choice. In the non-linear case, the kernel\n% scaling parameter should be found via parameter search, which can be time-consuming. In contrast\n% to SVMs, Relevance Vector Machines give probablistic outputs, which can be practical when multiple\n% uncertain predictions are to be fused, etc. In the future, an implementation of RVMs using convex\n% optimization will be provided, which is assumed to give better optimality guarantees than the\n% current implementation [3,4,5].\n%\n% RVMs (as well as kernel SVMs) are the most versatile general-purpose classifiers currently\n% available in the toolbox, and are a good default choice if very little is known about the data.\n% For best results, care must be taken to search over the respective regularization parameter(s)\n% appropriately. If more is known about the structure of the data (e.g. that it should be linearly\n% separable, or that that sparsity can be exploited across features), specialized methods may be\n% more appropriate (and give similar results faster or reach better performance by overfitting less\n% strongly).\n%\n% In:\n% Trials : training data, as in ml_train\n%\n% Targets : target variable, as in ml_train\n%\n% Options : optional name-value parameters to control the training details:\n% 'ptype': problem type: 'classification' (default) or 'regression'\n%\n% 'kernel': one of several kernel types:\n% * 'linear': Linear\n% * 'rbf': Gaussian / radial basis functions (default)\n% * 'laplace': Laplacian\n% * 'poly':\t\tPolynomial\n% * 'cauchy':\tCauchy\n%\n% 'gamma': scaling parameter of the kernel (for regularization); if multiple values\n% are given, the optimal gamma will be searched via evidence maximization\n% default: 2.^(-16:0.2:10)\n%\n% 'degree': degree of the polynomial kernel, if used (default: 3)\n%\n% 'bias': whether to add a bias to the data (default: 1)\n%\n% misc options:\n% 'iterations': Number of interations to run for\n% 'time': time limit to run for, e.g. '1.5 hours', '30 minutes', '1 second'\n% 'fixednoise': whether the gaussian noise is to be fixed 0/1\n% 'beta': (Gaussian) noise precision (inverse variance)\n% 'noisestd': (Gaussian) noise standard deviation\n% 'scaling': pre-scaling of the data (see hlp_findscaling for options) (default: 'std') \n% 'diagnosticlevel': verbosity level, 0-4\n%\n% Out:\n% Model : the computed model...\n% classes indicates the class labels which the model predicts\n% additional parameters determine a posterior distribution over the weights\n%\n% Examples:\n% % learn a standard Relevance Vector Machine classifier\n% model = ml_trainrvm(trials,targets)\n%\n% % as before, but this time use a regression approach\n% model = ml_trainrvm(trials,targets,'ptype','regression')\n%\n% % use a Laplacian kernel \n% model = ml_trainrvm(trials,targets,'kernel','laplace')\n%\n% % find the optimal kernel scale using parameter search\n% model = utl_searchmodel({trials,targets},'args',{{'rvm','gamma',seach(2.^(-16:2:4)))\n%\n% \n% See also:\n% ml_predictrvm, SparseBayes\n%\n% References:\n% [1] Vladimir Vapnik. \"The Nature of Statistical Learning Theory.\" \n% Springer-Verlag, 1995\n% [2] Michael E. Tipping and Alex Smola, \"Sparse Bayesian Learning and the Relevance Vector Machine\". \n% Journal of Machine Learning Research 1: 211?244. (2001)\n% [3] Michael E. Tipping and A. C. Faul. \"Fast marginal likelihood maximisation for sparse Bayesian models.\"\n% In C. M. Bishop and B. J. Frey (Eds.), Proceedings of the Ninth International Workshop on Artificial Intelligence and Statistics, Key West, FL, Jan 3-6 (2003)\n% [4] David P. Wipf and Srikantan Nagarajan, \"A New View of Automatic Relevance Determination,\"\n% In J.C. Platt, D. Koller, Y. Singer, and S. Roweis, editors, Advances in Neural Information Processing Systems 20, MIT Press, 2008.\n% [5] David P. Wipf and Srikantan Nagarajan, \"Sparse Estimation Using General Likelihoods and Non-Factorial Priors,\" \n% In Advances in Neural Information Processing Systems 22, 2009.\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2010-04-06\ndp;\n\nopts = arg_define([0 2],varargin, ...\n arg_norep('trials'), ...\n arg_norep('targets'), ...\n arg({'ptype','Type'}, 'classification', {'classification','regression'}, 'Type of problem to solve.','cat','Core Parameters'), ...\n arg({'kernel','Kernel'}, 'rbf', {'linear','rbf','laplace','poly','cauchy'}, 'Kernel type. Linear, or Non-linear kernel types: Radial Basis Functions (general-purpose), Laplace (sparse), Polynomial (rarely preferred), and Cauchy (slightly experimental).','cat','Core Parameters'), ...\n arg({'gammap','KernelScale','gamma'}, 2.^(-16:0.5:10), [0 2^-20 2^10 Inf], 'Scaling of the kernel functions. Should match the size of structures in the data. A reasonable range is 2.^(-16:2:4).','cat','Core Parameters','shape','row'), ...\n arg({'polydegree','PolyDegree','degree'}, 3, uint32([1 100]), 'Degree of the polynomial kernel, if chosen.','cat','Core Parameters'), ...\n arg({'bias','Bias'}, true, [], 'Include a bias term in the model.','cat','Core Parameters'), ...\n arg({'scaling','Scaling'}, 'std', {'none','center','std','minmax','whiten'}, 'Pre-scaling of the data. For the regulariation to work best, the features should either be naturally scaled well, or be artificially scaled.','cat','Core Parameters'), ...\n ...\n arg({'iterations','MaxIterations'}, 100, uint32([1 100000]), 'Number of iterations to run.','cat','Miscellaneous'), ...\n arg({'time','MaxTime'}, '1000 seconds', [], 'Maximum time to run. Can use ''seconds'', ''minutes'', ''hours'' in the string.','cat','Miscellaneous'), ...\n arg({'fixednoise','NoiseFixed'}, false, [], 'Keep the Gaussian noise estimate fixed.','cat','Miscellaneous'), ...\n arg({'noiseinvvar','NoiseInvVariance','beta'}, [], [], 'Inverse variance of the Gaussian noise term.','cat','Miscellaneous','shape','scalar'), ...\n arg({'noisestd','NoiseVariance'}, [], [], 'Variance of the Gaussian noise term.','cat','Miscellaneous','shape','scalar'), ...\n arg({'diagnosticlevel','Verbosity'}, 'none', {'none','minimal','low','medium','high','ultra'}, 'Verbosity level.','cat','Miscellaneous'),...\n arg({'votingScheme','VotingScheme'},'1vR',{'1v1','1vR'},'Voting scheme. If multi-class classification is used, this determine how binary classifiers are arranged to solve the multi-class problem. 1v1 gets slow for large numbers of classes (as all pairs are tested), but can be more accurate than 1vR.'), ... \n arg({'monitor','DisplayInterval'}, uint32(0), [], 'Iterations between diagnostic outputs.','cat','Miscellaneous'));\n\narg_toworkspace(opts);\n\nif is_search(gammap)\n gammap = 0.3; end\n\n% pre-process arguments\nptype = hlp_rewrite(ptype,'classification','c','regression','r'); %#ok<*NODEF>\nlikelihood = hlp_rewrite(ptype,'c','bernoulli','r','gaussian'); \nargs1 = [hlp_struct2varargin(opts,'restrict',{'iterations','time','monitor','fixednoise','freebasis','callback','callbackdata'}),{'diagnosticlevel',hlp_rewrite(opts.diagnosticlevel,'minimal','none')}];\nargs2 = hlp_struct2varargin(opts,'restrict',{'beta','noisestd','relevant','weights','alpha'},'rewrite',{'beta','noiseinvvar'});\n\n% remap targets for classification\nif strcmp(ptype,'c')\n classes = unique(targets);\n if length(classes) > 2\n % multiclass case: use the voter\n model = ml_trainvote(trials,targets,votingScheme,@ml_trainrvm,@ml_predictrvm,varargin{:});\n return;\n elseif length(classes) == 1\n error('BCILAB:only_one_class','Your training data set has no trials for one of your classes; you need at least two classes to train a classifier.\\n\\nThe most likely reasons are that one of your target markers does not occur in the data, or that all your trials of a particular class are concentrated in a single short segment of your data (10 or 20 percent). The latter would be a problem with the experiment design.');\n end\n % remap target labels to 0/1\n targets(targets==classes(1)) = 0;\n targets(targets==classes(2)) = 1;\nelse\n classes = [];\nend\n\n% prescale the data\nsc_info = hlp_findscaling(trials,scaling);\ntrials = hlp_applyscaling(trials,sc_info);\nbasis = trials;\n\nif length(gammap)>1\n if ~strcmp(opts.diagnosticlevel,'none')\n disp('Now optimizing gamma parameter using evidence maximization...'); end\n % optimize gamma parameter using marginal log-likelihood \n bestgam = NaN; % best gamma parameter so far\n likelihoods = nan(length(gammap),1);\n bestlike = -Inf; % best likelihood so far\n for k=1:length(gammap)\n gam = gammap(k);\n if ~strcmp(opts.diagnosticlevel,'none')\n fprintf('gamma=%.3f\\n',gam); end\n % kernelize the data and add bias\n ktrials = utl_kernelize(trials,basis,kernel,gam,polydegree);\n ktrials = quickif(bias,[ones(size(ktrials,1),1) ktrials],ktrials);\n % run the RVM\n [param, hyperparam, diag] = hlp_diskcache('predictivemodels',@SparseBayes,likelihood,ktrials,targets,SB2_UserOptions(args1{:}),SB2_ParameterSettings(args2{:})); %#ok \n if ~isempty(diag.Likelihood)\n likelihoods(k) = diag.Likelihood(end);\n if diag.Likelihood(end) > bestlike\n bestlike = diag.Likelihood(end);\n bestgam = gam;\n end\n end\n end\n gammap = bestgam;\nelse\n likelihoods = [];\nend\n\n% kernelize the data and add bias\nktrials = utl_kernelize(trials,basis,kernel,gammap,polydegree);\nktrials = quickif(bias,[ones(size(ktrials,1),1) ktrials],ktrials);\n% run the RVM\n[param, hyperparam, diag] = hlp_diskcache('predictivemodels',@SparseBayes,likelihood,ktrials,targets,SB2_UserOptions(args1{:}),SB2_ParameterSettings(args2{:}));\n\n% preselect relevant basis vectors\nif ~strcmp(kernel,'linear')\n if bias\n feature_sel = param.Relevant-1;\n if feature_sel(1) == 0\n % bias was relevant, remove it from the basis vector selection (it will be added after kernelization)\n feature_sel = feature_sel(2:end);\n else\n % bias was not relevant, forget about it\n bias = 0;\n end\n else\n feature_sel = param.Relevant;\n end\n basis = basis(feature_sel,:);\nelse\n feature_sel = param.Relevant;\nend\n\nmodel = struct('sc_info',{sc_info},'classes',{classes},'basis',{basis},'param',{param},'hyperparam',{hyperparam},...\n 'diag',{diag},'ptype',{ptype},'feature_sel',{feature_sel},'bias',{bias}, ...\n 'kernel',{kernel},'gamma',{gammap},'gamma_likelihoods',likelihoods,'degree',{polydegree});\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/machine_learning/ml_trainrvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6431082379235981}} {"text": "function [U,sm,X,V,W] = cgsvd(A,L)\n%CGSVD Compact generalized SVD of a matrix pair in regularization problems.\n%\n% sm = cgsvd(A,L)\n% [U,sm,X,V] = cgsvd(A,L) , sm = [sigma,mu]\n% [U,sm,X,V,W] = cgsvd(A,L) , sm = [sigma,mu]\n%\n% Computes the generalized SVD of the matrix pair (A,L). The dimensions of\n% A and L must be such that [A;L] does not have fewer rows than columns.\n%\n% If m >= n >= p then the GSVD has the form:\n% [ A ] = [ U 0 ]*[ diag(sigma) 0 ]*inv(X)\n% [ L ] [ 0 V ] [ 0 eye(n-p) ]\n% [ diag(mu) 0 ]\n% where\n% U is m-by-n , sigma is p-by-1\n% V is p-by-p , mu is p-by-1\n% X is n-by-n .\n%\n% Otherwise the GSVD has a more complicated form (see manual for details).\n%\n% A possible fifth output argument returns W = inv(X).\n \n% Reference: C. F. Van Loan, \"Computing the CS and the generalized \n% singular value decomposition\", Numer. Math. 46 (1985), 479-491. \n \n% Per Christian Hansen, IMM, March 17, 2008. \n \n% Initialization.\n[m,n] = size(A); [p,n1] = size(L);\nif (n1 ~= n)\n error('No. columns in A and L must be the same')\nend\nif (m+p < n)\n error('Dimensions must satisfy m+p >= n')\nend\n\n% Call Matlab's GSVD routine.\n[U,V,W,C,S] = gsvd(full(A),full(L),0);\n\nif (m >= n)\n % The overdetermined or square case.\n sm = [diag(C(1:p,1:p)),diag(S(1:p,1:p))]; \n if (nargout < 2) \n U = sm; \n else \n % Full decomposition. \n X = inv(W'); \n end\nelse\n % The underdetermined case.\n sm = [diag(C(1:m+p-n,n-m+1:p)),diag(S(n-m+1:p,n-m+1:p))]; \n if (nargout < 2) \n U = sm; \n else \n % Full decomposition. \n X = inv(W');\n X = X(:,n-m+1:n); \n end\nend\n\nif (nargout==5), W = W'; end", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/regu/regu/cgsvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6431082345493663}} {"text": "function [img,nrg] = rayCubeAnalytic(L,mat,air,Xsrc,Xmic,Rmax)\n%+========================================================================+\n%| |\n%| OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING |\n%| openRay is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : rayCubeAnalytic.m |\n%| # | VERSION : 0.41 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.04.2018 |\n%| ( === ) | SYNOPSIS : Analytical source image method for a cube |\n%| `---' | |\n%+========================================================================+\n\n% Indices\ni = -30:30; \na = i + 0.5 - 0.5*(-1).^i;\nb = (-1).^i;\n\n% Position relatives des sources images\nx = b*Xsrc(1) + a*L(1) - Xmic(1);\ny = b*Xsrc(2) + a*L(2) - Xmic(2);\nz = b*Xsrc(3) + a*L(3) - Xmic(3);\n[x,y,z] = meshgrid(x,y,z); \nimg = [x(:),y(:),z(:)];\n\n% Dissipation de l'energie par propagation spherique\ndst = sqrt(sum(img.^2,2));\nnrg = 1./(dst.^2);\n\n% Dissipation de l'energie par les parois\nnrg = nrg * ones(1,size(mat,2));\nrfl = (1-mat);\ni0 = abs(0.5*i - 0.25 + 0.25*(-1).^i);\ni1 = abs(0.5*i + 0.25 - 0.25*(-1).^i);\nfor j = 1:size(nrg,2)\n [rx,ry,rz] = meshgrid(...\n (rfl(1,j).^i0).*(rfl(2,j).^i1),...\n (rfl(3,j).^i0).*(rfl(4,j).^i1),...\n (rfl(5,j).^i0).*(rfl(6,j).^i1));\n nrg(:,j) = (rx(:).*ry(:).*rz(:)) .* nrg(:,j);\nend\n\n% Energie dissipee par l'air en fonction de la distance\ndst = sqrt(sum(img.^2,2));\nnrg = nrg .* exp(-dst*air);\n\n% Selections des images selon l'ordre initial\nind = find(dst=n), error('No. of iterations must satisfy k < n'), end\nend\nif (nargout > 1)\n eta = zeros(k,1); rho = eta;\nend\n\n% Prepare for interation.\nx = zeros(n,1); r = b;\nvold = 0; v = A*r;\nwold = 0; w = A*v;\nbeta = norm(w);\nv = v./beta; w = w./beta;\nif reorth, W(:,1) = w; end\n\n% Perform k iterations.\nfor i=1:k\n \n rrho = r'*w;\n x = x + rrho*v;\n r = r - rrho*w;\n Aw = A*w;\n alpha = w'*Aw;\n vnew = w - alpha*v - beta*vold;\n wnew = Aw - alpha*w - beta*wold;\n vold = v; wold = w; v = vnew; w = wnew;\n if reorth\n for j=1:i, w = w - (W(:,j)'*w)*W(:,j); end\n end;\n beta = norm(w);\n v = v./beta;\tw = w./beta;\n if reorth, W(:,i+1) = w; end;\n\n X(:,i) = x;\n if (nargout>1), rho(i) = norm(r); end\n if (nargout>2), eta(i) = norm(x); end\n \nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/regu/regu/mr2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6430948350360158}} {"text": "%% Execute this file to collect training data for model identification\n\n%% Parameters: Model\nn = 5;\noptions = odeset('RelTol',1e-10,'AbsTol',1e-10*ones(1,n));\nSIM_DURATION = 10; % Physical time simulation is integrated before integrator is switched, adjust if necessary, depends on length of time series to be computed\ndt = 1/12; % time step of data\n\nrun_HIV_params\n\n% Steady-state of model corresponding to progressive infection\nxSTEADY1 = zeros(1,5);\nxSTEADY1(2) = ((c2*(lambda1-d*q)-b2*alpha1) - ...\n sqrt((c2*(lambda1-d*q)-b2*alpha1)^2 - 4*alpha1*c2*q*d*b2))/(2*alpha1*c2*q);\nxSTEADY1(1) = lambda1/(d+alpha1*xSTEADY1(2));\nxSTEADY1(4) = 0;\nxSTEADY1(5) = (xSTEADY1(2)*c2*(alpha1*q-a) + b2*alpha1)/(c2*p2*xSTEADY1(2));\nxSTEADY1(3) = h*xSTEADY1(5)/(c2*q*xSTEADY1(2));\n\n% Steady-state of model corresponding to successful immune response\nxSTEADY2 = zeros(1,5);\nxSTEADY2(1) = (lambda1*c1)/(d*c1 + b1*alpha1);\nxSTEADY2(2) = b1/c1;\nxSTEADY2(3) = 0;\nxSTEADY2(4) = (alpha1*xSTEADY2(1)-a)/p1;\nxSTEADY2(5) = 0;\n\nxref = xSTEADY1; % recovered healthy steady state as reference, might be used in system identification\n%% Collect data\nif DATA_ENSEMBLE == 1\n \n Nic = 32; %568\n if exist(fullfile(datapath,['DATA_',SystemModel,'_TRAINING-ENSEMBLE_',InputSignalType,'_N',num2str(Nic),'.mat']))==2\n load(fullfile(datapath,['DATA_',SystemModel,'_TRAINING-ENSEMBLE_',InputSignalType,'_N',num2str(Nic),'.mat']))\n else\n tspan=[0:dt:20];\n Ntrain = (length(tspan)-1)/2+1;\n Nt = length(tspan);\n \n if strcmp(ModelName,'SINDYc')\n [x10, x20, x30, x40, x50] = ndgrid([1000],[0,10], [0,10], [0.1,1,10], [0.1,1,10]);\n elseif strcmp(ModelName,'NARX') || strcmp(ModelName,'DMDc')\n [x10, x20, x30, x40, x50] = ndgrid([10,10],[0.1,0.1], [0.1,0.1],[0.1,0.1], [0.1,0.1]);\n \n end\n [N1,N2,N3,N4,N5] = size(x10);\n x0_ensemble = [reshape(x10,[N1*N2*N3*N4*N5,1]), reshape(x20,[N1*N2*N3*N4*N5,1]), reshape(x30,[N1*N2*N3*N4*N5,1]), reshape(x40,[N1*N2*N3*N4*N5,1]), reshape(x50,[N1*N2*N3*N4*N5,1])];\n Nic = size(x0_ensemble,1)\n \n xensemble = zeros(Nt,n,Nic); % Init ensemble data \n switch InputSignalType\n \n case 'sine2'\n \n rng(1,'twister')\n Nrand = [1*rand(Nic,5)];\n A = 2;\n forcing = @(x,t) [(0.4*(sin(2*pi*0.2*t).*sin(2*pi*0.05*t)))+0.3];\n for iIC = 1:Nic\n tic\n try\n forcing = @(x,t) [(Nrand(iIC,1)*A* (sin(Nrand(iIC,1)*0.7*t).*sin(Nrand(iIC,1)*.1*t).*sin(Nrand(iIC,1)*.2*t).*sin(Nrand(iIC,1)*.05*t)) ).^2]; %[(A*(sin(0.01*t)+sin(.1*t))).^2];\n [t,x]=ode45(@(t,x) HIVsys_KWON(t,x,forcing(x,t)),tspan,x0_ensemble(iIC,:),options);\n xensemble(:,:,iIC) = x;\n for i = 1:length(tspan)\n u(i,:,iIC) = forcing(0,tspan(i));\n end\n catch\n disp(['ERROR: Simulation failed for i=',num2str(iIC)])\n xensemble(:,:,iIC) = nan(Nt,n);\n u(:,:,iIC) = zeros(Nt,length(A));\n end\n tend = toc;\n disp(['Time for ',num2str(iIC), ' of ',num2str(Nic),': ', num2str(tend)])\n end\n figure,plot(t,xensemble(:,:,iIC))\n figure,plot(t,squeeze(xensemble(:,5,:)))\n \n case 'prbs'\n A = 1;\n taulim = [0.2 8];\n states = [0,0:0.25:1,0,0,0]\n Nswitch = 200;\n \n rng(1,'twister');\n seed = randi(Nic,Nic,1); % vary actuation in each trajectory\n forcing = @(x,t,seedval) [A(1)*prbs(taulim, Nswitch, states, t,0,seedval)];\n u = zeros(length(tspan),length(A),Nic);\n \n for iIC = 1:Nic\n tic\n try\n % IF simulation takes longer than SIM_DURATION,\n % stop simulation and switch solver\n [t,x,isterminal] = integrateODE(tspan, x0_ensemble(iIC,:), 'ode45', SIM_DURATION,@(x,t) forcing(x,t,seed(iIC)));\n if isterminal == 1 % try different solver\n [t,x,isterminal] = integrateODE(tspan, x0_ensemble(iIC,:), 'ode15s', SIM_DURATION,@(x,t) forcing(x,t,seed(iIC)));\n end\n xensemble(:,:,iIC) = x;\n for i = 1:length(tspan)\n u(i,:,iIC) = forcing(0,tspan(i),seed(iIC));\n end\n catch\n disp(['ERROR: Simulation failed for i=',num2str(iIC)])\n xensemble(:,:,iIC) = nan(Nt,n);\n u(:,:,iIC) = zeros(Nt,length(A));\n end\n tend = toc;\n disp(['Time for ',num2str(iIC), ' of ',num2str(Nic),': ', num2str(tend)])\n end\n \n end\n \n \n %% Clean up data\n % from unstable simulations or which failed\n IXnaninf = zeros(Nic,1);\n for i = 1:Nic\n IXnan = isnan(squeeze((xensemble(:,:,i))));\n IXinf = isinf(squeeze(abs(xensemble(:,:,i))));\n if any(IXnan(:)==1) || any(IXinf(:)==1)\n IXnaninf(i) = 1;\n end\n end\n xensemble(:,:,logical(IXnaninf)) = [];\n u(:,:,logical(IXnaninf)) = [];\n Nic = size(xensemble,3);\n \n %% Split into training and validation data set\n Ntrain = ceil(length(tspan)/2);\n xv = xensemble(Ntrain+1:end,:,:);\n x = xensemble(1:Ntrain,:,:);\n \n uv = u(Ntrain+1:end,:,:);\n u = u(1:Ntrain,:,:);\n \n tv = t(Ntrain+1:end);\n t = t(1:Ntrain);\n \n tspanv = tspan(Ntrain+1:end);\n tspan = tspan(1:Ntrain);\n \n \n %% Show data\n \n figure;\n subplot(6,1,1)\n plot(tspan,squeeze(x(:,1,:)),'LineWidth',1.5)\n ylabel('x1')\n set(gca,'LineWidth',1, 'FontSize',14)\n \n subplot(6,1,2)\n plot(tspan,squeeze(x(:,2,:)),'LineWidth',1.5)\n ylabel('x2')\n set(gca,'LineWidth',1, 'FontSize',14)\n \n subplot(6,1,3)\n plot(tspan,squeeze(x(:,3,:)),'LineWidth',1.5)\n ylabel('x3')\n set(gca,'LineWidth',1, 'FontSize',14)\n \n subplot(6,1,4)\n plot(tspan,squeeze(x(:,4,:)),'LineWidth',1.5)\n ylabel('x4')\n set(gca,'LineWidth',1, 'FontSize',14)\n \n subplot(6,1,5)\n plot(tspan,squeeze(x(:,5,:)),'LineWidth',1.5)\n ylabel('x5')\n set(gca,'LineWidth',1, 'FontSize',14)\n \n subplot(6,1,6)\n plot(tspan,squeeze(u(:,1,:)),'LineWidth',1.5)\n ylabel('u')\n set(gca,'LineWidth',1, 'FontSize',14)\n %%\n T = length(tspan);\n N = length(tspan);\n save(fullfile(datapath,['DATA_',SystemModel,'_TRAINING-ENSEMBLE_',InputSignalType,'_N',num2str(Nic),'.mat']))\n end\nelseif DATA_ENSEMBLE == 0\n rng(3,'twister')\n \n % Initial Condition\n x0 = [10, 0.1, 0.1, 1, 0.1];\n tspan=[0:dt:400];\n Ntrain = (length(tspan)-1)/2+1;\n \n \n \n switch InputSignalType\n case 'unforced'\n forcing = @(x,t) [0];\n [t,x]=ode45(@(t,x) HIVsys_ZURAKOWSKI(t,x,forcing(x,t)),tspan,x0,options);\n u = zeros(length(tspan),1);\n for i = 1:length(tspan)\n u(i,:) = forcing(0,tspan(i));\n end\n case 'sine2'\n A = 1.5;\n Nic = 1; iIC = 1;\n Nrand = [rand(Nic,1),rand(Nic,1),randn(Nic,1),rand(Nic,1),randn(Nic,1),rand(Nic,1),randn(Nic,1),rand(Nic,1),randn(Nic,1)];\n forcing = @(x,t) [mod((A* (sin(Nrand(iIC,2)*0.7*(t-Nrand(iIC,3))).* ...\n sin(Nrand(iIC,4)*.1*(t-Nrand(iIC,5))).*sin(Nrand(iIC,6)*.2*(t-Nrand(iIC,7))).*sin(Nrand(iIC,8)*.05*(t-Nrand(iIC,9)))) ).^2,1)];\n [t,x]=ode45(@(t,x) HIVsys_ZURAKOWSKI(t,x,forcing(x,t)),tspan,x0,options);\n u = forcing(0,tspan)';\n \n case 'prbs'\n A = 1; % PAPER\n taulim = [0.2 10];\n states = [0:0.25:1,0,0,0,0];\n Nswitch = 200;\n forcing = @(x,t) [A(1)*prbs(taulim, Nswitch, states, t,0)];\n \n [t,x]=ode45(@(t,x) HIVsys_ZURAKOWSKI(t,x,forcing(x,t)),tspan,x0,options);\n \n u = zeros(length(tspan),1);\n for i = 1:length(tspan)\n u(i,:) = forcing(0,tspan(i));\n end\n figure,plot(tspan,u)\n size(u)\n \n end\n \n \n %% Split into training and validation data set\n Ntrain = ceil(length(tspan)/2);\n xv = x(Ntrain+1:end,:);\n x = x(1:Ntrain,:);\n \n uv = u(Ntrain+1:end,:);\n u = u(1:Ntrain,:);\n \n tv = t(Ntrain+1:end);\n t = t(1:Ntrain);\n \n tspanv = tspan(Ntrain+1:end);\n tspan = tspan(1:Ntrain);\n \n %% Show results\n betta_eff = alpha1*(1-eta*u(1));\n betta_eff 0);\n\tmax_percent_diff(rmex .* mmask, recon .* mmask)\n\tim(2, rmat .* mmask, 'mat'), cbar\n\tim(3, rmex .* mmask, 'mex'), cbar\nreturn\nend\n\nif 0 % examine \"aliasing\"\n\tclim = [9.5 10.5];\n%\tclim = [0.8 1.2];\n%\tclim = [-0.2 0.2];\n\tim clf, im(recon, clim), cbar\nreturn\nend\n\nif im\n\tim(2, recon, 'FBP matlab'), cbar\n\tim(5, recon - xtrue, 'error'), cbar\n\tiy = ig.ny/2; ix = 1:ig.nx;\n\tsubplot(133)\n\tplot(ix, xtrue(ix,iy), '-', ix, recon(ix,iy), '--')\n\taxis([1 ig.nx -0.5 10.5]), legend('true', 'recon', 4)\nend\n\nif has_aspire % check consistency with aspire\n\tdir = test_dir;\n\tf.sino = [dir 'sino.fld'];\n\tf.image = [dir 'image.fld'];\n\tf.dsc = [dir 't.dsc'];\n\tfld_write(f.sino, sino)\n\n\tchar_array_write(f.dsc, G.arg.args)\n\tf.win = 'boxcar,1,0,1';\n\tcom = sprintf('echo y | i fbp dsc %s %s %s %s', ...\n\t\tf.image, f.sino, f.dsc, f.win)\n%\teval(['!' com])\n\tdisp(os_run(com))\n\n\tif 0 % compare filters\n\t\ttmp = fld_read('fft_filt.fld');\n\t\tsum(tmp) / sum(test)\n%\t\tim clf, plot([tmp test])\n\t\tmax_percent_diff(test, tmp)\n\treturn\n\tend\n\n\tif 0 % compare filtered projections\n\t\t% seem to match except for slight shift?? \n\t\ttmp = fld_read('proj_filt.fld');\n\t\tim clf, plot([tmp(:,1) test(:,1)])\n\t\tplot(tmp(:,1)-test(:,1))\n\t\tmax_percent_diff(test, tmp)\n\t\tsum(tmp(:)) / sum(test(:))\n\t\tminmax(test)\n\t\tminmax(tmp)\n\t\tminmax(test-tmp)\n\treturn\n\tend\n\n\tim_asp = fld_read(f.image);\n\tim(233, im_asp, 'aspire'), cbar\n\tgood = recon ~= 0;\n\tdiff = im_asp - recon;\n\tdiff = diff .* good;\n\tim(236, diff, 'aspire-matlab'), cbar\n\tim(234, (im_asp ~= 0) - (recon ~= 0), 'aspire-matlab support'), cbar\n\tmax_percent_diff(recon.*good, im_asp.*good)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/fbp_fan_arc_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6430579802636298}} {"text": "%trotz SE(3) rotation about Z axis\n%\n% T = trotz(THETA) is a homogeneous transformation (4x4) representing a rotation \n% of THETA radians about the z-axis.\n%\n% T = trotz(THETA, 'deg') as above but THETA is in degrees.\n%\n% Notes::\n% - Translational component is zero.\n%\n% See also rotz, trotx, troty, trot2, SE3.Rz.\n\n%## 3d homogeneous rotation\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction T = trotz(t, varargin)\n\tT = [rotz(t, varargin{:}) [0 0 0]'; 0 0 0 1];\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/trotz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6430068633740387}} {"text": "function [ HessGrad ] = lbfgs_two_loop_recursion( grad, s_array, y_array )\n% Two loop recursion algorithm for L-BFGS.\n%\n% Reference:\n% Jorge Nocedal and Stephen Wright,\n% \"Numerical optimization,\"\n% Springer Science & Business Media, 2006.\n%\n% Algorithm 7.4 in Section 7.2.\n% \n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created H.Kasai on Oct. 17, 2016\n\n\n if(size(s_array,2)==0)\n HessGrad = -grad;\n else\n q = grad;\n\n for i = size(s_array,2):-1:1\n rk(i) = 1/(y_array(:,i)'*s_array(:,i));\n a(i) = rk(i)*s_array(:,i)'*q;\n q = q - a(i)*y_array(:,i);\n end\n\n Hk0 = (s_array(:,end)'*y_array(:,end))/(y_array(:,end)'*y_array(:,end));\n R = Hk0.*q;\n\n for jj = 1:size(s_array,2)\n beta = rk(jj)*y_array(:,jj)'*R;\n R = R + s_array(:,jj)*(a(jj) - beta);\n end\n\n HessGrad = -R; \n end\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/gd_solver/lbfgs_two_loop_recursion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224068675884, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6430068530431418}} {"text": "function H=comp_warpedfreqresponse(wintype,fc,bw,fs,L,freqtoscale,scaletofreq,varargin)\n%COMP_WARPEDFREQRESPONSE Transfer function of warped filter\n% Usage: H=comp_warpedfreqresponse(wintype,fc,bw,fs,L,freqtoscale);\n% H=comp_warpedfreqresponse(wintype,fc,bw,fs,L,freqtoscale,normtype);\n%\n% Input parameters:\n% wintype : Type of window (from firwin)\n% fc : Centre frequency, in scale units.\n% bw : Bandwith, in scale units.\n% fs : Sampling frequency in Hz.\n% L : Transform length (in samples).\n% freqtoscale : Function to convert Hz into scale units.\n% scaletofreq : Function to convert scale units into Hz.\n% normtype : Normalization flag to pass to |setnorm|.\n\n\ndefinput.import={'setnorm'};\ndefinput.flags.symmetry = {'nonsymmetric','symmetric'};\n[flags,kv]=ltfatarghelper({},definput,varargin);\n\nfcwasnegative = fc < 0;\n\nif fcwasnegative && flags.do_symmetric\n fc = -fc;\nend\n\nfcscale = freqtoscale(fc);\n\nif ~flags.do_symmetric\n % Compute the values in Aud of the channel frequencies of an FFT of\n % length L.\n bins_lo = freqtoscale(modcent(fs*(0:L-1)/L,fs)).';\nelse\n bins_lo = freqtoscale(fs*(0:L-1)/L).';\nend\n\n% This one is necessary to represent the highest frequency filters, which\n% overlap into the negative frequencies.\nnyquest2 = 2*freqtoscale(fs/2);\nbins_hi = nyquest2+bins_lo;\n\n% firwin makes a window of width 1 centered around 0 on the scale, so we rescale the\n% bins in order to pass the correct width to firwin and subtract fc\nbins_lo=(bins_lo-fcscale)/bw;\nbins_hi=(bins_hi-fcscale)/bw;\n\npos_lo=comp_warpedfoff(fc,bw,fs,L,freqtoscale,scaletofreq,flags.do_symmetric);\n% The \"floor\" below often cuts away a non-zero sample, but it makes\n% the support stay below the limit needed for the painless case. Same\n% deal 4 lines below.\npos_hi=floor(scaletofreq(fcscale+.5*bw)/fs*L);\n\nif pos_hi>L/2\n % Filter is high pass and spilling into the negative frequencies\n pos_hi=floor(scaletofreq(fcscale+.5*bw-nyquest2)/fs*L);\nend;\n\nwin_lo=firwin(wintype,bins_lo);\nwin_hi=firwin(wintype,bins_hi);\n\n\nH=win_lo+win_hi;\nH(isnan(H)) = 0;\n \nH=setnorm(H,flags.norm);\n\nH=circshift(H,-pos_lo);\nupidx=modcent(pos_hi-pos_lo,L);\n\n% ------ Testing ---------------\nif 0\n bb=circshift(bins_lo,-pos_lo);\n if bb(1)<-0.5\n % Adjust bin_lo\n error('Could do better here.');\n end;\n if (bb(upidx+1)<0.5) && (bb(upidx+1)>0)\n disp('Chopped non-zero sample.');\n bb(upidx+1)\n end;\nend;\n\nH=H(1:upidx);\n\nif fcwasnegative && flags.do_symmetric\n H = H(end:-1:1);\nend\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_warpedfreqresponse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6430068507041696}} {"text": "function [y,dy] = div_gmc(dx,x,Mu_x,Mu_dx,Sigma_dxdx,Sigma_xx,Sigma_dxx,Sigma_xdx)\n%GMC_DIV Derivative of the conditional Gaussian Mixture model P(dx|x)\n%\n% sqrt((2*pi)^nbVar * (abs(det(Sigma))+realmin))\n% check the derivative of log exp(- 0.5 * (dx - \\Mu_{dx|x})'(\\Sigma_{dx|x}^-1) (dx - \\Mu_{dx|x}) )\n%\n% input -----------------------------------------------------------------\n%\n% o dx : (P x 1)\n%\n% o x : (Q x 1)\n% \n% o Mu_dx : (P x 1), $\\mu_{\\dot{x}}$\n%\n% o Mu_x : (Q x 1), $\\mu_x$\n%\n% P + Q = D\n%\n% o Sigma_dxdx : (P x P), covariance between dx and dx\n% \n% o Sigma_{dx,x} : (P x Q), covarariance between dx and x\n%\n% o Sigma_{x,x} : (Q x Q), covariance between x and x\n%\n% o Sigma_{x,dx} : (Q x P), covariance between x and dx\n%\n%\n\n\nx = x(:);\ndx = dx(:);\nP = size(Mu_dx,1);\n\n\n% (P x 1) = (P x 1) + (P x Q) (Q x Q) * (Q x 1) - (Q x 1) \n% (P x 1) = (P x 1)\ninvSig_xx = inv(Sigma_xx);\n% (P x Q) = (P x Q) * (Q x Q) \nA = Sigma_dxx * invSig_xx;\n\n% (P x 1)\nMu_dx_x = Mu_dx + A * (x - Mu_x);\n\n% (P x P)\nSigma_dx_x = Sigma_dxdx - A * Sigma_xdx;\n\n\n% (P x N) \ninvSigma_dx_x = inv(Sigma_dx_x);\n%norm_fac = 0.9;%1/( (2*pi^(P/2)) * sqrt(det(Sigma_dx_x)));\n%norm_fac = -P/2 * log(pi) - 0.5*log(det(Sigma_dx_x));\ndenom = sqrt((2*pi)^P * (abs(det(Sigma_dx_x))+realmin));\n%norm_fac = log(1/denom);\nnorm_fac = -log(denom);\n%norm_fac = -log(sqrt((2*pi)^P) - log(abs(det(Sigma_dx_x))+realmin));\n\n\n%y = norm_fac .* exp(-0.5 .* (dx - Mu_dx_x)' * (invSigma_dx_x * (dx - Mu_dx_x)));\ny = norm_fac + (-0.5 .* (dx - Mu_dx_x)' * (invSigma_dx_x * (dx - Mu_dx_x)));\n\n\n% \n% (dx - Mu_dx_x)' * (invSigma_dx_x * (dx - Mu_dx_x))\n% \n% (dx' * invSigma_dx_x - Mu_dx_x' * invSigma_dx_x) * (dx - Mu_dx_x)\n% dx' * invSigma_dx_x * dx - Mu_dx_x' * invSigma_dx_x * dx - dx' * invSigma_dx_x * Mu_dx_x + Mu_dx_x' * invSigma_dx_x * Mu_dx_x\n% \n% dx' * invSigma_dx_x * dx - 2 * Mu_dx_x' * invSigma_dx_x * dx + Mu_dx_x' * invSigma_dx_x * Mu_dx_x\n% \n% dx' * invSigma_dx_x * dx - 2 * (Mu_dx + A * (x - Mu_x))' * invSigma_dx_x * dx + (Mu_dx + A * (x - Mu_x))' * invSigma_dx_x * (Mu_dx + A * (x - Mu_x))\n% 'here'\n% tmp1 = (x - Mu_x)' * A' * invSigma_dx_x;\n% \n% part1 = dx' * invSigma_dx_x * dx - 2 *Mu_dx' *invSigma_dx_x * dx - 2 * tmp1 * dx;\n% \n% part1 + (Mu_dx' * invSigma_dx_x + tmp1) * (Mu_dx + A * (x - Mu_x))\n% 'max expansion'\n% part1 + Mu_dx' * invSigma_dx_x * Mu_dx + tmp1 * Mu_dx + Mu_dx' * invSigma_dx_x * (A * (x - Mu_x)) + tmp1 * (A * (x - Mu_x))\n% \n% part1 + Mu_dx' * invSigma_dx_x * Mu_dx + tmp1 * Mu_dx + tmp1 * Mu_dx + tmp1 * (A * (x - Mu_x))\n% \n% \n% dx' * invSigma_dx_x * dx - 2 *Mu_dx' *invSigma_dx_x * dx + Mu_dx' * invSigma_dx_x * Mu_dx - 2 * tmp1 * dx + tmp1 * Mu_dx + tmp1 * Mu_dx + tmp1 * (A * (x - Mu_x))\n% \n% dx' * invSigma_dx_x * dx - 2 *Mu_dx' *invSigma_dx_x * dx + Mu_dx' * invSigma_dx_x * Mu_dx + tmp1 * (- 2 * dx + Mu_dx + Mu_dx + (A * (x - Mu_x)));\n\n%fac = (x - Mu_x)' * A' * invSigma_dx_x;\n% y2 = dx' * invSigma_dx_x * dx -2 *Mu_dx' *invSigma_dx_x * dx + Mu_dx' * invSigma_dx_x * Mu_dx + fac * (-2*dx + 2*Mu_dx + A * (x - Mu_x)); \n% \n% y2 = exp(-0.5 .* y2);\n\n\n\nif nargout > 1\n % \n % - (1 x P) (1 x P) (1 x P)\n% dy = y .* ((dx' * invSigma_dx_x)' - (Mu_dx' * invSigma_dx_x)' - fac' );\n % dy = ((dx' * invSigma_dx_x)' - (Mu_dx' * invSigma_dx_x)' - ( (x - Mu_x)' * A' * invSigma_dx_x)' );\n dy = invSigma_dx_x' * ( dx - Mu_dx - ((x - Mu_x)' * A')' );\n\n\nend\n\n\n\n\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/gmmbox/GMMfunctions/Gaussian_derivative/GMC_derivative/div_gmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.6429906935286166}} {"text": "% Data File LAN\n% Free linear vibrations of a system\n% with one degree of freedom\ns = 1; % degree of freedom\nL = '1/2*(a*qt1^2 - c*q1^2)'; % Lagrangian\nQN{1} = '-b*qt1'; % generalized non potential force\nqj0 = 'q0'; % initial coordinate\nqtj0 = 'qt0'; % initial velocity\nTend = 20; % upper bound of integration\neps = 1e-10; % desirable accuracy\nnp = 3; % number of parameters\nP{1} = 'a'; % generalized coefficient of inertia\nP{2} = 'b'; % generalized coefficient of resistance\nP{3} = 'c'; % generalized coefficient of stiffness\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/DATA Files/LAN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6429906922168972}} {"text": "function out = MD_hrv_classic(y)\n% MD_hrv_classic Classic heart rate variability (HRV) statistics.\n%\n% Typically assumes an NN/RR time series in units of seconds.\n%\n%---INPUTS:\n% y, the input time series.\n%\n% Includes:\n% (i) pNNx\n% cf. \"The pNNx files: re-examining a widely used heart rate variability\n% measure\", J.E. Mietus et al., Heart 88(4) 378 (2002)\n%\n% (ii) Power spectral density ratios in different frequency ranges\n% cf. \"Heart rate variability: Standards of measurement, physiological\n% interpretation, and clinical use\",\n% M. Malik et al., Eur. Heart J. 17(3) 354 (1996)\n%\n% (iii) Triangular histogram index, and\n%\n% (iv) Poincare plot measures\n% cf. \"Do existing measures of Poincare plot geometry reflect nonlinear\n% features of heart rate variability?\"\n% M. Brennan, et al., IEEE T. Bio.-Med. Eng. 48(11) 1342 (2001)\n%\n% Code is heavily derived from that provided by Max A. Little:\n% http://www.maxlittle.net/\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\n% Standard defaults\ndiffy = diff(y);\nN = length(y); % time-series length\n\n% ------------------------------------------------------------------------------\n% Calculate pNNx percentage\n% ------------------------------------------------------------------------------\n% pNNx: recommendation as per Mietus et. al. 2002, \"The pNNx files: ...\", Heart\n% strange to do this for a z-scored time series...\n\nDy = abs(diffy);\n\n% Anonymous function to do the PNNx calcualtion:\n% proportion of difference magnitudes greater than X*sigma\nPNNxfn = @(x) mean(Dy > x/1000);\n\nout.pnn5 = PNNxfn(5); % 0.005*sigma\nout.pnn10 = PNNxfn(10); % 0.01*sigma\nout.pnn20 = PNNxfn(20); % 0.02*sigma\nout.pnn30 = PNNxfn(30); % 0.03*sigma\nout.pnn40 = PNNxfn(40); % 0.04*sigma\n\n% ------------------------------------------------------------------------------\n% Calculate PSD\n% ------------------------------------------------------------------------------\n% [Pxx, F] = psd(series,1024,1,hanning(1024),512);\n[Pxx, F] = periodogram(y,hann(N)); % periodogram with hanning window\n\n% ------------------------------------------------------------------------------\n% Calculate spectral measures such as subband spectral power percentage, LF/HF ratio etc.\n% ------------------------------------------------------------------------------\n% LF/HF: as per Malik et. al. 1996, \"Heart Rate Variability\"\nLF_lo = 0.04; % /pi -- fraction of total power (max F is pi)\nLF_hi = 0.15;\nHF_lo = 0.15;\nHF_hi = 0.4;\n\nfbinsize = F(2) - F(1);\nindl = ((F >= LF_lo) & (F <= LF_hi));\nindh = ((F >= HF_lo) & (F <= HF_hi));\nindv = (F <= LF_lo);\nlfp = fbinsize * sum(Pxx(indl));\nhfp = fbinsize * sum(Pxx(indh));\nvlfp = fbinsize * sum(Pxx(indv));\nout.lfhf = lfp / hfp;\ntotal = fbinsize * sum(Pxx);\nout.vlf = vlfp/total * 100;\nout.lf = lfp/total * 100;\nout.hf = hfp/total * 100;\n\n% ------------------------------------------------------------------------------\n% Triangular histogram index\n% ------------------------------------------------------------------------------\nnumBins = 10;\nout.tri = length(y)/max(histcounts(y,numBins));\n\n% ------------------------------------------------------------------------------\n% Poincare plot measures:\n% ------------------------------------------------------------------------------\n% cf. \"Do Existing Measures ... \", Brennan et. al. (2001), IEEE Trans Biomed Eng 48(11)\nrmssd = std(diffy); % std of differenced series\nsigma = std(y); % should be 1 for zscored time series\nout.SD1 = 1/sqrt(2) * rmssd * 1000;\nout.SD2 = sqrt(2 * sigma^2 - (1/2) * rmssd^2) * 1000;\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/MD_hrv_classic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.642990690200788}} {"text": "%% Analyzing Neural Time Series Data\n% Matlab code for Chapter 26\n% Mike X Cohen\n% \n% This code accompanies the book, titled \"Analyzing Neural Time Series Data\" \n% (MIT Press). Using the code without following the book may lead to confusion, \n% incorrect data analyses, and misinterpretations of results. \n% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code. \n\n%% Figure 26.1\n\n% load sample EEG dataset\nload sampleEEGdata\n\n% names of the channels you want to synchronize\nchannel1 = 'p1';\nchannel2 = 'pz';\n\n% create complex Morlet wavelet\ncenter_freq = 5; % in Hz\ntime = -1:1/EEG.srate:1; % time for wavelet\nwavelet = exp(2*1i*pi*center_freq.*time) .* exp(-time.^2./(2*(4/(2*pi*center_freq))^2))/center_freq;\nhalf_of_wavelet_size = (length(time)-1)/2;\n\n% FFT parameters\nn_wavelet = length(time);\nn_data = EEG.pnts;\nn_convolution = n_wavelet+n_data-1;\n\n% FFT of wavelet\nfft_wavelet = fft(wavelet,n_convolution);\n\n% initialize output time-frequency data\nphase_data = zeros(2,EEG.pnts);\nreal_data = zeros(2,EEG.pnts);\n\n% find channel indices\nchanidx = zeros(1,2); % always initialize!\nchanidx(1) = find(strcmpi(channel1,{EEG.chanlocs.labels}));\nchanidx(2) = find(strcmpi(channel2,{EEG.chanlocs.labels}));\n\n\n% run convolution and extract filtered signal (real part) and phase\nfor chani=1:2\n fft_data = fft(squeeze(EEG.data(chanidx(chani),:,1)),n_convolution);\n convolution_result_fft = ifft(fft_wavelet.*fft_data,n_convolution) * sqrt(4/(2*pi*center_freq));\n convolution_result_fft = convolution_result_fft(half_of_wavelet_size+1:end-half_of_wavelet_size);\n \n % collect real and phase data\n phase_data(chani,:) = angle(convolution_result_fft);\n real_data(chani,:) = real(convolution_result_fft);\nend\n\n\n% open and name figure\nfigure, set(gcf,'Name','Movie magic minimizes the mystery.','Number','off');\n\n% draw the filtered signals\nsubplot(321)\nfilterplotH1 = plot(EEG.times(1),real_data(1,1),'b');\nhold on\nfilterplotH2 = plot(EEG.times(1),real_data(2,1),'m');\nset(gca,'xlim',[EEG.times(1) EEG.times(end)],'ylim',[min(real_data(:)) max(real_data(:))])\nxlabel('Time (ms)')\nylabel('Voltage (\\muV)')\ntitle([ 'Filtered signal at ' num2str(center_freq) ' Hz' ])\n\n% draw the phase angle time series\nsubplot(322)\nphaseanglesH1 = plot(EEG.times(1),phase_data(1,1),'b');\nhold on\nphaseanglesH2 = plot(EEG.times(1),phase_data(2,1),'m');\nset(gca,'xlim',[EEG.times(1) EEG.times(end)],'ylim',[-pi pi]*1.1,'ytick',-pi:pi/2:pi)\nxlabel('Time (ms)')\nylabel('Phase angle (radian)')\ntitle('Phase angle time series')\n\n% draw phase angle differences in cartesian space\nsubplot(323)\nfilterplotDiffH1 = plot(EEG.times(1),real_data(1,1)-real_data(2,1),'b');\nset(gca,'xlim',[EEG.times(1) EEG.times(end)],'ylim',[-10 10])\nxlabel('Time (ms)')\nylabel('Voltage (\\muV)')\ntitle([ 'Filtered signal at ' num2str(center_freq) ' Hz' ])\n\n% draw the phase angle time series\nsubplot(324)\nphaseanglesDiffH1 = plot(EEG.times(1),phase_data(1,1)-phase_data(2,1),'b');\nset(gca,'xlim',[EEG.times(1) EEG.times(end)],'ylim',[-pi pi]*2.2,'ytick',-2*pi:pi/2:pi*2)\nxlabel('Time (ms)')\nylabel('Phase angle (radian)')\ntitle('Phase angle time series')\n\n% draw phase angles in polar space\nsubplot(325)\npolar2chanH1 = polar([phase_data(1,1) phase_data(1,1)]',repmat([0 1],1,1)','b');\nhold on\npolar2chanH2 = polar([phase_data(1,1) phase_data(2,1)]',repmat([0 1],1,1)','m');\ntitle('Phase angles from two channels')\n \n% draw phase angle differences in polar space\nsubplot(326)\npolarAngleDiffH = polar([zeros(1,1) phase_data(2,1)-phase_data(1,1)]',repmat([0 1],1,1)','k');\ntitle('Phase angle differences from two channels')\n \n% now update plots at each timestep\n% Note: in/decrease skipping by 10 to speed up/down the movie\nfor ti=1:10:EEG.pnts\n \n % update filtered signals\n set(filterplotH1,'XData',EEG.times(1:ti),'YData',real_data(1,1:ti))\n set(filterplotH2,'XData',EEG.times(1:ti),'YData',real_data(2,1:ti))\n \n % update cartesian plot of phase angles\n set(phaseanglesH1,'XData',EEG.times(1:ti),'YData',phase_data(1,1:ti))\n set(phaseanglesH2,'XData',EEG.times(1:ti),'YData',phase_data(2,1:ti))\n \n % update cartesian plot of phase angles differences\n set(phaseanglesDiffH1,'XData',EEG.times(1:ti),'YData',phase_data(1,1:ti)-phase_data(2,1:ti))\n set(filterplotDiffH1,'XData',EEG.times(1:ti),'YData',real_data(1,1:ti)-real_data(2,1:ti))\n \n subplot(325)\n cla\n polar(repmat(phase_data(1,1:ti),1,2)',repmat([0 1],1,ti)','b');\n hold on\n polar(repmat(phase_data(2,1:ti),1,2)',repmat([0 1],1,ti)','m');\n \n subplot(326)\n cla\n polar(repmat(phase_data(2,1:ti)-phase_data(1,1:ti),1,2)',repmat([0 1],1,ti)','k');\n \n drawnow\nend\n\n%% Figure 26.2\n\nfigure\nsubplot(221)\npolar(repmat(phase_data(2,:)-phase_data(1,:),1,2)',repmat([0 1],1,EEG.pnts)','k');\ntitle([ 'Phase synchronization: ' num2str(abs(mean(exp(1i*(diff(phase_data,1)))))) ])\n\nnew_phase_data = phase_data;\nfor i=2:4\n subplot(2,2,i)\n \n % add random phase offset\n new_phase_data(1,:) = new_phase_data(1,:)+rand*pi;\n \n % plot again\n polar(repmat(new_phase_data(2,:)-new_phase_data(1,:)+pi/2,1,2)',repmat([0 1],1,EEG.pnts)','k');\n title([ 'Phase synchronization: ' num2str(abs(mean(exp(1i*(diff(new_phase_data,1)))))) ])\nend\n\n%% Figure 26.3\n\n% note: see commented line \"time_window_idx...\" below for panels C and D\n\nchannel1 = 'fz';\nchannel2 = 'o1';\n\nfreqs2use = logspace(log10(4),log10(30),15); % 4-30 Hz in 15 steps\ntimes2save = -400:20:800;\ntimewindow = linspace(1.5,3,length(freqs2use)); % number of cycles on either end of the center point (1.5 means a total of 3 cycles))\nbaselinetm = [-400 -200];\n\n% wavelet and FFT parameters\ntime = -1:1/EEG.srate:1;\nhalf_wavelet = (length(time)-1)/2;\nnum_cycles = logspace(log10(4),log10(8),length(freqs2use));\nn_wavelet = length(time);\nn_data = EEG.pnts*EEG.trials;\nn_convolution = n_wavelet+n_data-1;\n\n% time in indices\ntimes2saveidx = dsearchn(EEG.times',times2save');\nbaselineidx = dsearchn(times2save',baselinetm');\n\nchanidx = zeros(1,2); % always initialize!\nchanidx(1) = find(strcmpi(channel1,{EEG.chanlocs.labels}));\nchanidx(2) = find(strcmpi(channel2,{EEG.chanlocs.labels}));\n\n% initialize\nispc = zeros(length(freqs2use),length(times2save));\nps = zeros(length(freqs2use),length(times2save));\n\n% data FFTs\ndata_fft1 = fft(reshape(EEG.data(chanidx(1),:,:),1,n_data),n_convolution);\ndata_fft2 = fft(reshape(EEG.data(chanidx(2),:,:),1,n_data),n_convolution);\n\n\nfor fi=1:length(freqs2use)\n \n % create wavelet and take FFT\n s = num_cycles(fi)/(2*pi*freqs2use(fi));\n wavelet_fft = fft( exp(2*1i*pi*freqs2use(fi).*time) .* exp(-time.^2./(2*(s^2))) ,n_convolution);\n \n % phase angles from channel 1 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft1,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n phase_sig1 = angle(reshape(convolution_result_fft,EEG.pnts,EEG.trials));\n \n % phase angles from channel 2 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft2,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n phase_sig2 = angle(reshape(convolution_result_fft,EEG.pnts,EEG.trials));\n \n % phase angle differences\n phase_diffs = phase_sig1-phase_sig2;\n \n % compute ICPS over trials\n ps(fi,:) = abs(mean(exp(1i*phase_diffs(times2saveidx,:)),2));\n \n % compute time window in indices for this frequency\n time_window_idx = round((1000/freqs2use(fi))*timewindow(fi)/(1000/EEG.srate));\n% time_window_idx = round(300/(1000/EEG.srate)); % set 300 to 100 for figure 3c/d\n \n for ti=1:length(times2save)\n \n % compute phase synchronization\n phasesynch = abs(mean(exp(1i*phase_diffs(times2saveidx(ti)-time_window_idx:times2saveidx(ti)+time_window_idx,:)),1));\n \n % average over trials\n ispc(fi,ti) = mean(phasesynch);\n end\nend % end frequency loop\n\nfigure\ncontourf(times2save,freqs2use,ispc-repmat(mean(ispc(:,baselineidx(1):baselineidx(2)),2),1,size(ispc,2)),20,'linecolor','none')\nset(gca,'clim',[-.08 .08],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)))\nxlabel('Time (ms)'), ylabel('Frequency (Hz)')\n\nfigure\nplot(freqs2use,(1000./freqs2use).*timewindow*2,'o-','markerface','k')\nhold on\nplot(freqs2use,(1000./freqs2use).*timewindow(1)*2,'ro-','markerface','m')\nylabel('Window width (ms)'), xlabel('Frequency (Hz)')\nlegend({'variable windows';'fixed 3*f window'})\n\n%% Figure 26.4\n\nfigure\nfor i=1:8\n subplot(8,1,i)\n plot(phase_sig1(1:200,i)-phase_sig2(1:200,i))\nend\n\nfigure\nsubplot(121)\npolar(repmat(phase_sig1(1:200,1)-phase_sig2(1:200,1),2,1),repmat([0 1]',200,1),'k');\ntitle('Phase angle differences over time')\n\nsubplot(122)\npolar(repmat(phase_sig1(100,1:i)-phase_sig2(100,1:i),2,1),repmat([0 1]',1,i),'k');\ntitle('Phase angle differences over trials')\n\n%% Figure 26.5\n\nfigure\ncontourf(times2save,freqs2use,bsxfun(@minus,ps,mean(ps(:,baselineidx(1):baselineidx(2)),2)),20,'linecolor','none')\nset(gca,'clim',[-.2 .2],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)),'xlim',[-300 800])\nxlabel('Time (ms)'), ylabel('Frequency (Hz)')\n\n%% figure 26.6\n\ntime2use = 300; % ms\nniterations = 50; % you can decrease this to make the code a bit faster\n\n% initialize\nispcByNandF = zeros(length(freqs2use),EEG.trials);\ntime2useidx = dsearchn(times2save',time2use);\n\n% data FFTs\ndata_fft1 = fft(reshape(EEG.data(chanidx(1),:,:),1,n_data),n_convolution);\ndata_fft2 = fft(reshape(EEG.data(chanidx(2),:,:),1,n_data),n_convolution);\n\nfor fi=1:length(freqs2use)\n \n % create wavelet and take FFT\n s = num_cycles(fi)/(2*pi*freqs2use(fi));\n wavelet_fft = fft( exp(2*1i*pi*freqs2use(fi).*time) .* exp(-time.^2./(2*(s^2))) ,n_convolution);\n \n % phase angles from channel 1 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft1,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n phase_sig1 = angle(reshape(convolution_result_fft,EEG.pnts,EEG.trials));\n \n % phase angles from channel 2 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft2,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n phase_sig2 = angle(reshape(convolution_result_fft,EEG.pnts,EEG.trials));\n \n % phase angle differences\n phase_diffs = phase_sig1-phase_sig2;\n \n for n=1:EEG.trials\n % multiple iterations to select different random sets of trials\n for iteri=1:niterations\n trials2use = randsample(EEG.trials,n);\n ispcByNandF(fi,n) = ispcByNandF(fi,n) + mean(abs(mean(exp(1i*phase_diffs(times2saveidx(time2useidx)-time_window_idx:times2saveidx(time2useidx)+time_window_idx,trials2use)),2)),1);\n end\n end\nend\n\nfigure\nplot(1:EEG.trials,ispcByNandF/iteri)\nxlabel('Trials')\nylabel('ICPS-trials')\n\n%% Figure 26.7\n\n% initialize\ndata4test = zeros(2,EEG.pnts,EEG.trials);\ndata4power = zeros(2,EEG.pnts,EEG.trials);\n\namp_mod = 0.00001;\n\nfor triali=1:EEG.trials\n % each trial is a random channel and trial\n trialdata1 = EEG.data(chanidx(1),:,triali);\n trialdata2 = EEG.data(chanidx(2),:,triali);\n \n % Un/comment the next line of code for band-pass filtered data.\n % This uses the eegfilt function, which is part of the eeglab toolbox.\n % You can also replace this function with your preferred filter method (chapter 14).\n trialdata1 = eegfilt(double(trialdata1),EEG.srate,10,20);\n trialdata2 = eegfilt(double(trialdata2),EEG.srate,10,20);\n \n % phase angle differences, with and without amplitude dampening\n data4test(1,:,triali) = angle(hilbert(trialdata1)) - angle(hilbert(trialdata2));\n data4test(2,:,triali) = angle(hilbert(trialdata1)) - angle(hilbert(trialdata2*amp_mod));\n \n data4power(1,:,triali) = abs(hilbert(trialdata2)).^2;\n data4power(2,:,triali) = abs(hilbert(trialdata2*amp_mod)).^2;\nend\n\n% compute ITPC\nispc_nomod = abs(mean(exp(1i*data4test(1,:,:)),3));\nispc_mod = abs(mean(exp(1i*data4test(2,:,:)),3));\n\n% compute power\npower = squeeze(mean(data4power,3));\n\n% plot!\nfigure\nsubplot(311)\nplot(EEG.times,trialdata2)\nhold on\nplot(EEG.times,trialdata2*amp_mod,'r')\ntitle('Amplitude modulator')\n\nsubplot(312)\nplot(EEG.times,data4test(1,:,10))\nhold on\nplot(EEG.times,data4test(2,:,10),'r')\naxis tight\nset(gca,'ytick',-2*pi:pi:2*pi)\ntitle('Example trials')\n\nsubplot(313)\nplot(EEG.times,ispc_mod,'ro')\nhold on\nh=plotyy(EEG.times,ispc_nomod,EEG.times,squeeze(mean(data4power(1,:,:),3)));\nlegend({'amplitude modulation';'no amp mod'})\nset(h(2),'ylim',[12 36])\nset(h(1),'ylim',[0 .4])\nxlabel('Time (ms)'), ylabel('ICPS')\ntitle('ICPS')\n\nfigure\nsubplot(121)\nplot(power(1,:),ispc_nomod,'.')\naxis square\nxlabel('Power'), ylabel('ICPS')\ntitle('non-modulated power')\n\nsubplot(122)\nplot(power(2,:),ispc_mod,'.')\naxis square\nxlabel('Power'), ylabel('ICPS')\ntitle('modulated power')\n\n%% figure 26.8\n\n% select channels\nchannel1 = 'fz';\nchannel2 = 'o1';\n\n% wavelet and FFT parameters\ntime = -1:1/EEG.srate:1;\nhalf_wavelet = (length(time)-1)/2;\nn_wavelet = length(time);\nn_data = EEG.pnts*EEG.trials;\nn_convolution = n_wavelet+n_data-1;\n\nchanidx = zeros(1,2); % always initialize!\nchanidx(1) = find(strcmpi(channel1,{EEG.chanlocs.labels}));\nchanidx(2) = find(strcmpi(channel2,{EEG.chanlocs.labels}));\n\n% data FFTs\ndata_fft1 = fft(reshape(EEG.data(chanidx(1),:,:),1,n_data),n_convolution);\ndata_fft2 = fft(reshape(EEG.data(chanidx(2),:,:),1,n_data),n_convolution);\n\n\n% initialize\nspectcoher = zeros(length(freqs2use),length(times2save));\n\nfor fi=1:length(freqs2use)\n \n % create wavelet and take FFT\n s = num_cycles(fi)/(2*pi*freqs2use(fi));\n wavelet_fft = fft( exp(2*1i*pi*freqs2use(fi).*time) .* exp(-time.^2./(2*(s^2))) ,n_convolution);\n \n % phase angles from channel 1 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft1,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n sig1 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n \n % phase angles from channel 2 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft2,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n sig2 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n \n % compute power and cross-spectral power\n spec1 = mean(sig1.*conj(sig1),2);\n spec2 = mean(sig2.*conj(sig2),2);\n specX = abs(mean(sig1.*conj(sig2),2)).^2;\n \n % alternative notation for the same procedure, using the Euler-like expression: Me^ik\n %spec1 = mean(abs(sig1).^2,2);\n %spec2 = mean(abs(sig2).^2,2);\n %specX = abs(mean( abs(sig1).*abs(sig2) .* exp(1i*(angle(sig1)-angle(sig2))) ,2)).^2;\n \n % compute spectral coherence, using only requested time points\n spectcoher(fi,:) = specX(times2saveidx)./(spec1(times2saveidx).*spec2(times2saveidx));\n \n % yet another equivalent notation, just FYI\n %spec1 = sum(sig1.*conj(sig1),2);\n %spec2 = sum(sig2.*conj(sig2),2);\n %specX = sum(sig1.*conj(sig2),2);\n %spectcoher(fi,:) = abs(specX(times2saveidx)./sqrt(spec1(times2saveidx).*spec2(times2saveidx))).^2;\n \n \n % imaginary coherence\n %spec1 = sum(sig1.*conj(sig1),2);\n %spec2 = sum(sig2.*conj(sig2),2);\n %specX = sum(sig1.*conj(sig2),2);\n % spectcoher(fi,:) = abs(imag(specX(times2saveidx)./sqrt(spec1(times2saveidx).*spec2(times2saveidx))));\nend\n\n\nfigure\nsubplot(121)\ncontourf(times2save,freqs2use,spectcoher,20,'linecolor','none') % \nset(gca,'clim',[0 .2],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)),'xlim',[times2save(1) times2save(end)])\ntitle('\"Raw\" spectral coherence')\n\nsubplot(122)\ncontourf(times2save,freqs2use,spectcoher-repmat(mean(spectcoher(:,baselineidx(1):baselineidx(2)),2),1,size(spectcoher,2)),20,'linecolor','none') % \nset(gca,'clim',[-.1 .1],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)),'xlim',[times2save(1) times2save(end)])\nxlabel('Time (ms)'), ylabel('Frequency (Hz)')\ntitle('Baseline-subtracted spectral coherence')\n\n%% Figure 26.9\n\n% number of \"trials\"\nn = 100;\n\nfigure\n\nsubplot(221)\nphases = rand(n,1)*pi;\npolar([phases; phases],repmat([0 1]',n,1),'k');\npli = abs(mean(sign(imag(exp(1i*phases)))));\nispc = abs(mean(exp(1i*phases)));\ntitle([ 'PLI=' num2str(pli) ', ISPC=' num2str(ispc) ])\n\nsubplot(222)\nphases = phases-pi/2;\npolar([phases; phases],repmat([0 1]',n,1),'k');\npli = abs(mean(sign(imag(exp(1i*phases)))));\nispc = abs(mean(exp(1i*phases)));\ntitle([ 'PLI=' num2str(pli) ', ISPC=' num2str(ispc) ])\n\n\nsubplot(223)\nphases = rand(n,1)/2+pi/3+.25;\npolar([phases; phases],repmat([0 1]',n,1),'k');\npli = abs(mean(sign(imag(exp(1i*phases)))));\nispc = abs(mean(exp(1i*phases)));\ntitle([ 'PLI=' num2str(pli) ', ISPC=' num2str(ispc) ])\n\nsubplot(224)\nphases = phases-pi/2;\npolar([phases; phases],repmat([0 1]',n,1),'k');\npli = abs(mean(sign(imag(exp(1i*phases)))));\nispc = abs(mean(exp(1i*phases)));\ntitle([ 'PLI=' num2str(pli) ', ISPC=' num2str(ispc) ])\n\n\n%% Figure 26.10\n\n% select channels\nchannel1 = 'fz';\nchannel2 = 'o1';\n\n% specify some time-frequency parameters\nfreqs2use = logspace(log10(4),log10(30),15); % 4-30 Hz in 15 steps\ntimes2save = -400:10:800;\ntimewindow = linspace(1.5,3,length(freqs2use)); % number of cycles on either end of the center point (1.5 means a total of 3 cycles))\nbaselinetm = [-400 -200];\n\n% wavelet and FFT parameters\ntime = -1:1/EEG.srate:1;\nhalf_wavelet = (length(time)-1)/2;\nnum_cycles = logspace(log10(4),log10(8),length(freqs2use));\nn_wavelet = length(time);\nn_data = EEG.pnts*EEG.trials;\nn_convolution = n_wavelet+n_data-1;\n\n% time in indices\ntimes2saveidx = dsearchn(EEG.times',times2save');\nbaselineidxF = dsearchn(EEG.times',baselinetm'); % for the full temporal resolution data (thanks to Daniel Roberts for finding/reporting this bug here!)\nbaselineidx = dsearchn(times2save',baselinetm'); % for the temporally downsampled data\n\nchanidx = zeros(1,2); % always initialize!\nchanidx(1) = find(strcmpi(channel1,{EEG.chanlocs.labels}));\nchanidx(2) = find(strcmpi(channel2,{EEG.chanlocs.labels}));\n\n% data FFTs\ndata_fft1 = fft(reshape(EEG.data(chanidx(1),:,:),1,n_data),n_convolution);\ndata_fft2 = fft(reshape(EEG.data(chanidx(2),:,:),1,n_data),n_convolution);\n\n% initialize\nispc = zeros(length(freqs2use),EEG.pnts);\npli = zeros(length(freqs2use),EEG.pnts);\nwpli = zeros(length(freqs2use),EEG.pnts);\ndwpli = zeros(length(freqs2use),EEG.pnts);\ndwpli_t = zeros(length(freqs2use),length(times2save));\nispc_t = zeros(length(freqs2use),length(times2save));\n\nfor fi=1:length(freqs2use)\n \n % create wavelet and take FFT\n s = num_cycles(fi)/(2*pi*freqs2use(fi));\n wavelet_fft = fft( exp(2*1i*pi*freqs2use(fi).*time) .* exp(-time.^2./(2*(s^2))) ,n_convolution);\n \n % phase angles from channel 1 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft1,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n sig1 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n \n % phase angles from channel 2 via convolution\n convolution_result_fft = ifft(wavelet_fft.*data_fft2,n_convolution);\n convolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\n sig2 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n \n % cross-spectral density\n cdd = sig1 .* conj(sig2);\n \n % ISPC\n ispc(fi,:) = abs(mean(exp(1i*angle(cdd)),2)); % note: equivalent to ispc(fi,:) = abs(mean(exp(1i*(angle(sig1)-angle(sig2))),2));\n \n \n % take imaginary part of signal only\n cdi = imag(cdd);\n \n % phase-lag index\n pli(fi,:) = abs(mean(sign(imag(cdd)),2));\n \n % weighted phase-lag index (eq. 8 in Vink et al. NeuroImage 2011)\n wpli(fi,:) = abs( mean( abs(cdi).*sign(cdi) ,2) )./mean(abs(cdi),2);\n \n % debiased weighted phase-lag index (shortcut, as implemented in fieldtrip)\n imagsum = sum(cdi,2);\n imagsumW = sum(abs(cdi),2);\n debiasfactor = sum(cdi.^2,2);\n dwpli(fi,:) = (imagsum.^2 - debiasfactor)./(imagsumW.^2 - debiasfactor);\n \n % compute time window in indices for this frequency\n time_window_idx = round((1000/freqs2use(fi))*timewindow(fi)/(1000/EEG.srate));\n\n for ti=1:length(times2save)\n imagsum = sum(cdi(times2saveidx(ti)-time_window_idx:times2saveidx(ti)+time_window_idx,:),1);\n imagsumW = sum(abs(cdi(times2saveidx(ti)-time_window_idx:times2saveidx(ti)+time_window_idx,:)),1);\n debiasfactor = sum(cdi(times2saveidx(ti)-time_window_idx:times2saveidx(ti)+time_window_idx,:).^2,1);\n dwpli_t(fi,ti) = mean((imagsum.^2 - debiasfactor)./(imagsumW.^2 - debiasfactor));\n\n % compute phase synchronization\n phasesynch = abs(mean(exp(1i*angle(cdd(times2saveidx(ti)-time_window_idx:times2saveidx(ti)+time_window_idx,:))),1));\n ispc_t(fi,ti) = mean(phasesynch);\n end\nend\n\n% baseline subtraction from all measures\nispc = bsxfun(@minus,ispc,mean(ispc(:,baselineidxF(1):baselineidxF(2)),2)); % not plotted in the book, but you can plot it for comparison with PLI\nispc_t = bsxfun(@minus,ispc_t,mean(ispc_t(:,baselineidx(1):baselineidx(2)),2));\npli = bsxfun(@minus,pli,mean(pli(:,baselineidxF(1):baselineidxF(2)),2));\ndwpli = bsxfun(@minus,dwpli,mean(dwpli(:,baselineidxF(1):baselineidxF(2)),2));\ndwpli_t = bsxfun(@minus,dwpli_t,mean(dwpli_t(:,baselineidx(1):baselineidx(2)),2));\n\nfigure\nsubplot(221)\ncontourf(times2save,freqs2use,pli(:,times2saveidx),40,'linecolor','none')\nset(gca,'clim',[-.3 .3],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)))\ntitle('PLI over trials')\n\nsubplot(222)\ncontourf(times2save,freqs2use,dwpli(:,times2saveidx),40,'linecolor','none')\nset(gca,'clim',[-.2 .2],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)))\ntitle('dWPLI over trials')\n\nsubplot(223)\ncontourf(times2save,freqs2use,ispc_t,40,'linecolor','none')\nset(gca,'clim',[-.1 .1],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)))\ntitle('ICPS over time')\n\nsubplot(224)\ncontourf(times2save,freqs2use,dwpli_t,40,'linecolor','none')\nset(gca,'clim',[-.1 .1],'yscale','log','ytick',round(logspace(log10(freqs2use(1)),log10(freqs2use(end)),8)))\ntitle('dWPLI over time')\n\n%% Figure 26.11\n\ntrial2plot = 10; % any trial between 1 and 99 (book uses trial 10)\ncenter_freq = 4.6; % Hz (book uses 4.6)\n\n\n% create wavelet and take FFT\ns = 4.5/(2*pi*center_freq);\nwavelet_fft = fft( exp(2*1i*pi*center_freq.*time) .* exp(-time.^2./(2*(s^2))) ,n_convolution);\n% phase angles from channel 1 via convolution\nconvolution_result_fft = ifft(wavelet_fft.*data_fft1,n_convolution);\nconvolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\nsig1 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n% phase angles from channel 2 via convolution\nconvolution_result_fft = ifft(wavelet_fft.*data_fft2,n_convolution);\nconvolution_result_fft = convolution_result_fft(half_wavelet+1:end-half_wavelet);\nsig2 = reshape(convolution_result_fft,EEG.pnts,EEG.trials);\n% cross-spectral density\nxsd = sig1 .* conj(sig2);\nxsdi = imag(xsd);\n\ndwpli = zeros(size(EEG.times));\nispc = zeros(size(EEG.times));\n\n[junk,animate_start] = min(abs(EEG.times-0));\n[junk,animate_stop] = min(abs(EEG.times-1000));\n\ntime_window_idx = round(100*timewindow(1)/(1000/EEG.srate));\n\nfigure\nsubplot(121)\nhpol = polar(repmat(angle(xsd(animate_start:animate_start+time_window_idx-1,trial2plot)),1,2)',[zeros(time_window_idx,1) ones(time_window_idx,1)]','k-o');\nsubplot(122)\nhplo2 = plot(EEG.times,0,'r');\nhold on\nhplo1 = plot(EEG.times,0,'b');\n\nfor idx=animate_start:animate_stop\n \n % update angles\n for i=1:length(hpol)\n set(hpol(i),'XData',[0; cos(angle(xsd(idx+i,trial2plot)))],'YData',[0; sin(angle(xsd(idx+i,trial2plot)))]);\n end\n title([ num2str(round(EEG.times(idx))) '-' num2str(round(EEG.times(idx+i))) ' ms' ])\n\n % compute ICPS and dwPLI\n ispc(idx) = abs(mean(exp(1i*angle(xsd(idx:idx+i,trial2plot))),1));\n \n imagsum = sum(xsdi(idx:idx+i,trial2plot),1);\n imagsumW = sum(abs(xsdi(idx:idx+i,trial2plot)),1);\n debiasfactor = sum(xsdi(idx:idx+i,trial2plot).^2,1);\n dwpli(idx) = mean((imagsum.^2 - debiasfactor)./(imagsumW.^2 - debiasfactor));\n \n \n set(hplo1,'XData',EEG.times(1:idx),'YData',ispc(1:idx));\n set(hplo2,'XData',EEG.times(1:idx),'YData',dwpli(1:idx));\n set(gca,'xlim',EEG.times([animate_start animate_stop]),'ylim',[-.1 1.1])\n axis square\n \n pause(0.01)\nend\n\n%% Figure 26.12\n\n% This figure is generated in the code below.\n\n%% Figure 26.13\n\n% generate inline functions (small functions that you define without being\n% saved as general Matlab functions)\nvtest = inline('n.*icpcmag*cos(val).*sqrt(2./n)');\ngvtest = inline('n.*(icpcmag*exp((-(val).^2)./(4.*pi./n)).*(sqrt(2./n)))');\n\n% Since initially writing this code, Matlab decided to make the inline\n% function obsolete in future versions. The following two lines produce\n% the identical 'anonymous functions' as the previous two lines.\n%vtest = @(icpcmag,n,val) n.*icpcmag*cos(val).*sqrt(2./n);\n%gvtest = @(icpcmag,n,val) n.*(icpcmag*exp((-(val).^2)./(4.*pi./n)).*(sqrt(2./n)));\n\n\n% figure\nclf\nsubplot(221)\nn = 2:100;\nplot(n,1-normcdf(vtest(.3,n,pi/10)))\nhold on\nplot(n,1-normcdf(gvtest(.3,n,pi/10)),'m')\nlegend({'v-test';'gv-test'})\nxlabel('Number of points'), ylabel('P-value')\nset(gca,'ylim',[0 .6])\ntitle('angle = pi/10')\n\nsubplot(222)\nplot(n,1-normcdf(vtest(.3,n,pi/3)))\nhold on\nplot(n,1-normcdf(gvtest(.3,n,pi/3)),'m')\nlegend({'v-test';'gv-test'})\nxlabel('Number of points'), ylabel('P-value')\nset(gca,'ylim',[0 .6])\ntitle('angle = pi/3')\n\nsubplot(223)\nx=linspace(-pi,pi,50);\nn=15;\npolar(x,1-normcdf(vtest(.3,n,x-0)))\nhold on\npolar(x,1-normcdf(gvtest(.3,n,x-0)),'m')\ntitle([ 'N=' num2str(n) ])\n\nsubplot(224)\nn=600;\npolar(x,1-normcdf(vtest(.3,n,x-0)))\nhold on\npolar(x,1-normcdf(gvtest(.3,n,x-0)),'m')\nset(gca,'xtick',round((-pi:pi/4:pi)*100)/100)\ntitle([ 'N=' num2str(n) ])\n\n% number of simulated data points\nnumUsims = 10000;\n\nu = zeros(2,numUsims);\n\nfor i=1:numUsims\n \n % make some noise\n fake_phase_data = rand(2,EEG.pnts)*pi*2-pi;\n \n % compute ispc\n ispc_mag = abs (mean(exp(1i*(diff(fake_phase_data,1)))));\n ispc_phs = angle(mean(exp(1i*(diff(fake_phase_data,1)))));\n \n % compute statistics\n u(1,i) = vtest (ispc_mag,EEG.pnts,ispc_phs-0);\n u(2,i) = gvtest(ispc_mag,EEG.pnts,ispc_phs-0);\nend\n\n\n% This figure is also figure 26.12 but with no log-scaling\nfigure\nfor i=1:2\n subplot(1,2,i)\n \n [y,x]=hist(u(i,:),100);\n h=bar(x,log10(y),'histc');\n set(h,'linestyle','none')\n \n title([ num2str(100*sum((1-normcdf(u(i,:)))<.05)/length(u)) '% false positive' ])\nend\n\n\nnrange = 10:300; % here n is number of datapoints\nispcrange = .05:.01:.7;\npvalmat = zeros(2,length(nrange),length(ispcrange));\n\nfor ni=1:length(nrange)\n for mi=1:length(ispcrange)\n \n n = nrange(ni);\n \n pvalmat(1,ni,mi) = 1-normcdf( vtest(ispcrange(mi),nrange(ni),pi/5));\n pvalmat(2,ni,mi) = 1-normcdf(gvtest(ispcrange(mi),nrange(ni),pi/5));\n end\nend\n\nfigure\nsubplot(121)\nimagesc(ispcrange,nrange,squeeze(pvalmat(1,:,:))), axis xy, \nset(gca,'clim',[0 .5])\nxlabel('ICPS strength'), ylabel('N')\ntitle('v-test')\n\nsubplot(122)\nimagesc(ispcrange,nrange,squeeze(pvalmat(2,:,:))), axis xy, \ntitle('gv-test')\nxlabel('ICPS strength'), ylabel('N')\nset(gca,'clim',[0 .5])\n\n%% end.\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/chapter26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6429906868244298}} {"text": "%% patchCurvature\n% Below is a demonstration of the features of the |patchCurvature| function\n\n%% Syntax\n% |[Vd,Fd,Fds]=patchCurvature(V,F);|\n\n%% Description\n% Computes curvature metrics for the patch data defined by the faces F and\n% the vertices V. \n\n%% Examples\n\n%%\nclear; close all; clc;\n\n%%\n% Plot settings\ncMap=warmcold(250);\n\n%%\n\n[F,V]=graphicsModels(9);\n% [F,V]=stanford_bunny;\n% [F,V]=tri2quad(F,V);\n\n%% Compute curvature\n\n[U_min,U_max,C_min,C_max,C_mean,C_gauss] = patchCurvature(F,V);\n\n%% Visualize curvature on mesh\n\n% Compute plot variables\nC_min_V=faceToVertexMeasure(F,V,C_min); %Vertex data for interpolated shading\nC_max_V=faceToVertexMeasure(F,V,C_max); %Vertex data for interpolated shading\nVN=patchCentre(F,V); %Element centres used for vector origins\nvecPlotSize=mean(patchEdgeLengths(F,V)); %Vector plotting size\n\n% Visualize\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('C_{min}');\nhp=gpatch(F,V,C_min_V,'none',0.9);\nhp.FaceColor='interp';\ncolormap(gca,cMap); colorbar;\nquiverVec(VN,U_min,vecPlotSize,'k');\naxisGeom; \nc=max(abs(C_min(:)));\ncaxis(0.25*[-c c]);\ncamlight headlight;\n \nsubplot(1,2,2); hold on;\ntitle('C_{max}');\nhp=gpatch(F,V,C_max_V,'none',0.9);\nhp.FaceColor='interp';\nquiverVec(VN,U_max,vecPlotSize,'k');\ncolormap(gca,cMap); colorbar;\naxisGeom;\nc=max(abs(C_max(:)));\ncaxis(0.25*[-c c]);\ncamlight headlight;\n\ndrawnow;\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_patchCurvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6429452201810444}} {"text": "%GSP_DEMO Tutorial on the GSPBox\n% \n% In this demo, we are going to show the basic operations of the GSPBox.\n% To lauch the toolbox, just go into the repository where the GSPBox was\n% extracted and type:\n%\n% gsp_start;\n%\n% A banner will popup telling you that everything happens correctly. To\n% speedup some processing, you might want to compile some mexfile. Refer\n% to |gsp_make| for more informations. However, if the compilation is not\n% working on your computer, keep quiet, everything should still work and\n% most of the routine are implemented only in matlab.\n%\n% Most likely, the first thing you would like to do is to create a graph.\n% To do so, you only need the adjacendy or the weight matrix $W$. Once\n% you have it, you can construct a graph using::\n%\n% G = gsp_graph(W);\n%\n% This function will create a full structure ready to be used with the\n% toolbox. To know a bit more about what is in this structure, you can\n% refer to the help of the function |gsp_graph_default_parameters|.\n%\n% The GSPBox contains also a list of graph generators. To see a full list\n% of these graphs, type:::\n%\n% help graphs\n%\n% For this demo, we will use the graph |gsp_logo|. You can load it\n% using:::\n%\n% G = gsp_logo\n%\n% Here observe the attribute of the structure *G*. \n%\n% * *G.W*: Weight matrix \n% * *G.A*: Adacency matrix \n% * *G.N*: Number of nodes \n% * *G.type*: Type of graph \n% * *G.directed*: 1 if the graph is directed, 0 if not\n% * *G.lap_type*: Laplacian type \n% * *G.d*: Degree vector \n% * *G.Ne*: Number of edges\n% * *G.coords*: Coordinates of the vertices\n% * *G.plotting*: Plotting parameters \n%\n% In the folder 'plotting', the GSPBox contains some plotting routine.\n% For instance, we can plot a graph using::\n%\n% gsp_plot_graph(G);\n%\n% .. figure::\n%\n% GSP graph\n%\n% This figure shows the result of the command 'gsp_plot_graph(G)'\n%\n% Wonderful! Isn't it? Now, let us start to analyse this graph. To compute\n% graph Fourier transform or exact graph filtering, you need to\n% precompute the Fourier basis of the graph. This operation could be\n% relatively long since it involves a full diagonalization of the\n% Laplacian. Don't worry, you do not need to perform this operation to\n% filter signals on graph. The fourier basis is computed by::\n%\n% G = gsp_compute_fourier_basis(G);\n%\n% The function |gsp_compute_fourier_basis| add two new fields to the\n% structure *G*:\n%\n% * *G.U*: The eigenvectors of the Fourier basis\n% * *G.e*: The eigenvalues\n%\n% The fourier eigenvectors does look like a sinusoide on the graph. Let's\n% plot the second and the third ones. (The first one is constant!)::\n%\n% gsp_plot_signal(G,G.U(:,2));\n% title('Second eigenvector')\n% subplot(212)\n% gsp_plot_signal(G,G.U(:,3));\n% title('Third eigenvector')\n%\n% .. figure::\n%\n% Eigenvectors\n%\n%\n%\n% Now, we are going to show a basic filtering operation. Filters are usually\n% defined in the spectral domain. To define the following filter\n%\n% .. h(x) = 1/(1+tau*x),\n%\n% .. math:: h(x) =\\frac{1}{1+\\tau x},\n%\n% just write in Matlab::\n%\n% tau = 1;\n% h = @(x) 1./(1+tau*x);\n%\n% Hint: You can define filterbank using cell array!\n%\n% Let's display this filter::\n%\n% gsp_plot_filter(G,h);\n%\n% .. figure::\n%\n% Low pass filter $h$\n%\n% The filter $h$ is plotted along all the spectrum of the graph.\n% The black cross are the eigenvalues of the Laplacian. They are the\n% points where the continuous filter will be evaluated to create a\n% discrete filter.\n%\n% To apply the filter to a given signal, you only need to run a single\n% function::\n%\n% % Create a signal\n% f = zeros(G.N,1);\n% f(G.info.idx_g) = -1;\n% f(G.info.idx_s) = 1;\n% f(G.info.idx_p) = -0.5;\n% f = f + 0.3*randn(G.N,1);\n% % Remove the noise\n% f2 = gsp_filter(G,h,f);\n%\n% `gsp_filter` is actually a shortcut to |gsp_filter_analysis|.\n% `gsp_filter_analysis` performs the analysis operator associated to a\n% filterbank. See the |gsp_demo_wavelet| for more information.\n%\n% Finnaly, we display the result of this low pass filtering on the graph::\n%\n% figure;\n% subplot(211)\n% gsp_plot_signal(G,f);\n% title('Signal with noise')\n% subplot(212)\n% gsp_plot_signal(G,f2);\n% title('Signal denoised');\n%\n% .. figure::\n%\n% Result of filtering\n%\n% The noise is largely removed thanks to the filter. However, some\n% energy is diffused between the letters. This is the typical\n% behaviour of a low pass filter.\n%\n% Enjoy the GSPBOX !\n%\n\n\n% Author: Nathanael Perraudin\n% Date : 14 August 2014\n\nclear;\nclose all;\n\nG = gsp_logo;\n\n% display the graph\nfigure;\ngsp_plot_graph(G);\n\n%% Compute the Fourier basis\n\nG = gsp_compute_fourier_basis(G);\n\n% Display an eigenvector\nfigure;\nsubplot(211)\ngsp_plot_signal(G,G.U(:,2));\ntitle('Second eigenvector')\nsubplot(212)\ngsp_plot_signal(G,G.U(:,3));\ntitle('Third eigenvector')\n\n%% Create a signal\n\nf = zeros(G.N,1);\nf(G.info.idx_g) = -1;\nf(G.info.idx_s) = 1;\nf(G.info.idx_p) = -0.5;\nf = f + 0.3*randn(G.N,1);\n\n\n%% Define a low pass filter\ntau = 1;\nh = @(x) 1./(1+tau*x);\n\nfigure\ngsp_plot_filter(G,h);\ntitle('Filter h')\n\n\n%% Perform the filtering operation\nf2 = gsp_filter(G,h,f);\n% f2 = gsp_filter_analysis(G,h,f);\n\n\n% Display the result\nfigure;\nsubplot(211)\ngsp_plot_signal(G,f);\ntitle('Signal with noise')\nsubplot(212)\ngsp_plot_signal(G,f2);\ntitle('Signal denoised');\n\n\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/demos/gsp_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.6429452197054958}} {"text": "function [dyc, dyt]=hamfilter(X,h,d,ck,fig,timeplot, nameplot)\n\n% local projections (direct forecast) to perform detrending\n% regressions\n% y(t+h)= a*y(t)+b*y(t-1)+c*y(t-2)+...+d*y(t-d)+ e(t+h)\n% cycle is e(t+h)\n% trend is hat(a)*y(t)+hat(b)*y(t-1)+hat(c)*y(t-2)+...+hat(d)*y(t-d)\n\n% h= horizon of the projection\n% d= number of lags used\n% ck if=1 constant if =0 no constant in the projection\n\n% dyc = estimated cycle\n% dyt = estimated trend\n\n[enddT,QQ]=size(X);\nyc=zeros(enddT,QQ); yt=zeros(enddT,QQ);\nR=[];\nT = 1:1:enddT;\ntime = T;\nif nargin > 5\n time =timeplot;\nend\nif nargin > 6\n titleplot = nameplot;\n if length(nameplot) ~= size(X,2)\n error('nameplot size shold be the same as the column of Y')\n end\nelse\n for v = 1 : size(X,2)\n eval(['titleplot{' num2str(v) '} = ''Var' num2str(v) ''';'])\n end\nend\n\n\n\nfor qq=1:QQ\n yh=squeeze(X(d+h:enddT,qq)); % independent variable\n if ck==1\n R=ones(enddT-d-h+1,1); % constant\n end\n \n for jj=1:d\n r=squeeze(X(d+1-jj:enddT-h+1-jj,qq));\n R=[R r]; % dependent variables\n end\n \n yc(d+h:enddT,qq) = yh - R*((R'*R)\\(R'*yh)); % cycle\n yt(d+h:enddT,qq) = R*((R'*R)\\(R'*yh)); % trend\n \n if fig==1\n subplot(2,1,1)\n %plot(time(d+h:enddT),yh(1:enddT-d-h,1),'r', 'linewidth',2);hold on;\n plot(time(d+h:enddT),X(d+h:enddT,qq),'r', 'linewidth',2);hold on;\n plot(time(d+h:enddT),yt(d+h:enddT,qq),'k--','linewidth',2);hold off; axis tight;\n legend('data', 'Hamil trend')\n title(titleplot(qq))\n subplot(2,1,2)\n plot(time(d+h:enddT),yc(d+h:enddT,qq),'b', 'linewidth',2);\n legend('Hamil cycle')\n pause\n end\nend\ndyc=yc;\ndyt=yt;\nend", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/hamfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6429323465885483}} {"text": "%% DEMO_stent_hexahedral_sweeping_02\n% Below is a demonstration for:\n%\n% * Creating a hexahedral mesh for a vascular stent by sweeping allong a\n% curve and copying over the segments.\n\n%% Keywords\n% * Sweeping, sweepLoft\n% * Hexahedral mesh\n% * stent, vascular\n% * Exporting Abaqus, .inp\n\n%%\nclear; close all; clc;\n\n%%\n% plot settings\n\nfontSize=25;\nmarkerSize=10;\nlineWidth=3;\n\n%% Contol parameters\n\ncontrolParameterSet.stentRadius=3; %The outer radius of the stent\ncontrolParameterSet.numPeriodsWave=10; %The number of periods to use for a sinusoidal modulation\nnumStepsPeriod=100; %Number of sweeping steps allong a single period segment for sweeping\ncontrolParameterSet.stentSectionHeight=0.1; %Height of the stent wire\ncontrolParameterSet.stentSectionWidth=0.1; %Width of the stent wire\ncontrolParameterSet.numStepsCircumference=(controlParameterSet.numPeriodsWave*numStepsPeriod)+1; %Number of sweeping steps across curve\ncontrolParameterSet.overSampleFactorCurve=10; %Oversample factor curve\ncontrolParameterSet.numSplitSteps_axial=1;\ncontrolParameterSet.numSplitSteps_inward=1;\ncontrolParameterSet.plotOn=0;\n% controlParameterSet.waveAmplitude=0.9; %Amplitude of the sinusoidal modulation\n\nsheetLayerThickness=0.025;\nnumStepsSheet=1; \n\n%%\n\nnumSegments=8;\nwaveAmplitudes=0.6*ones(1,numSegments);\nwaveAmplitudes(2)=0.9; \noffsetLevels=waveAmplitudes*2; \n\noffSetTotal=0;\n\ncFigure; hold on;\ntitle('Stent hexahedral mesh','fontSize',fontSize);\ncolormap(gjet(4)); caxis([1 4]); icolorbar;\naxisGeom;\ncamlight headlight;\ndrawnow;\n \nE_stent_cell=cell(numSegments,1);\nV_stent_cell=cell(numSegments,1);\nE_sheet_cell=cell(numSegments,1);\nV_sheet_cell=cell(numSegments,1);\nfor q=1:1:numSegments\n \n controlParameterSet.waveAmplitude=waveAmplitudes(q); %Amplitude of the sinusoidal modulation\n [E,V]=stentSegmentDesign(controlParameterSet);\n \n offSetTotal=offSetTotal+offsetLevels(q);\n V(:,3)=V(:,3)+offSetTotal;\n \n %%\n \n C=hexVol(E,V); %Get hexahedral element volumes\n \n [F,CF]=element2patch(E,C); %Create face data for plotting\n \n [indBoundary]=tesBoundary(F,V);\n faceMarker=ones(size(E,1),1)*(1:6); %The 6 face colors for the hexahedral faces \n faceMarker=faceMarker(:); %Force as a column\n Fb=F(indBoundary,:); %Select the boundary faces (which will exclude tops (1) and bottoms (2))\n faceBoundaryMarker=faceMarker(indBoundary,:)-2; %Get boundary colors and subtract 2 so they are 1-4\n \n %%\n gpatch(Fb,V,faceBoundaryMarker,'k',1);\n \n %%\n \n F_inner = Fb(faceBoundaryMarker==2,:);\n [edgesBoundaryInner]=patchBoundary(F_inner,V);\n \n edgesBottom=F_inner(:,[4 1]);\n edgesTop=F_inner(:,[2 3]);\n \n edgesBoundaryInnerTop=edgesBoundaryInner(all(ismember(edgesBoundaryInner,edgesTop),2),:);\n edgesBoundaryInnerBottom=edgesBoundaryInner(all(ismember(edgesBoundaryInner,edgesBottom),2),:);\n \n indCurveTop=edgeListToCurve(edgesBoundaryInnerTop);\n indCurveTop=flip(indCurveTop(1:end-1));\n indCurveBottom=edgeListToCurve(edgesBoundaryInnerBottom);\n indCurveBottom=indCurveBottom(1:end-1);\n \n plotV(V(indCurveTop(:),:),'r-','LineWidth',lineWidth);\n plotV(V(indCurveBottom(:),:),'b-','LineWidth',lineWidth);\n \n drawnow; \n \n %%\n if q==1\n [FQ,VQ]=patchCleanUnused(F_inner,V);\n else\n cPar.closeLoopOpt=1;\n cPar.patchType='quad';\n [Fq,Vq]=polyLoftLinear(V_curveTopPrevious,V(indCurveBottom(:),:),cPar); \n% gpatch(Fq,Vq,'rw','rw',1);\n [F_inner_clean,V_inner_clean]=patchCleanUnused(F_inner,V);\n [FQ,VQ]=joinElementSets({Fq,F_inner_clean},{Vq,V_inner_clean});\n [FQ,VQ]=mergeVertices(FQ,VQ);\n% gpatch(FQ,VQ,'rw','rw',1);\n% patchNormPlot(FQ,VQ);\n end\n\n [E_sheet,V_sheet,Fq1,Fq2]=quadThick(FQ,VQ,1,sheetLayerThickness,numStepsSheet);\n \n [F_sheet]=element2patch(E_sheet); %Create face data for plotting\n gpatch(F_sheet,V_sheet,'gw','gw',1);\n % patchNormPlot(F_sheet,V_sheet);\n\n E_sheet_cell{q}=E_sheet;\n V_sheet_cell{q}=V_sheet;\n \n V_curveTopPrevious=V(indCurveTop(:),:); \n \n E_stent_cell{q}=E;\n V_stent_cell{q}=V;\n \nend\n\n%% Merge components\n\n[E_stent,V_stent,C_stent]=joinElementSets(E_stent_cell,V_stent_cell);\n[E_sheet,V_sheet,C_sheet]=joinElementSets(E_sheet_cell,V_sheet_cell);\n[E,V,C]=joinElementSets({E_stent,E_sheet},{V_stent,V_sheet},{C_stent,C_sheet+max(C_stent)});\n[E,V]=mergeVertices(E,V);\n \n[F,CF]=element2patch(E,C); %Create face data for plotting\n\n%%\ncFigure; hold on;\ntitle('Stent hexahedral mesh','fontSize',fontSize);\ngpatch(F,V,CF,'none',1);\n% patchNormPlot(F,V);\ncolormap gjet; icolorbar\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n%% Export inp file\n% \n% elementStruct.E=E;\n% elementStruct.E_ind=(1:size(E,1))';\n% elementStruct.E_type='*ELEMENT, TYPE=C3D8, ELSET=PART-STENT';\n% nodeStruct.N=V;\n% nodeStruct.N_ind=(1:size(V,1))';\n% \n% pathName = fileparts(fileparts(mfilename('fullpath')));\n% fileName=fullfile(pathName,'data','INP','stentMeshSheet.inp');\n% export_INP(elementStruct,nodeStruct,fileName);\n\n\n%% FUNCTIONS\n\nfunction [E,V]=stentSegmentDesign(controlParameterSet)\n\n%% parse input\n\nstentRadius=controlParameterSet.stentRadius; %The outer radius of the stent\nnumPeriodsWave=controlParameterSet.numPeriodsWave; %The number of periods to use for a sinusoidal modulation\nwaveAmplitude=controlParameterSet.waveAmplitude; %Amplitude of the sinusoidal modulation\nstentSectionHeight=controlParameterSet.stentSectionHeight; %Height of the stent wire\nstentSectionWidth=controlParameterSet.stentSectionWidth; %Width of the stent wire\nnumStepsCircumference=controlParameterSet.numStepsCircumference; %Number of sweeping steps across curve\noverSampleFactorCurve=controlParameterSet.overSampleFactorCurve; %Oversample factor curve\nnumSplitSteps_axial=controlParameterSet.numSplitSteps_axial;\nnumSplitSteps_inward=controlParameterSet.numSplitSteps_inward;\nplotOn=controlParameterSet.plotOn;\n\n%% plot settings\nif plotOn==1\n fontSize=25;\n markerSize=10;\n lineWidth=1;\nend\n\n%% Build stent section\n% The rectangular stent wire section is created here.\n\nV_section=[-stentSectionWidth/2 stentSectionHeight/2 0; ...\n stentSectionWidth/2 stentSectionHeight/2 0; ...\n stentSectionWidth/2 -stentSectionHeight/2 0; ...\n -stentSectionWidth/2 -stentSectionHeight/2 0; ...\n ];\n\n%%\n% V=isualize stent section\nif plotOn==1\n cFigure; hold on;\n title('Stent section','fontSize',fontSize);\n plotV(V_section,'b.-','lineWidth',lineWidth,'MarkerSize',markerSize);\n view(2); axis tight; axis equal; grid on; box on;\n set(gca,'fontSize',fontSize);\n drawnow;\nend\n\n%% Create guide curve\n% The sweepLoft (see |HELP_sweepLoft|) is created here. First and angle\n% based parameterization is created. Next this curve is evenly sample\n% across the curve length (see |HELP_evenlySampleCurve|).\nt=linspace(0,2*pi,numStepsCircumference*overSampleFactorCurve); %Angles\nt=t(1:end-1); %Remove last point so it is not closed for resampling\nx=stentRadius.*sin(t); %x-coordinates\ny=stentRadius.*cos(t); %y-coordinates\nz=waveAmplitude.*sin(numPeriodsWave*t); %z-coordinates\nV_guide_curve=[x(:) y(:) z(:)]; %Collected curve nodes\n[V_guide_curve] = evenlySampleCurve(V_guide_curve,numStepsCircumference-1,'pchip',1); %Resample curve evenly\nV_guide_curve(end+1,:)=V_guide_curve(1,:); %Append start to end so it is a closed loop\n\n%%\n% Visualize guide curve\nif plotOn==1\n cFigure; hold on;\n title('Stent guide curve','fontSize',fontSize);\n plotV(V_guide_curve,'k.-','lineWidth',lineWidth,'MarkerSize',markerSize);\n axisGeom;\n drawnow;\nend\n\n%% Position stent section at the start and end of the guide curve\n% Next the section is translated and rotated so it is placed at the start\n% of the guide curve such that the curve normal points allong the curve.\n\n% Create rotation matrix\nn3=vecnormalize(V_guide_curve(2,:)-V_guide_curve(1,:)); %Out of section normal direction z ish direction\n[~,indMin]=min(dot(n3(ones(1,2),:),[1 0 0; 0 1 0],2)); %Get index most appropriate initial other axis\nswitch indMin\n case 1\n n1=[1 0 0]; %Initialized x direction\n n2=vecnormalize(cross(n3,n1)); %y ish direction\n n1=vecnormalize(cross(n2,n3)); %Proper x ish direction\n R=[n1; n2; n3]; %Rotation matrix\n case 2\n n2=[0 1 0]; %Initialized y direction\n n1=vecnormalize(cross(n2,n3)); %x ish direction\n n2=vecnormalize(cross(n3,n1)); %Proper y ish direction\n R=[n1; n2; n3]; %Rotation matrix\nend\n\np1=V_guide_curve(1,:); %The start node\nV_section=V_section*R; %Rotate the section\nV_section=V_section+p1(ones(size(V_section,1),1),:); % Translate coordinate to start\n\n%%\n% Visualize guide curve\n\nif plotOn==1\n cFigure; hold on;\n title('Stent section positioned on guide curve','fontSize',fontSize);\n plotV(V_guide_curve,'k-','lineWidth',1);\n plotV(V_section,'k.-','lineWidth',lineWidth,'MarkerSize',markerSize);\n quiverVec(p1,n1,1,'r');\n quiverVec(p1,n2,1,'g');\n quiverVec(p1,n3,1,'b');\n axisGeom;\n drawnow;\nend\n\n%% Sweeping section allong curve\n% Normally |sweepLoft| produces patch data as an output (e.g. faces and\n% vertices). However these outputs are supressed here and the coordinate\n% mesh output is instead used to create a hexahedral mesh. See also |HELP_sweepLoft|\n\nnumTwist=0; %Number of additional twists of loft feature around guide curve\nnumStepsSweep=numStepsCircumference; %Number of steps for loft feature from sketch 1 to sketch 2\n[~,~,~,S]=sweepLoft(V_section,V_section,n3,n3,V_guide_curve,numStepsSweep,numTwist,0);\n\n%% Construct hexahedral mesh\n\nX=S.X'; Y=S.Y'; Z=S.Z'; %Coordinate matrices\nV=[X(:) Y(:) Z(:)]; %Create node list\n\nF=reshape((1:1:size(V,1)),4,size(V,1)/4)'; %All top and bottom faces\nE=[F(2:end,:) F(1:end-1,:)]; %The hexahedral elements\n[E,V]=mergeVertices(E,V); %Merge nodes (start and end are not shared yet)\n\n%% Refine mesh\n% The swept mesh can be refined through slitting. The splitting can be\n% homogeneous or only in a particular direction (see HELP_subHex|)\n% Split method explanation:\n% 1: Overall splitting in all directions\n% 2: Split allong curve direction\n% 3: Split axially\n% 4: Splint inward\n\nsplitMethod=3;\nnRefine=numSplitSteps_axial;\n[E,V]=subHex(E,V,nRefine,splitMethod);\n\nsplitMethod=4;\nnRefine=numSplitSteps_inward;\n[E,V]=subHex(E,V,nRefine,splitMethod);\n\n%%\n% Visualize hexahedral mesh\n\nif plotOn==1\n \n [F]=element2patch(E); %Create face data for plotting\n\n cFigure; hold on;\n title('Stent hexahedral mesh','fontSize',fontSize);\n plotV(V_guide_curve,'k-','lineWidth',3);\n gpatch(F,V,'gw','k',1);\n patchNormPlot(F,V); \n axisGeom;\n camlight headlight;\n drawnow;\nend\n\n%%\n\n\n\nend\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_stent_hexahedral_sweeping_02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6429323414940452}} {"text": "function ld = sn_ld(l, n_sensor, n_source, n_snapshot)\n%SN_LD Sufficient statistic for source number detection in MDL/AIC.\n% This function is used internally.\n%Syntax:\n% ld = SN_LD(l, n_sensor, n_source, n_snapshot);\n%Inputs:\n% l - Eigenvalues of the covariance matrix in descending order.\n% n_sensor - Number of sensors used. Should match the length of l.\n% n_source - Number of sources.\n% n_snapshot - Number of snapshots.\n%Outputs:\n% ld - Computed value.\n%Reference:\n% H. L. Van Trees, Optimum array processing. New York: Wiley, 2002.\n\ndiff = n_sensor - n_source;\nl = l(n_source+1:end);\nld = n_snapshot * diff * log(sum(l)/diff/(prod(l)^(1/diff)));\n\nend\n\n", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/estimator/sn_ld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6429323363995423}} {"text": "clear;\nt0=0;\ntf=10;\nb0=[0.2 0.2];\n[t,b]=ode45('dfun3',[t0, tf],b0);\nplot(b(:,1),b(:,2));\nhold on \nb0=[0.1 0.1];\n[t,b]=ode45('dfun3',[t0, tf],b0);\nplot(b(:,1),b(:,2));\nhold on \nb0=[0.2 0.15];\n[t,b]=ode45('dfun3',[t0, tf],b0);\nplot(b(:,1),b(:,2));\nhold on\nxlabel('x1');\nylabel('x2');", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/美赛A题常见代码/微分方程模型/program/program/phasespacef3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6429323316394823}} {"text": "function [ x, w ] = rule06 ( n )\n\n%*****************************************************************************80\n%\n%% RULE06 returns the rule of degree 6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, integer N, the number of nodes.\n%\n% Output, real X(2,N), the coordinates of the nodes.\n%\n% Output, real W(N), the weights.\n%\n xs = [ ...\n 0.4595981103653579E-16, ...\n 0.9258200997725515E+00, ...\n 0.6742045114073804E-16, ...\n -0.9258200997725515E+00, ...\n -0.3805544332083157E+00, ...\n 0.3805544332083157E+00, ...\n 0.3805544332083157E+00, ...\n -0.3805544332083157E+00, ...\n -0.8059797829185990E+00, ...\n 0.8059797829185988E+00, ...\n 0.8059797829185990E+00, ...\n -0.8059797829185988E+00 ];\n ys = [ ...\n -0.9258200997725515E+00, ...\n -0.1073032005210112E-16, ...\n 0.9258200997725515E+00, ...\n 0.1241105822293750E-15, ...\n -0.3805544332083157E+00, ...\n -0.3805544332083157E+00, ...\n 0.3805544332083157E+00, ...\n 0.3805544332083157E+00, ...\n -0.8059797829185988E+00, ...\n -0.8059797829185990E+00, ...\n 0.8059797829185988E+00, ...\n 0.8059797829185990E+00 ];\n ws = [ ...\n 0.1711023816204485E+00, ...\n 0.1711023816204485E+00, ...\n 0.1711023816204485E+00, ...\n 0.1711023816204485E+00, ...\n 0.3681147816131979E+00, ...\n 0.3681147816131979E+00, ...\n 0.3681147816131979E+00, ...\n 0.3681147816131979E+00, ...\n 0.1678896179529011E+00, ...\n 0.1678896179529011E+00, ...\n 0.1678896179529011E+00, ...\n 0.1678896179529011E+00 ];\n\n x(1,1:n) = xs(1:n);\n x(2,1:n) = ys(1:n);\n w(1:n) = ws(1:n);\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/square_symq_rule/rule06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6428272675162561}} {"text": "% This is a 2D separable low pass filter for constructing Gaussian and \n% Laplacian pyramids, built from a 1D 5-tap low pass filter.\n%\n% tom.mertens@gmail.com, August 2007\n% sam.hasinoff@gmail.com, March 2011 [imfilter faster with 2D filter]\n%\n\nfunction f = pyramid_filter()\nf = [.05, .25, .4, .25, .05]; % original [Burt and Adelson, 1983]\n%f = [.0625, .25, .375, .25, .0625]; % binom-5\nf = f'*f;\nend", "meta": {"author": "mahmoudnafifi", "repo": "Exposure_Correction", "sha": "01300c3ff186123d405141202f8201ebd59965fa", "save_path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction", "path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction/Exposure_Correction-01300c3ff186123d405141202f8201ebd59965fa/exFusion/pyramid_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6428272529260424}} {"text": "function gray = grayFilter(img, varargin)\n%GRAYFILTER Compute configuration map of a binary image\n%\n% GRAY = grayFilter(IMG);\n% Returns a gray-scale image, with size dim(IMG)-1, containing values of\n% the 2x2 configuration of the original binary image.\n%\n% Example:\n% img = [0 0 0 0 0;0 1 1 0 0;0 1 1 1 0;0 0 0 0 0];\n% grayFilter(img)\n% ans =\n% 8 12 4 0\n% 10 15 13 4\n% 2 3 3 1\n%\n% ---------\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 22/10/2004.\n%\n\n% HISTORY \n% 03/11/2004 : add 3x3 2D case.\n\n\n% pre-processing\nimg = img~=0;\ndim = size(img);\nnd = length(dim);\n\n% size of neighborhood to consider\nnu=1;\n\n% extract input parameters\nif ~isempty(varargin)\n var = varargin{1};\n if length(var)==1\n nu = var;\n else\n coef = var;\n % find size of filter from length of coefficients.\n nu = power(log(length(coef))/log(2), 1/nd);\n end \nend\n \nif length(dim)==2\n % 2 dimensions\n NY = dim(1)-nu;\n NX = dim(2)-nu;\n\n if nu==1\n gray=1*img(1:NY, 1:NX) + ...\n 2*img(1:NY, 2:NX+1) + ...\n 4*img(2:NY+1, 1:NX) + ...\n 8*img(2:NY+1, 2:NX+1) ;\n elseif nu==2\n gray = 1*img(1:NY, 1:NX) + ...\n 2*img(1:NY, 2:NX+1) + ...\n 4*img(1:NY, 3:NX+2) + ...\n 8*img(2:NY+1, 1:NX) + ...\n 16*img(2:NY+1, 2:NX+1) + ...\n 32*img(2:NY+1, 3:NX+2) + ...\n 64*img(3:NY+2, 1:NX) + ...\n 128*img(3:NY+2, 2:NX+1) + ...\n 256*img(3:NY+2, 3:NX+2) ; \n end\n \nelse\n % 3 dimensions \n NY = dim(1)-nu;\n NX = dim(2)-nu;\n NZ = dim(3)-nu;\n \n gray= img(1:NY, 1:NX, 1:NZ) + ...\n 2*img(1:NY, 2:NX+1, 1:NZ) + ...\n 4*img(2:NY+1, 1:NX, 1:NZ) + ...\n 8*img(2:NY+1, 2:NX+1, 1:NZ) + ...\n 16*img(1:NY, 1:NX, 2:NZ+1) + ...\n 32*img(1:NY, 2:NX+1, 2:NZ+1) + ...\n 64*img(2:NY+1, 1:NX, 2:NZ+1) + ...\n 128*img(2:NY+1, 2:NX+1, 2:NZ+1);\nend\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imFilters/grayFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6427202164784657}} {"text": "classdef IMOP6 < PROBLEM\n% \n% Benchmark MOP with irregular Pareto front\n% a1 --- 0.05 --- Parameter a1\n% a2 --- 10 --- Parameter a2\n% K --- 5 --- Parameter K\n\n%------------------------------- Reference --------------------------------\n% Y. Tian, R. Cheng, X. Zhang, M. Li, and Y. Jin, Diversity assessment of\n% multi-objective evolutionary algorithms: Performance metric and benchmark\n% problems, IEEE Computational Intelligence Magazine, 2019, 14(3): 61-74.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties(Access = private)\n a1 = 0.05; % Parameter a1\n a2 = 10; % Parameter a2\n K = 5; % Parameter K\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n [obj.a1,obj.a2,obj.K] = obj.ParameterSet(0.05,10,5);\n obj.M = 3;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n y1 = mean(PopDec(:,1:2:obj.K),2).^obj.a1;\n y2 = mean(PopDec(:,2:2:obj.K),2).^obj.a2;\n g = sum((PopDec(:,obj.K+1:end)-0.5).^2,2);\n r = max(0,min(sin(3*pi*y1).^2,sin(3*pi*y2).^2)-0.05);\n PopObj(:,1) = (1+g).*y1 + ceil(r);\n PopObj(:,2) = (1+g).*y2 + ceil(r);\n PopObj(:,3) = (0.5+g).*(2-y1-y2) + ceil(r);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n [x,y] = meshgrid(linspace(0,1,ceil(sqrt(N))));\n R = [x(:),y(:)];\n r = max(0,min(sin(3*pi*R(:,1)).^2,sin(3*pi*R(:,2)).^2)-0.05);\n R(:,3) = 1 - sum(R,2)/2;\n R = R + repmat(ceil(r),1,3);\n R = R(NDSort(R,1)==1,:);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n [x,y] = meshgrid(linspace(0,1,50));\n z = 1 - x/2 - y/2;\n R = [x(:),y(:),z(:)];\n r = max(0,min(sin(3*pi*R(:,1)).^2,sin(3*pi*R(:,2)).^2)-0.05);\n R = R + repmat(ceil(r),1,3);\n fes = NDSort(R,1) == 1;\n z(reshape(~fes,size(z))) = nan;\n R = {x,y,z};\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/IMOP/IMOP6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6427202134201556}} {"text": "function chebcoeffs = chebvals2chebcoeffs(chebvals, kind)\n%CHEBVALS2CHEBCOEFFS Convert Chebyshev values to coefficients.\n% \tCHEBCOEFFS = CHEBVALS2CHEBCOEFFS(CHEBVALS), converts the column vector\n% CHEBVALS of values on a second-kind Chebyshev grid (i.e, F(CHEBPTS(N)))\n% to a vector CHEBCOEFFS of the Chebyshev coefficients of the series\n% F(X) = C_CHEB(1)*T0(X) + ... + C_CHEB(N)*T{N-1}(X).\n%\n% \tCHEBVALS2CHEBCOEFFS(CHEBVALS, 1) is similar, but assumes the entries in\n% \tCHEBVALS come from evaluating on a first-kind Chebyshev grid, i.e.,\n% F(CHEBPTS(N,1))).\n% \n% See also CHEBTECH2.VALS2COEFFS, CHEBPTS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Default to second-kind points\nif ( nargin == 1 )\n kind = 2;\nend\n\nif ( kind == 1 )\n % This command is a wrapper for chebtech2/vals2coeffs.\n chebcoeffs = chebtech1.vals2coeffs(chebvals);\nelseif ( kind == 2 )\n % This command is a wrapper for chebtech1/vals2coeffs.\n chebcoeffs = chebtech2.vals2coeffs(chebvals);\nelse\n error('CHEBFUN:chebvals2chebcoeffs:kind', ...\n 'Invalid Chebyshev kind. Must be 1 or 2.')\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/chebvals2chebcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6427202073606366}} {"text": "% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz\n\n\n%GEOMETRICAL PARAMETERS\n\nclear;\n\n%Length from the bearing to the hinge\nl0 = 27.5;\n\n%Length of the vertical wall that supports the hinge\nh0 = 6.5;\n\n%Lenght of the vertical support of the bearing\nhb = 4.0;\n\n%Bearing radius\nbr = 1.1;\n\n%Array of different max and min positions of the bearing\nh1a = [6.5, 7.1, 7.7, 8.3];\nh2a = [20.5, 20.5, 20.5, 20.5];\n\n%Number of cycles per cam turn (1 to 3).\nnc = 1;\n\n%Minimum radius of the camshaft\nrmin = 5;\n\n\n%BREATHING CYCLE PARAMETERS\n\n%Duration of the inhale cycle / duration of the whole cycle\nlambda1 = 0.500;\nlambda2 = 0.060;\n\n%Soft transition between inhale and exhale cycles\ndpsi21 = 0.12;\ndpsi12 = 0.15;\n\n%Adjust parameters of the inhale curve\nga1 = pi;\ngb1 = 1.2;\nff1 = 20;\nsp1 = 1;\n\n%Adjust parametes of the exhale curve\nga2 = 9;\ngb2 = .5;\nff2 = 20;\n\n\n%GENERATION OF THE CURVES AND THE CAMSHAFT\n\n%Generation of the geometry\n\nl = sqrt(l0^2+hb^2);\n\n\nfor i = 1:numel(h1a);\n \n ymin(i) = h1a(i);\n ymax(i) = h2a(i);\n \n alphamin(i) = acos((h0 - h1a(i)) / l);\n alphamax(i) = acos((h0 - h2a(i)) / l);\n \n xmin(i) = l*sin(alphamin(i)); \n xmax(i) = l*sin(alphamax(i));\n \n d(i) = sqrt((xmin(i)-xmax(i))^2 + (ymin(i)-ymax(i))^2);\n \n alphatan(i) = (alphamin(i) + alphamax(i)) / 2;\n \n xtan(i) = l*sin(alphatan(i)); \n ytan(i) = h0 - l*cos(alphatan(i));\n \n xsup(i) = xtan(i) + (d(i)/2)*cos(alphatan(i));\n xinf(i) = xtan(i) - (d(i)/2)*cos(alphatan(i));\n \n ysup(i) = ytan(i) + (d(i)/2)*sin(alphatan(i));\n yinf(i) = ytan(i) - (d(i)/2)*sin(alphatan(i));\n \n xcam(i) = xtan(i) + (d(i)/2 + rmin + br)*cos(alphatan(i));\n ycam(i) = ytan(i) + (d(i)/2 + rmin + br)*sin(alphatan(i));\n \nend;\n\n\n%Time increment\ndt = 0.01;\n\n%time coordinate during the whole cycle\ntheta = 0:dt:2*pi;\n\n%Generation of the soft transition between inhale and exhale curves\npsi1 = [];\npsi2 = [];\n\nfor i = 1:numel(theta);\n \n if theta(i) < (lambda2-dpsi21/2)*2*pi;\n psi1(i) = 0;\n \n elseif theta(i) < (lambda2+dpsi21/2)*2*pi;\n psi1(i) = 0.5 + 0.5*cos((theta(i)-(lambda2+dpsi21/2)*2*pi)/(2*dpsi21));\n \n else theta(i) < (lambda1-dpsi12/2)*2*pi;\n psi1(i) = 1;\n \n end;\n \n psi2(i) = 1 - psi1(i);\n \nend; \n\n\n%Generation of the complete breathing cycle rho(theta)\n\nrho = [];\nrho1 = [];\nrho2 = [];\nrho2next = [];\n\nrhomin = 1000;\nrhomax = 0;\n\nfor i = 1:numel(theta);\n \n %Inhale curve\n rho1(i) = ff1*normpdf(sp1*theta(i), ga1, gb1);\n rho1next(i) = ff1*normpdf(sp1*theta(i)+sp1*2*pi, ga1, gb1);\n \n %Exhale curve\n rho2(i) = ff2*gampdf(theta(i), ga2, gb2);\n rho2next(i) = ff2*gampdf(theta(i)+2*pi, ga2, gb2);\n \n \n rho(i) = max(rho1(i), rho1next(i));\n \n \n %Capturing min and max in order to generate the normalized curve\n if rho(i) > rhomax\n rhomax = rho(i);\n end;\n \n if rho(i) < rhomin\n rhomin = rho(i);\n end;\n\nend;\n\n\n%Generation of a normalised curve and camshaft\n\nrhonorm = [];\nrhocam = [];\n\nfor i = 1:numel(theta);\n \n rhonorm(i) = (rho(i)-rhomin)/(rhomax-rhomin);\n \n for n = 1:numel(d)\n \n rhocam(n,i) = rmin + rhonorm(i)*d(n);\n \n end;\n \nend;\n\n\n%Generation of the first derivate of the camshaft geometry to analize and\n%validate the design\n\ndrho = [];\ndrhonorm = [];\ndrhocam = [];\n\na = rmin;\nb = 1/dt;\n\nfor i = 1 : numel(rho)-1;\n \n drho(i) = b*(rho(i+1)-rho(i));\n drhonorm(i) = b*(rhonorm(i+1)-rhonorm(i));\n drhocam(i) = b*(rhocam(i+1)-rhocam(i)) + a;\n \nend;\n\ndrho(numel(rho)) = b*(rho(1)-rho(numel(rho)));\ndrhonorm(numel(rhonorm)) = b*(rhonorm(1)-rhonorm(numel(rhonorm)));\ndrhocam(numel(rhocam)) = b*(rhocam(1)-rhocam(numel(rhocam))) + a;\n\n\n%X and Y coordinates during two cycles (for 2-cycle camshaft plot)\n\ntheta2 = [theta/2, (2*pi+theta)/2];\n\nrhocam2 = [rhocam, rhocam];\ndrhocam2 = [drho, drho];\n\n\n%X and Y coordinates during three cycles (for 3-cycle camshaft plot)\n\ntheta3 = [theta/3, (2*pi+theta)/3, (4*pi+theta)/3];\n\nrhocam3 = [rhocam, rhocam, rhocam];\ndrhocam3 = [drho, drho, drho];\n\n\n\n%GENERATION OF THE PLOTS\n\n%Trying to print it out in real size (FAIL)\n%set(gcf,'PaperUnits','centimeters'); \n%set(gcf,'PaperSize',[42 29.7]);\n\n\nfpos = figure('Name', 'Dimensions', 'Units', 'centimeters', 'NumberTitle', 'off');\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 28, 20]);\nfpos = gcf;\nhold on\n\nxlim([-5 35]);\nylim([0 30]);\n\nfor i = 1:numel(xmin)\n \n plot([0, xmin(i)], [h0, ymin(i)], '-x') \n plot([0, xmax(i)], [h0, ymax(i)], '-x')\n \n plot([0, xtan(i)], [h0, ytan(i)], '--xb')\n \n plot([xsup(i), xinf(i)], [ysup(i), yinf(i)], '--xr')\n scatter(xcam(i), ycam(i))\n\nend;\n\nhold off\n\n\n\n\n%Plot of the breathing cycle interpolation by curves\n\nfcycle = figure('Name', 'Breath Cycle curves', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, psi1, '-k')\nplot(theta, psi2, '-k')\nplot(theta, rho1, '-g')\nplot(theta, rho1next, '-g')\nplot(theta, rho2, '-g')\nplot(theta, rho2next, '-g')\n%plot(theta, drho, '-r')\nplot(theta, rho, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of the normalized breathing cycle and first derivate\n\n\nfnorm = figure('Name', 'Normalized Breath Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\n%plot(theta, drhonorm, '-r')\nplot(theta, rhonorm, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 1-cycle camshaft\n\nfor n = 1:numel(d)\n\n fcam1 = figure('Name', '1-Cycle Camshaft', 'Units', 'centimeters', 'NumberTitle', 'off');\n %hold on\n \n %polarplot(theta, drhocam, '-r')\n polar(theta, rhocam(n,:), '-b')\n\n \n %rlim([0 25]);\n hold off\n\n set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n fcam3 = gcf;\n \nend\n\n\n% %Plot of a 2-cycle camshaft\n% \n% fcam2 = figure('Name', '2-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta, drhocam2, '-r')\n% polar(theta2, rhocam2, '-b')\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n% \n% \n% %Plot of a 3-cycle camshaft\n% \n% fcam3 = figure('Name', '3-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta,drhocam3)\n% polar(theta3, rhocam3)\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n\n% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz", "meta": {"author": "ProtofyTeam", "repo": "OxyGEN", "sha": "8a2870695e01928c07af2cc73ed86e5e53d8f726", "save_path": "github-repos/MATLAB/ProtofyTeam-OxyGEN", "path": "github-repos/MATLAB/ProtofyTeam-OxyGEN/OxyGEN-8a2870695e01928c07af2cc73ed86e5e53d8f726/Matlab Files/V8/Respirador_V6_1_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6427077834261713}} {"text": "function value = p05_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P05_EXACT returns the exact integral for problem 05.\n%\n% Discussion:\n%\n% The exact value is given only for DIM_NUM = 1, 2, 3, 4 or 5.\n% For other cases, the value R8_HUGE is returned instead.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral,\n% or R8_HUGE if the exact value is not known.\n%\n if ( dim_num == 1 )\n\n value = log ( 3.0 );\n\n elseif ( dim_num == 2 )\n\n value = 5.0 * log ( 5.0 ) - 6.0 * log ( 3.0 );\n\n elseif ( dim_num == 3 )\n\n value = 0.5 * ( 49.0 * log ( 7.0 ) ...\n - 75.0 * log ( 5.0 ) + 27.0 * log ( 3.0 ) );\n\n elseif ( dim_num == 4 )\n\n value = 225.0 * log ( 3.0 ) + 125.0 * log ( 5.0 ) ...\n - 686.0 * log ( 7.0 ) / 3.0;\n\n elseif ( dim_num == 5 )\n\n value = ( ...\n - 65205.0 * log ( 3.0 ) ...\n - 6250.0 * log ( 5.0 ) ...\n + 24010.0 * log ( 7.0 ) ...\n + 14641.0 * log ( 11.0 ) ) / 24.0;\n\n else\n\n value = r8_huge ( );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p05_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6427077764816359}} {"text": "function [yz, dy] = pzextr1(iest, xest, yest)\n% pzextr.m uses extrapolation to evaluate nv functions at x=0 by fitting a\n% polynomial to a sequence of estimates with progressively smaller values x= xest(1..np), and\n% corresponding function vectors yest(1..nv,1..np). This call is number iest in the sequence\n% of calls, see also bsstep1.m and pzextr.m\n% \n% output : the extrapolated function values, yz(1..nv,1..np) and their estimated error, dy(1..nv,1..np).\n\n\n% D Vangheluwe 8 mrt 2005\n\nglobal x_bulirsch_stoer d_bulirsch_stoer\n\n[nv np] = size(yest);\n\nif np > 1\n x_bulirsch_stoer(iest,:) = xest;\n% save current independent variable\n yz = yest;\n dy = yz;\n\n% x_bulirsch_stoer\n% d_bulirsch_stoer\n\n if iest == 1\n% store first estimate in first column\n d_bulirsch_stoer(:,:,1) = yest;\n else\n c = yest;\n for k1 = 1:iest-1\n delta = 1 ./ (x_bulirsch_stoer(iest-k1,:) - xest);\n f1 = xest .* delta;\n f2 = x_bulirsch_stoer(iest-k1,:) .* delta; \n q = d_bulirsch_stoer(:,:,k1);\n d_bulirsch_stoer(:,:,k1) = dy;\n deltay = c - q;\n dy = repmat(f1, nv, 1) .* deltay;\n c = repmat(f2, nv, 1) .* deltay;\n yz = yz + dy;\n end\n d_bulirsch_stoer(:,:,iest) = dy;\n end\n\nelse %np == 1\n\n x_bulirsch_stoer(iest) = xest';\n% save current independent variable\n yz = yest;\n dy = yz;\n\n% x_bulirsch_stoer\n% d_bulirsch_stoer\n if iest == 1\n% store first estimate in first column\n d_bulirsch_stoer(:,1) = yest;\n else\n c = yest;\n for k1 = 1:iest-1\n delta = 1 ./ (x_bulirsch_stoer(iest-k1) - xest);\n f1 = xest .* delta;\n f2 = x_bulirsch_stoer(iest-k1) .* delta; \n q = d_bulirsch_stoer(:,k1);\n d_bulirsch_stoer(:,k1) = dy;\n deltay = c - q;\n dy = f1 .* deltay;\n c = f2 .* deltay;\n yz = yz + dy;\n end\n d_bulirsch_stoer(:,iest) = dy;\n end\n\nend %np > 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/8491-cmbaccur/pzextr1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118068790618, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6426029684536289}} {"text": "function tf = ispolycw_N(x, y)\n%ISPOLYCW_N True if polygon vertices are in clockwise order\n%\n% TF = ISPOLYCW(X, Y) returns true if the polygonal contour vertices \n% represented by X and Y are ordered in the clockwise direction. X and Y\n% are numeric vectors with the same number of elements.\n%\n% Alternatively, X and Y can contain multiple contours, either in\n% NaN-separated vector form or in cell array form. In that case,\n% ISPOLYCW returns a logical array containing one true or false value\n% per contour.\n%\n% ISPOLYCW always returns true for polygonal contours containing two or\n% fewer vertices.\n%\n% Vertex ordering is not well defined for self-intersecting polygonal\n% contours. For such contours, ISPOLYCW returns a result based on the\n% order or vertices immediately before and after the left-most of the \n% lowest vertices. In other words, of the vertices with the lowest Y\n% value, find the vertex with the lowest X value. For a few special\n% cases of self-intersecting contours, the vertex ordering cannot be\n% determined using only the left-most of the lowest vertices; for these\n% cases, ISPOLYCW uses a signed area test to determine the ordering.\n%\n% Class Support\n% -------------\n% X and Y may be any numeric class.\n%\n% Example\n% -------\n% Orientation of a square:\n%\n% x = [0 1 1 0 0];\n% y = [0 0 1 1 0];\n% ispolycw(x, y) % Returns 0\n% ispolycw(fliplr(x), fliplr(y)) % Returns 1\n%\n% See also POLY2CW, POLY2CCW, POLYBOOL.\n\n% Copyright 2004-2009 The MathWorks, Inc.\n% $Revision: 1.1.4.3 $ $Date: 2009/08/11 15:44:28 $\n\nif isempty(x)\n tf = true;\n return;\nend\n\nif ~iscell(x)\n checkxy_N(x, y, mfilename, 'X', 'Y', 1, 2)\n is_row = (size(x,1) == 1);\n [x, y] = polysplit_N(x, y);\n if is_row\n x = x';\n y = y';\n end\nend\n\ntf = false(size(x));\nfor k = 1:numel(x)\n tf(k) = isContourClockwise(x{k}, y{k});\nend\n\n%----------------------------------------------------------------------\nfunction tf = isContourClockwise(x, y)\n\nif numel(x) <= 1\n tf = true;\n return;\nend\n\nis_closed = (x(1) == x(end)) && (y(1) == y(end));\nif is_closed\n x(end) = [];\n y(end) = [];\nend\n\n[x, y] = removeDuplicates(x, y);\nnum_vertices = numel(x);\nif num_vertices <= 2\n tf = true;\n return;\nend\n\nidx = findExtremeVertices(x, y);\n\nif numel(idx) > 1\n % The same extreme vertex appears multiple, nonsuccessive times in\n % the vertex list. Use signed area test.\n tf = signedArea(x, y) <= 0;\n return;\nend\n\n% Find the three vertices we are interested in: the left-most of the\n% lowest vertices, as well as the ones immediately before and after it.\np = mod((idx - 1) + [-1, 0, 1], num_vertices) + 1;\nxx = x(p);\nyy = y(p);\n\nif ~isfloat(xx)\n xx = double(xx);\nend\nif ~isfloat(yy)\n yy = double(yy);\nend\n\nux = xx(2) - xx(1);\nuy = yy(2) - yy(1);\n\nvx = xx(3) - xx(2);\nvy = yy(3) - yy(2);\n\na = ux*vy;\nb = uy*vx;\nif a == b\n % The left-most lowest vertex is the end-point of a kind of linear\n % \"spur.\" The contour doubles back on itself, such as in this case:\n % x = [0 1 1 0 0 -1 0];\n % y = [0 0 1 1 0 -1 0];\n % The left-most lowest vertex is (-1,-1), but we since this vertex\n % is the end-point of a spur, we can't tell the direction from it.\n % Use the signed polygon test.\n tf = signedArea(x, y) <= 0;\nelse\n tf = a < b;\nend\n\n%----------------------------------------------------------------------\nfunction [xout, yout] = removeDuplicates(x, y)\nnum_vertices = numel(x);\nk1 = [2:num_vertices 1];\nk2 = 1:num_vertices;\ndups = (x(k1) == x(k2)) & (y(k1) == y(k2));\nxout = x;\nyout = y;\nxout(dups) = [];\nyout(dups) = [];\n\n%----------------------------------------------------------------------\nfunction idx = findExtremeVertices(x, y)\n% Return the indices of all the left-most lowest vertices in (x,y).\n\n% Find the vertices with the minimum y.\nidx = find(y == min(y));\n\nx_subset = x(idx);\nidx2 = (x_subset == min(x_subset));\n\nidx = idx(idx2);\n\n%----------------------------------------------------------------------\nfunction a = signedArea(x, y)\n% a = signedArea(x,y) returns twice the signed area of the polygonal\n% contour represented by vectors x and y. Assumes (x,y) is NOT closed.\n\n% Reference: \n% http://geometryalgorithms.com/Archive/algorithm_0101/algorithm_0101.htm\n\nx = x - mean(x);\nn = numel(x);\nif n <= 2\n a = 0;\nelse\n i = [2:n 1];\n j = [3:n 1 2];\n k = (1:n);\n a = sum(x(i) .* (y(j) - y(k)));\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/yinda_map/ispolycw_N.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6426029627626143}} {"text": "function v=shear_bulk2poisson(mu,k)\n\n\nv=((3.*k)-(2.*mu))./((6.*k)+(2.*mu));\n\n\n\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/shear_bulk2poisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6426029608700321}} {"text": "function [y,t,optw,W,C,confb95,yb] = sskernel(x,tin,W)\n% [y,t,optw,W,C,confb95,yb] = sskernel(x,t,W)\n%\n% Function `sskernel' returns an optimized kernel density estimate \n% using a Gauss kernel function.\n%\n% Examples:\n% >> x = 0.5-0.5*log(rand(1,1e3)); t = linspace(0,3,1000);\n% >> [y,t,optw] = sskernel(x,t);\n% This example produces a vector of kernel density estimates, y, at points\n% specified in a vector t, using an optimized bandwidth, optw (a standard \n% deviation of a normal density function).\n% \n% >> sskernel(x);\n% By calling the function without output arguments, the estimated density \n% is displayed along with 95% bootstrap confidence intervals.\n%\n% Input arguments:\n% x: Sample data vector. \n% tin (optinal):\n% Points at which estimation are computed. Please use fine resolution\n% to obtain a correct optimal bandwidth.\n% W (optinal): \n% A vector of kernel bandwidths. \n% If W is provided, the optimal bandwidth is selected from the \n% elements of W.\n% * Do not search bandwidths smaller than a sampling resolution of data.\n% If W is not provided, the program searches the optimal bandwidth\n% using a golden section search method. \n%\n% Output arguments:\n% y: Estimated density\n% t: Points at which estimation was computed.\n% The same as tin if tin is provided. \n% (If the sampling resolution of tin is smaller than the sampling \n% resolution of the data, x, the estimation was done at smaller\n% number of points than t. The results, t and y, are obtained by \n% interpolating the low resolution sampling points.)\n% optw: Optimal kernel bandwidth.\n% W: Kernel bandwidths examined. \n% C: Cost functions of W.\n% conf95:\n% Bootstrap confidence intervals.\n% yb: Booststrap samples.\n%\n% \n% Usage:\n% >> [y,t,optw] = sskernel(x);\n% When t is not given in the input arguments, i.e., the output argument t \n% is generated automatically.\n%\n% >> W = linspace(0.01,1,20);\n% >> [y,t,optw] = sskernel(x,t,W);\n% The optimal bandwidth is selected from the elements of W.\n%\n% >> [y,t,optw] = sskernel(x,t,0.1);\n% If the density estimate with a given bandwidth, simply put a scalar value\n% as W. The computation is faster than the built-in function, ksdensity.\n%\n% >> [y,t,optw,confb95,yb] = sskernel(x);\n% This additionally computes 95% bootstrap confidence intervals, confb95.\n% The bootstrap samples are provided as yb.\n% \n%\n% Optimization principle:\n% The optimal bandwidth is obtained as a minimizer of the formula, \n% sum_{i,j} \\int k(x - x_i) k(x - x_j) dx - 2 sum_{i~=j} k(x_i - x_j), \n% where k(x) is the kernel function, according to\n%\n% Hideaki Shimazaki and Shigeru Shinomoto\n% Kernel Bandwidth Optimization in Spike Rate Estimation \n% Journal of Computational Neuroscience 2010\n% http://dx.doi.org/10.1007/s10827-009-0180-4\n%\n% The above optimization is based on a principle of minimizing \n% expected L2 loss function between the kernel estimate and an unknown \n% underlying density function. An assumption is merely that samples \n% are drawn from the density independently each other. \n%\n% For more information, please visit \n% http://2000.jukuin.keio.ac.jp/shimazaki/res/kernel.html\n%\n% See also SSVKERNEL, SSHIST\n% \n% Bug fix\n% 131004 fixed a problem for large values\n%\n% Hideaki Shimazaki \n% http://2000.jukuin.keio.ac.jp/shimazaki\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Parameters Settings\nx = reshape(x,1,numel(x));\n\nif nargin == 1\n T = max(x) - min(x);\n [mbuf,nbuf,dt_samp] = find( sort(diff(sort(x))),1,'first');\n tin = linspace(min(x),max(x), min(ceil(T/dt_samp),1e3));\n t = tin;\n x_ab = x( logical((x >= min(tin)) .*(x <= max(tin))) ) ;\nelse\n T = max(tin) - min(tin); \n x_ab = x( logical((x >= min(tin)) .*(x <= max(tin))) ) ;\n [mbuf,nbuf,dt_samp] = find( sort(diff(sort(x_ab))),1,'first');\n\n if dt_samp > min(diff(tin))\n t = linspace(min(tin),max(tin), min(ceil(T/dt_samp),1e3));\n else\n t = tin;\n end\nend\n\ndt = min(diff(t));\n\n% Create a finest histogram\ny_hist = histc(x_ab,t-dt/2);\nL = length(y_hist);\nN = sum(y_hist);\ny_hist = y_hist/N/dt; %density\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Compute a Cost Function\n\nif nargin >= 3\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Global search\nC = zeros(1,length(W));\nC_min = Inf;\n\nfor k = 1: length(W)\n\tw = W(k); \n [C(k) yh] = CostFunction(y_hist,N,w,dt);\n \n if C(k) < C_min\n C_min = C(k);\n optw = w;\n y = yh;\n end\nend\n\nelse\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Golden section search on a log-exp scale\n% Initialize\nWmin = 2*dt; Wmax = 1*(max(x) - min(x));\n\ntol = 10^-5; \nphi = (sqrt(5) + 1)/2; %golden ratio\n%logexp = @(x) log(1+exp(x));\n%ilogexp = @(x) log(exp(x)-1);\n\n%a = Wmin; b = Wmax;\na = ilogexp(Wmin); b = ilogexp(Wmax);\n\nc1 = (phi-1)*a + (2-phi)*b;\nc2 = (2-phi)*a + (phi-1)*b;\n\nf1 = CostFunction(y_hist,N,logexp(c1),dt);\nf2 = CostFunction(y_hist,N,logexp(c2),dt);\n\nk = 1;\nwhile abs(b-a) > tol*(abs(c1)+abs(c2)) && k <= 20\n\tif (f1 < f2) \n b = c2;\n c2 = c1;\n\n c1 = (phi - 1)*a + (2 - phi)*b;\n \n f2 = f1;\n [f1 yh1] = CostFunction(y_hist,N,logexp(c1),dt);\n \n W(k) = logexp(c1);\n C(k) = f1;\n optw = logexp(c1);\n y = yh1./sum(yh1.*dt); %make the final output a density\n else\n a = c1;\n c1 = c2;\n \n c2 = (2 - phi)*a + (phi - 1)*b;\n \n f1 = f2;\n [f2 yh2] = CostFunction(y_hist,N,logexp(c2),dt);\n \n W(k) = logexp(c2);\n C(k) = f2;\n optw = logexp(c2);\n y = yh2./sum(yh2.*dt);\n end\n \n k = k + 1;\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Bootstrap Confidence Intervals\nif nargout == 0 || nargout >= 6\n nbs = 1e3; %number of bootstrap samples\n yb = zeros(nbs,length(tin));\n\n for i = 1: nbs,\n %y_histb = poissrnd(y_hist*dt*N)/dt/N;\n \n idx = ceil(rand(1,N)*N);\n xb = x_ab(idx);\n y_histb = histc(xb,t-dt/2)/dt/N;\n \n yb_buf = fftkernel(y_histb,optw/dt);\n yb_buf = yb_buf / sum(yb_buf*dt);\n \n yb(i,:) = interp1(t,yb_buf,tin);\n end\n\n ybsort = sort(yb);\n y95b = ybsort(floor(0.05*nbs),:);\n y95u = ybsort(floor(0.95*nbs),:);\n \n confb95 = [y95b; y95u];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Return results\ny = interp1(t,y,tin);\nt = tin;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Display results\nif nargout == 0\n hold on;\n\n line([t; t],[y95b; y95u]...\n ,'Color',[7 7 7]/8,'LineWidth',1 );\n plot(t,y95b,'Color',[7 7 7]/9,'LineWidth',1);\n plot(t,y95u,'Color',[7 7 7]/9,'LineWidth',1);\n\n plot(t,y,'Color',[0.9 0.2 0.2],'LineWidth',2);\n\n grid on;\n ylabel('density');\n set(gca,'TickDir','out'); \nelse\n if nargin >= 4\n if strcmp(option,'Visible')\n hold on; \n \n if nargout >= 6\n line([t; t],[y95b; y95u]...\n ,'Color',[7 7 7]/8,'LineWidth',1 );\n plot(t,y95b,'Color',[7 7 7]/9,'LineWidth',1);\n plot(t,y95u,'Color',[7 7 7]/9,'LineWidth',1);\n end\n\n plot(t,y,'Color',[0.9 0.2 0.2],'LineWidth',1);\n\n grid on;\n ylabel('density');\n set(gca,'TickDir','out'); \n \n end\n end\nend\n\n\nfunction [C yh] = CostFunction(y_hist,N,w,dt)\nyh = fftkernel(y_hist,w/dt); %density\n\n%formula for density\nC = sum(yh.^2)*dt - 2* sum(yh.*y_hist)*dt...\n + 2*1/sqrt(2*pi)/w/N; \nC = C * N* N;\n\n%formula for rate\n%C = dt*sum( yh.^2 - 2*yh.*y_hist + 2/sqrt(2*pi)/w*y_hist );\n\n \nfunction y = fftkernel(x,w)\n% y = fftkernel(x,w)\n%\n% Function `fftkernel' applies the Gauss kernel smoother to \n% an input signal using FFT algorithm.\n%\n% Input argument\n% x: Sample signal vector. \n% w: \tKernel bandwidth (the standard deviation) in unit of \n% the sampling resolution of x. \n%\n% Output argument\n% y: \tSmoothed signal.\n%\n% MAY 5/23, 2012 Author Hideaki Shimazaki\n% RIKEN Brain Science Insitute\n% http://2000.jukuin.keio.ac.jp/shimazaki\n\nL = length(x);\nLmax = max(1:L+3*w);\nn = 2^(nextpow2(Lmax));\n\nX = fft(x,n);\n\nf = (0:n-1)/n;\nf = [-f(1:n/2+1) f(n/2:-1:2)];\n\nK = exp(-0.5*(w*2*pi*f).^2);\n\ny = ifft(X.*K,n);\n\ny = y(1:L);\n\n\nfunction y = logexp(x) \nif x<1e2 \n y = log(1+exp(x));\nelse\n y = x;\nend\n\nfunction y = ilogexp(x)\n%ilogexp = @(x) log(exp(x)-1);\nif x<1e2\n y = log(exp(x)-1);\nelse\n y = x;\nend\n \n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/sskernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6426029518603644}} {"text": "%% Mesh Generator for Tecplot\n% Generating a 2D mesh for Tecplot for an axisymmetric diffuser.\n% by Manuel Diaz, 2012.09.15.\n\nclear all; close all; \n%% Parameters\nL0 = 0; L1 = 10 + L0; L2 = 6 + L1 + L0;\nH0 = 0; H1 = 0.5;\ntheta = deg2rad(5); % theta = 5 degress converted to radians\nH2 = H1 + L2*tan(theta);\n\n%% Number of elements of edges (ne)\nne_x1 = 25; ne_x2 = 40; ne_y = 40;\n\n%% End Points for the rectangular zones:\nZ1=[ L0,H1 ; L1,H1 ; L1,H0 ; L0,H0 ]; % Zone1\nZ2=[ L1,H1 ; L2,H2 ; L2,H0 ; L1,H0 ]; % Zone2\n\n%% Zone 1: \n% There are 4 edge lines, each having several edge points.\n% We use the Function \"Pinterpol\" to create the edge points for zone 1.\n\nE1 = Pinterpol(Z1(1,1),Z1(1,2),Z1(2,1),Z1(2,2),ne_x1);\nE2 = Pinterpol(Z1(4,1),Z1(4,2),Z1(3,1),Z1(3,2),ne_x1);\n\n% Now generating the mesh for Zone 1\nM1 = zeros(ne_x1+1,ne_y+1,2);\nfor i = 1:(ne_x1+1);\n V = Pinterpol(E1(i,1),E1(i,2),E2(i,1),E2(i,2),ne_y);\n M1(i,1:(ne_y+1),1:2) = V; % mesh1\nend\n\n%% Zone 2:\n% Similarly for zone 2\nE1 = Pinterpol(Z2(1,1),Z2(1,2),Z2(2,1),Z2(2,2),ne_x2);\nE2 = Pinterpol(Z2(4,1),Z2(4,2),Z2(3,1),Z2(3,2),ne_x2);\n\n% generating the mesh for Zone 2\nM2 = zeros(ne_x2+1,ne_y+1,2);\nfor i = 1:(ne_x2+1);\n V = Pinterpol(E1(i,1),E1(i,2),E2(i,1),E2(i,2),ne_y);\n M2(i,1:(ne_y+1),1:2) = V; % mesh2\nend\n\n%% To Tecplot\n% Writing Output data for Tecplot format:\n\nfile = fopen('mesh1.tec','w');\n% h1 gets the handel for the file \"mesh1.tec\".\n% 'w' specifies that it will be written.\n% similarly 'r' is for reading and 'a' for appending.\n\nfprintf(file, 'TITLE = \"Mesh from Matlab\"\\n');\nfprintf(file, 'VARIABLES = \"X\" \"Y\"\\n');\nfprintf(file, 'ZONE T = \"Inlet zone\"\\n');\nfprintf(file, 'I = %d, J = %d, K = 1, F = POINT\\n\\n', ne_x1+1,ne_y+1);\n\nfor j = 1:(ne_y+1)\n for i = 1:(ne_x1+1)\n fprintf(file, '%f\\t%f\\n', M1(i,j,1),M1(i,j,2));\n end\nend\n\nfprintf(file, 'ZONE T=\"Diffuser zone\"\\n');\nfprintf(file, 'I = %d, J=%d, k=1, F=POINT\\n\\n', ne_x2+1,ne_y+1);\n\nfor j = 1:(ne_y+1)\n for i = 1:(ne_x2+1)\n fprintf(file, '%f\\t%f\\n', M2(i,j,1),M2(i,j,2));\n end\nend\n\nfclose(file);", "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/Tecplot/diffuser_mesh2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6425851931364607}} {"text": "function [X,Y,Z]=cylinder2(x,y,z,r,N,o)\n%\n% [X,Y,Z]=cylinder2(x,y,z,r,N,o)\n%\n% Vectors x, y, z define the central line of cylindrical surface\n% and vector r defines the radius of cylindrical surface, and has\n% the same length as x, y, z.\n%\n% N is the number of points around the circumference. The default value\n% is N = 100.\n%\n% Matrix o defines ovality of the directrix (circle) of cylindrical\n% surface. Its elements take values between 0 and 1 and apply to the\n% primary and secondary axis of directrix. The defeault values are \n% o=ones(length(x),2).\n%\n% Matrices X, Y, Z define the cylindrical surface, surf(X,Y,Z) displays \n% the cylindrical surface.\n%\n% Example 1: Horn\n%\n% f=linspace(0,4*pi,100);\n% x=cos(f); y=sin(f); z=f; r=-1/99*([1:100]-1)+1;\n% [X,Y,Z]=cylinder2(x,y,z,r);\n%\n% Example 2: Pot\n% \n% x=[0 0 1 1 .5 .5]; y=[0 0 3 3 1.5 1.5];\n% z=[0 0 2 2 1 1]; r=[0 1 1.5 1.2 1 0];\n% [X,Y,Z]=cylinder2(x,y,z,r,6); view([-150 25])\n% \n% Example 3: Plumbing\n%\n% x=[0 0 0 0 0 0 1 1 1 1 1 1]; y=[0 .2 .2 1 1 .5 .5 1 1 .2 .2 0]; \n% z=[1 1 1 1 0 0 0 0 1 1 1 1]; r=[.2 .2 .1 .1 .1 .1 .1 .1 .1 .1 .2 .2];\n% o=[1 1 .5 .5 .5 1 1 .5 .5 .5 1 1; 1 1 1 1 1 .5 .5 1 1 1 1 1];\n% [X,Y,Z]=cylinder2(x,y,z,r,8,o);\n%\n%\n% Example 4: Triangle , closed central line\n%\n% f=linspace(0,2*pi,4); \n% x=cos(f-pi/6); y=sin(f-pi/6); z=zeros(4,1); r=0.2*ones(4,1);\n% [X,Y,Z]=cylinder3(x,y,z,r); view([0 90])\n%\n%\n%\n% Copyright (c) 2011, Version 2.2\n% Avni Pllana \n\nX=[]; Y=[]; Z=[];\n\nif nargin<5\n N=100;\nend\n\nx=x(:); y=y(:); z=z(:); r=r(:);\n\nnx=length(x);\nny=length(y);\nnz=length(z);\nnr=length(r);\n\nan=[nx ny nz nr];\nif ~ismember(diff(an),[0 0 0],'rows')\n disp(' ')\n disp('x, y, z, r must have the same length!')\nelse\n if nx<2\n disp(' ')\n disp('The length of x must be greater than 1!')\n else\n \n if nargin<6\n o=ones(nx,2); \n else\n [o1,o2]=size(o);\n if o2>o1\n o=o';\n end \n end\n \n C=[x y z]; \n D=diff(C);\n \n for i=1:nx-1 \n if norm(D(i,:))>0\n E(i,:)=D(i,:)/norm(D(i,:));\n else\n E(i,:)=[0 0 0];\n end\n \n end\n \n if norm(C(1,:)-C(nx,:))<1e-10 && norm(cross(E(1,:),E(nx-1,:)))>0\n Closed=1;\n nxx=nx+1;\n E=[E;E(1,:)];\n else\n Closed=0;\n nxx=nx; \n end\n \n f=linspace(0,2*pi,N+1);\n for j=1:N+1\n xcc(j)=cos(f(j));\n ycc(j)=sin(f(j));\n zcc(j)=0;\n end\n \n for i=1:nx\n \n if i==1\n \n if ~Closed\n \n d=[];\n k=i;\n\n while k3*pi/4)\n alf=0;\n end\n \n end \n \n else\n \n if ismember(i,d)\n V=Vp;\n alf=0;\n else\n d=[];\n k=i;\n\n while k0\n ang=-ang;\n end \n\n A=[cos(ang) sin(ang); -sin(ang) cos(ang)];\n xy=A*[xcc;ycc];\n xcc=xy(1,:);\n ycc=xy(2,:);\n %%%%%%%%%%%%\n Vpp=V;\n\n alf=acos(E(i,:)*E(i-1,:)'); \n\n if abs(alf>3*pi/4)\n alf=0;\n end\n end\n end \n \n end\n \n xc=o(i,1)*r(i)/cos(alf/2)*xcc;\n yc=o(i,2)*r(i)*ycc;\n xyz=[xc;yc;zcc];\n \n M=pinv(V);\n \n xyz1=M*xyz+repmat([x(i);y(i);z(i)],1,N+1);\n \n X(:,i)=xyz1(1,:)';\n Y(:,i)=xyz1(2,:)';\n Z(:,i)=xyz1(3,:)';\n \n end\n \n figure\n surf(X,Y,Z) \n shading interp\n camlight\n grid on\n axis equal\n \n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31253-cylinder/cylinder2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6425851896827243}} {"text": "% Data file PILZ3\n% Forced damped vibrations of a mechanical\n% system with one degree of freedom, contained\n% a reverse pendulum. \n s = 1; % degree of freedom\n L = '2.5*qt1^2 - 1/2*c*q1^2 - 3.9*cos(10*q1)'; % Lagrangian\n QN{1} = '-k*qt1 + 10*sin(p*t)'; % generalized non potential force\n Tend = 20; % upper bound of integration\n qj0 = 0.05; % initial coordinate\n qtj0 = 0; % initial velocity\n eps = 1e-10; % desirable accuracy\n np = 3; % number of parameters\n P{1} = 'c'; % spring stiffness\n P{2} = 'k'; % coefficient of damping\n P{3} = 'p'; % disturbance frequency", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/DATA Files/PILZ3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6425638114104059}} {"text": "function [sol,times,ocp] = bouncingball \n \n before_contact = ocl.Stage([], @before_contact_vars, @before_contact_ode, 'N', 3, 'd', 2);\n after_contact = ocl.Stage(1, @after_contact_vars, @after_contact_ode, ...\n @after_contact_cost, 'N', 5, 'd', 2);\n\n before_contact.setInitialStateBounds('s', 1);\n before_contact.setInitialStateBounds('v', 0);\n before_contact.setEndStateBounds('s', 0);\n \n after_contact.setEndStateBounds('s', 1);\n\n ocp = ocl.MultiStageProblem({before_contact, after_contact}, {@stage_transition});\n\n [sol,times] = ocp.solve(ocp.getInitialGuess());\n\n % stage 1\n figure; \n subplot(1,2,1)\n hold on; grid on;\n ocl.plot(times{1}.states, sol{1}.states.s)\n ocl.plot(times{1}.states, sol{1}.states.v)\n legend({'s','v'})\n xlabel('time [s]');\n ylim([-5 3])\n yticks(-5:3)\n title('stage 1')\n \n % stage 2\n subplot(1,2,2)\n hold on; grid on;\n ocl.plot(times{2}.states, sol{2}.states.s)\n ocl.plot(times{2}.states, sol{2}.states.v)\n ocl.stairs(times{2}.controls, sol{2}.controls.F)\n legend({'s','v','F'})\n xlabel('time [s]');\n ylim([-5 3])\n yticks(-5:3)\n title('stage 2')\n\nend\n\nfunction before_contact_vars(sh)\n sh.addState('s');\n sh.addState('v');\nend\n\nfunction before_contact_ode(sh,x,~,~,~) \n sh.setODE('s', x.v);\n sh.setODE('v', -10);\nend\n\nfunction after_contact_vars(sh)\n sh.addState('s');\n sh.addState('v');\n sh.addControl('F');\nend\n\nfunction after_contact_ode(sh,x,~,u,~)\n sh.setODE('s', x.v);\n sh.setODE('v', -10 + 10*u.F);\nend\n\nfunction after_contact_cost(ch,~,~,u,~)\n ch.add( u.F^2 );\nend\n\nfunction stage_transition(ch, x0, xF)\n % x0 current stage\n % xF previous stage\n ch.add(x0.s, '==', xF.s);\n ch.add(x0.v, '==', -xF.v/2);\nend\n\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/+examples/bouncingball.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6425538767842017}} {"text": "function [outR, outID] = makeBayesWeightedCorr1(Pr, bID, varargin)\n%function [outR, outID] = makeBayesWeightedCorr1(Pr, bID, preComputedQ (optional))\n\noutID = unique(bID);\nh = histc(bID, outID);\nif isempty(varargin)\n Q = makeQForWeightedCorr(h, size(Pr, 2));\nelse\n Q = varargin{1};\nend\n\noutR = zeros(length(outID), 1);\nfor i = 1:length(outR)\n outR(i) = makeWeightedCorr1(Q{h(i)}, reshape(Pr(bID == outID(i), :), [], 1));\nend\n\n \nend\n\nfunction out = makeWeightedCorr1(xy, w);\n%function out = makeWeightedCorr1(xy, w);\n\nmxy = sum(xy.*repmat(w, 1, 2)/sum(w));\ncovxy = sum(w.*(xy(:, 1) - mxy(1)).*(xy(:, 2) - mxy(2)))/sum(w);\ncovxx = sum(w.*(xy(:, 1) - mxy(1)).*(xy(:, 1) - mxy(1)))/sum(w);\ncovyy = sum(w.*(xy(:, 2) - mxy(2)).*(xy(:, 2) - mxy(2)))/sum(w);\nout = covxy/(sqrt(covyy*covxx));\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/utilities/makeBayesWeightedCorr1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6425431349650879}} {"text": "function [ xnew, ferr, q ] = roots_rc ( n, x, fx, q )\n\n%*****************************************************************************80\n%\n%% ROOTS_RC solves a system of nonlinear equations using reverse communication.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2013\n%\n% Author:\n%\n% Original FORTRAN77 version by Gaston Gonnet.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Gaston Gonnet,\n% On the Structure of Zero Finders,\n% BIT Numerical Mathematics,\n% Volume 17, Number 2, June 1977, pages 170-183.\n%\n% Parameters:\n%\n% Input, integer N, the number of equations.\n%\n% Input, real X(N). Before the first call, the user should\n% set X to an initial guess or estimate for the root. Thereafter, the input\n% value of X should be the output value of XNEW from the previous call.\n%\n% Input, real FX(N), the value of the function at XNEW.\n%\n% Workspace, real ( kind = 8 ) Q(2*N+2,N+2). Before the first call\n% for a given problem, the user must set Q(2*N+1,1) to 0.0.\n%\n% Output, real ( kind = 8 ) XNEW(N), a new point at which a function\n% value is requested.\n%\n% Output, real ( kind = 8 ) FERR, the function error, that is, the sum of\n% the absolute values of the most recently computed function vector.\n%\n% Workspace, real ( kind = 8 ) Q(2*N+2,N+2). \n%\n ferr = sum ( abs ( fx(1:n) ) );\n%\n% Initialization if Q(2*N+1,1) = 0.0.\n%\n if ( q(2*n+1,1) == 0.0 )\n\n for i = 1 : n\n for j = 1 : n + 1\n q(i,j) = 0.0;\n q(i+1,j) = 0.0;\n end\n q(i,i) = 100.0;\n q(i+n,i) = 1.0;\n end\n\n q(2*n+1,1:n) = 1.0E+30;\n q(2*n+2,1:n) = n;\n\n for i = 1 : n\n q(i+n,n+1) = x(i);\n end\n\n q(1:n,n+1) = fx(1:n);\n\n q(2*n+1,n+1) = ferr;\n q(2*n+2,n+1) = 0.0;\n damp = 0.99;\n\n else\n\n jsus = 1;\n for i = 2 : n + 1\n if ( 2 * n <= q(2*n+2,i) )\n q(2*n+1,i) = 1.0E+30;\n end\n if ( q(2*n+2,jsus) < floor ( ( n + 3 ) / 2 ) )\n jsus = i;\n end\n if ( ( n + 3 ) / 2 <= q(2*n+2,i) && q(2*n+1,jsus) < q(2*n+1,i) )\n jsus = i;\n end\n end\n\n for i = 1 : n\n q(i+n,jsus) = x(i);\n q(i,jsus) = fx(i);\n end\n\n q(2*n+1,jsus) = ferr;\n q(2*n+2,jsus) = 0;\n jsma = 1;\n damp = 0.0;\n\n for j = 1 : n + 1\n if ( 1.0E+30 / 10.0 < q(2*n+1,j) )\n damp = 0.99;\n end\n if ( q(2*n+1,j) < q(2*n+1,jsma) )\n jsma = j;\n end\n end\n\n if ( jsma ~= n + 1 )\n for i = 1 : 2 * n + 2\n t = q(i,jsma);\n q(i,jsma) = q(i,n+1);\n q(i,n+1) = t;\n end\n end\n\n end\n\n q(1:n,n+2) = q(1:n,n+1);\n%\n% Call the linear equation solver, which should not destroy the matrix\n% in Q(1:N,1:N), and should overwrite the solution into Q(1:N,N+2).\n%\n q(1:n,n+2) = q(1:n,1:n) \\ q(1:n,n+2);\n\n sump = sum ( q(1:n,n+2) );\n\n if ( abs ( 1.0 - sump ) <= 1.0E-10 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ROOT - Fatal error!\\n' );\n fprintf ( 1, ' SUMP almost exactly 1.\\n' );\n fprintf ( 1, ' SUMP = %g\\n', sump );\n error ( 'ROOTS_RC - Fatal error!' );\n end\n\n for i = 1 : n\n xnew(i) = q(i+n,n+1);\n for j = 1 : n\n xnew(i) = xnew(i) - q(i+n,j) * q(j,n+2);\n end\n%\n% If system not complete, damp the solution.\n%\n xnew(i) = xnew(i) / ( 1.0 - sump ) * ( 1.0 - damp ) ...\n + q(i+n,n+1) * damp;\n\n end\n\n for j = 1 : n + 1\n q(2*n+2,j) = q(2*n+2,j) + 1.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/zero_rc/roots_rc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6425431240705362}} {"text": "function M = shapefitfactory(VJt)\n% Linear manifold structure for optimization over the ShapeFit search space\n%\n% function M = shapefitfactory(VJt)\n%\n% Input: VJt is a matrix of size dxn, such that VJt * ones(n, 1) = 0.\n%\n% Returns M, a structure describing the Euclidean space of d-by-n matrices\n% equipped with the standard Frobenius distance and associated trace inner\n% product, as a manifold for Manopt. Matrices on M, denoted by T, have size\n% dxn and obey T*ones(n, 1) = 0 (centered columns) and = 1, where\n% = Trace(A' * B).\n%\n% See this paper: http://arxiv.org/abs/1506.01437\n% ShapeFit: Exact location recovery from corrupted pairwise directions, 2015\n% Paul Hand, Choongbum Lee, Vladislav Voroninski\n%\n% See also: shapefit_smoothed\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, June 18, 2015.\n% Contributors: \n% Change log: \n \n [d, n] = size(VJt);\n\n M.name = @() sprintf('ShapeFit space of size %d x %d', d, n);\n \n M.dim = @() d*n - d - 1;\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d, 'fro');\n \n M.dist = @(x, y) norm(x-y, 'fro');\n \n M.typicaldist = @() sqrt(d*n);\n \n M.proj = @(T, U) projection(U);\n VJt_normed = VJt / norm(VJt, 'fro');\n function PU = projection(U)\n % Center the columns\n PU = bsxfun(@minus, U, mean(U, 2));\n % Remove component along VJt\n % Note: these two actions can be executed separately, without\n % interference, owing to VJt having centered columns itself.\n PU = PU - (VJt_normed(:)'*U(:))*VJt_normed;\n end\n \n M.egrad2rgrad = M.proj;\n \n M.ehess2rhess = @(x, eg, eh, d) projection(eh);\n \n M.tangent = @(x, d) d;\n \n M.exp = @exp;\n function y = exp(x, d, t)\n if nargin == 3\n y = x + t*d;\n else\n y = x + d;\n end\n end\n \n M.retr = M.exp;\n\t\n\tM.log = @(x, y) y-x;\n\n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.randvec = @(x) randvec();\n function u = randvec()\n u = projection(randn(d, n));\n u = u / norm(u, 'fro');\n end\n \n % We exploit the fact that VJt_normed belongs to the manifold\n M.rand = @() VJt_normed + randn(1) * randvec();\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(d, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [d, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/euclidean/shapefitfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6425431213468981}} {"text": "% SFR_Bif_Diag_Second_Method - Bifurcation diagram with history.\n% Copyright Springer 2013 Stephen Lynch.\nclear\nformat long;\nhalfN=19999;N=2*halfN+1;N1=1+halfN;\nE(1)=0.4;B=0.15;Pmax=16;\n\n% Ramp the power up\nfor n=1:halfN\n E(n+1)=sqrt(n*Pmax/N1)+B*E(n)*exp(1i*abs(E(n))^2);\n Esqr(n+1)=abs(E(n+1))^2;\nend\n\n% Ramp the power down\nfor n=N1:N\n E(n+1)=sqrt(2*Pmax-n*Pmax/N1)+B*E(n)*exp(1i*abs(E(n))^2);\n Esqr(n+1)=abs(E(n+1))^2;\nend\n\nfor n=1:halfN\n Esqr1(n)=Esqr(N+1-n);\n ptsup(n)=n*Pmax/N1;\nend\n\n% Plot the bifurcation diagrams\nfsize=15;\nhold on\nset(gca,'xtick',0:4:16,'FontSize',fsize)\nset(gca,'ytick',0:5:25,'FontSize',fsize)\nplot(ptsup(1:halfN),Esqr(1:halfN),'.','MarkerSize',1);\nplot(ptsup(1:halfN),Esqr1(1:halfN),'.','MarkerSize',1);\nxlabel('Input Power','FontSize',fsize);\nylabel('Output Power','FontSize',fsize);\nhold off\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/32919-applications-of-chaos-and-nonlinear-dynamics-in-engineering-vol-1/SFR_Bif_Diag_Second_Method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.642385821503294}} {"text": "y = load('data/motorcycle.dat')';\ntime = y(1, :);\ndelta = y(2, [2:end 1]);\ny = y(3, :);\n\n%% Spline smoothing model %%\nspline = ssm_spline(delta);\nspline = estimate(y, spline, [1 0.1]);\n[alphahat V] = statesmo(y, spline);\nconf = squeeze(1.96*realsqrt(V(1, 1, :)))';\n[eps eta epsvar] = disturbsmo(y, spline);\n\nfigure('Name', 'Motorcycle acceleration data analyzed by a cubic spline');\nsubplot(2, 1, 1), plot(time, alphahat(1, :), 'b'), hold all, plot(time, [alphahat(1, :)+conf; alphahat(1, :)-conf], 'b:'), scatter(time, y, 10, 'r', 's', 'filled'), hold off, title('Spline and 95% confidence intervals'), ylim([-140 80]), set(gca,'YGrid','on');\nsubplot(2, 1, 2), scatter(time, eps./realsqrt(epsvar), 10, 'r', 's', 'filled'), title('Standardized irregular'), set(gca,'YGrid','on');\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\n\n%% Continuous local level model %%\nabseps = abs(eps);\ncontllm = [ssm_gaussian ssmodel('continuous local level', 0, 1, 1, 1, ssmat(0, [], true, zeros(size(delta)), true), 'Qd', {@(X) exp(2*X)*delta}, {[]}, ssparam({'zeta var'}, '1/2 log'))];\n[contllm logL] = estimate(abseps, contllm, [1 0.1]);\nalphahat = statesmo(abseps, contllm);\n\nfigure('Name', 'Correction for heteroscedasticity');\nsubplot(3, 1, 1), plot(time, alphahat, 'b'), hold all, scatter(time, abseps, 10, 'r', 's', 'filled'), hold off, title('Absolute smoothed irregular and h^\\ast_t'), ylim([0 87.5]);\n\n%% Correction for heteroscedasticity %%\nh2 = (alphahat/alphahat(1)).^2;\nsplineh = [ssmodel('Heteroscedastic noise', ssmat(0, [], true, zeros(size(h2)), true), zeros(1, 0), [], [], [], 'Hd', {@(X) exp(2*X)*h2}, {[]}, ssparam({'epsilon var'}, '1/2 log')) spline];\nsplineh = estimate(y, splineh, [1 0.1]);\n[alphahath Vh] = statesmo(y, splineh);\nconfh = squeeze(1.96*realsqrt(Vh(1, 1, :)))';\n[epsh eta epsvarh] = disturbsmo(y, splineh);\n\nsubplot(3, 1, 2), plot(time, alphahath(1, :), 'b'), hold all, plot(time, [alphahath(1, :)+confh; alphahath(1, :)-confh], 'b:'), scatter(time, y, 10, 'r', 's', 'filled'), hold off, title('Spline and 95% confidence intervals'), ylim([-140 80]), set(gca,'YGrid','on');\nsubplot(3, 1, 3), scatter(time, epsh./realsqrt(epsvarh), 10, 'r', 's', 'filled'), title('Standardized irregular'), set(gca,'YGrid','on');\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/ssm-1.0.1/ssm-release/demos/demo_motorcycle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6423858170015537}} {"text": "% MLRC Muli-response Linear Regression Combiner\n% \n% W = A*(WU*MLRC)\n% W = WT*MLRC(B*WT)\n% D = C*W\n% \n% INPUT\n% A Dataset used for training base classifiers as well as combiner\n% B Dataset used for training combiner of trained base classifiers\n% C Dataset used for testing (executing) the combiner\n% WU Set of untrained base classifiers, see STACKED\n% WT Set of trained base classifiers, see STACKED\n% \n% OUTPUT\n% W Trained Muli-response Linear Regression Combiner\n% D Dataset with prob. products (over base classifiers) per class\n% \n% DESCRIPTION\n% Using dataset A that contains the posterior probabilities of each instance \n% belonging to each class predicted by the base classifiers to train a\n% multi-response linear regression combiner.\n% If the original classification problem has K classes, it is converted\n% into K seperate regression problems, where the problem for class c has\n% instances with responses equal to 1 when they have label c and zero\n% otherwise. Put in another way, this function establish a multi-response \n% linear regression model for each class and utilize these models to estimate \n% the probability that the instances belong to each class.\n% Note that in the model for class c, only the probabilities of class c \n% predicted by the set of base classifiers are used. \n% \n% REFERENCE\n% 1. Ting, KM, Witten IH. Issues in stacked generalization, Journal of \n% Artificial Intelligent Research, 1999, 10: 271-289.\n% 2. Dzeroski S, Zenko B. Is combining classifiers with stacking better\n% than selecting the best one? Machine Learning, 2004, 54(3): 255-273.\n%\n% SEE ALSO (PRTools Guide)\n% DATASETS, MAPPINGS, STACKED, CLASSC, TESTD, LABELD\n\n% Copyright: Chunxia Zhang, R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction W = mlrc(A)\n\n name = 'MLR combiner';\n\n % If there are no inputs, return an untrained mapping.\n % Handle untrained calls like MLRC([])\n if nargin < 1 || isempty(A)\n W = prmapping(mfilename);\n W = setname(W,name);\n return\n end\n\n islabtype(A,'crisp'); % allow crisp labels only\n isvaldfile(A,1,2); % at least one object per class and 2 classes\n\n A = testdatasize(A,'features'); % test whether they fit\n A = setprior(A,getprior(A)); % avoid many warnings\n [m,k,c] = getsize(A); % size of training set; (m objects; k features; c classes)\n L = k/c; % compute the number of classifiers\n A = setfeatlab(A,repmat([1:c]',L,1)); % reset the feature labels of dataset A such that the first c features correspond to\n % the first classifier, the next c features correspond to the second classifier, ect.\n C = zeros(c*L,c); % register the coefficients of each model\n options = optimset('ToLX',1e-4);\n for i = 1:c % run over all classes\n Res = zeros(m,1);\n Index = find(A.featlab == i); % find the indices correspond to the jth class\n B = seldat(A,[],Index); % select the data corresponding to the jth class(m x L matrix)\n I = A.nlab == i;\n Res(I) = 1;\n [x,resnorm,residual,exitflag] = lsqnonneg(B.data,Res,[],options); % compute the nonnegative coefficients\n if exitflag == 0\n resnorm\n end\n \n for j = 1:L \n C((j-1)*c+i,i) = x(j);\n end \n end\n\n W = affine(C,[],A,getlablist(A),k,c);\n W = setname(W,name);\n\nreturn \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/mlrc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6423641158666447}} {"text": "classdef RWMOP20 < PROBLEM\n% \n% Hydro-static thrust bearing design problem\n\n%------------------------------- Reference --------------------------------\n% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,\n% A benchmark-suite of real-world constrained multi-objective optimization\n% problems and some baseline results, Swarm and Evolutionary Computation,\n% 2021, 67: 100961.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Initialization\n function Setting(obj)\n obj.M = 2;\n obj.D = 4;\n obj.lower = [ 1, 1, 1e-6,1];\n obj.upper = [16, 16, 16*1e-6,16];\n obj.encoding = ones(1,obj.D);\n end\n %% Evaluate multiple solutions\n function Population = Evaluation(obj,varargin)\n x = varargin{1};\n R = x(:,1); Ro = x(:,2); mu = x(:,3); Q = x(:,4);\n gamma = 0.0307; C = 0.5; n = -3.55; C1 = 10.04;\n Ws = 101000; Pmax = 1000; delTmax = 50; hmin = 0.001;\n gg = 386.4; N = 750;\n P = (log10(log10(8.122*1e6.*mu+0.8))-C1)./n;\n delT = 2.*(10.^P-560);\n Ef = 9336.*Q.*gamma.*C.*delT;\n h = (2.*pi.*N./60).^2.*2.*pi.*mu./Ef.*(R.^4./4-Ro.^4./4)-1e-5;\n Po = (6.*mu.*Q./(pi.*h.^3)).*log(R./Ro);\n W = pi.*Po./2.*(R.^2-Ro.^2)./(log(R./Ro)-1e-5);\n % Objective function\n f(:,1) = (Q.*Po./0.7+Ef)./12;\n f(:,2) = gamma./(gg.*Po).*(Q./(2.*pi.*R.*h));\n % Constraints\n g(:,1) = Ws-W;\n g(:,2) = Po-Pmax;\n g(:,3) = delT-delTmax;\n g(:,4) = hmin-h;\n g(:,5) = Ro-R;\n g(:,6) = f(:,2)-0.001;\n g(:,7) = W./(pi.*(R.^2-Ro.^2)+1e-5)-5000;\n Population = SOLUTION(varargin{1},f,g,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate a point for hypervolume calculation\n function R = GetOptimum(obj,~)\n R = [2.6725846e+02 -2.7672651e-05];\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/RWMOPs/RWMOP20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6423641156952999}} {"text": "function square_hex_grid_test02 ( )\n\n%*****************************************************************************80\n%\n%% SQUARE_HEX_GRID_TEST02 tests HEX_GRID_01_H.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n test_num = 17;\n\n nodes_per_layer_test = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 21, 41, 81, 101, 1001, 10001 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQUARE_HEX_GRID_TEST02\\n' );\n fprintf ( 1, ' For a hexagonal grid of points in the unit square,\\n' );\n fprintf ( 1, ' given NODES_PER_LAYER, the number of grid points\\n' );\n fprintf ( 1, ' along the first layer,\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HEX_GRID_01_H computes HX and HY, the spacings\\n' );\n fprintf ( 1, ' in the row and column directions.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NODES LAYERS HX HY\\n' );\n fprintf ( 1, ' PER\\n' );\n fprintf ( 1, ' LAYER\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n nodes_per_layer = nodes_per_layer_test ( test );\n layers = hex_grid_01_layers ( nodes_per_layer );\n [ hx, hy ] = hex_grid_01_h ( nodes_per_layer );\n fprintf ( 1, ' %6d %6d %10f %10f\\n', nodes_per_layer, layers, hx, hy );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LAYERS is chosen so that LAYERS-1 layers just fit\\n' );\n fprintf ( 1, ' inside the unit square, but LAYERS layers do not.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LAYERS HY (LAYERS-1)*HY LAYERS*HY\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n nodes_per_layer = nodes_per_layer_test ( test );\n layers = hex_grid_01_layers ( nodes_per_layer );\n [ hx, hy ] = hex_grid_01_h ( nodes_per_layer );\n\n temp1 = ( layers - 1 ) * hy;\n temp2 = ( layers ) * hy;\n\n fprintf ( 1, ' %6d %10f %10f %10f\\n', ...\n nodes_per_layer, hy, temp1, temp2 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/square_hex_grid/square_hex_grid_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.8152324893520001, "lm_q1q2_score": 0.6423471100620549}} {"text": "function f=loglikGaPfromVWH(varargin)\n% f=loglikGaPfromVWH(varargin)\n% complete log likellihood of the GaP model \n% Vxt = varargin{1}; %data (XxT)\n% Wxk = varargin{2}; %basis functions (XxK)\n% Hkt = varargin{3}; %intensities (KxT)\n% alpha = varargin{4}; %parameters of the Gamma blinking (Kx1)\n% beta = varargin{5}; %parameters of the Gamma blinking (Kx1) \n% peval = varargin{6}; %parameters\n% Gamma distribution with mean alpha/beta!\n% X: number of pixels\n% T: number of images (time - slices)\n% K: number of components\n\nVxt = varargin{1}; %data (XxT)\nWxk = varargin{2}; %basis functions (XxK)\nHkt = varargin{3}; %intensities (KxT)\nalpha = varargin{4}; %parameters of the Gamma blinking (Kx1)\nbeta = varargin{5}; %parameters of the Gamma blinking (Kx1)\npeval = varargin{6}; %parameters\n\nk=size(Wxk,2);\nif length(alpha) ==1; alpha = repmat(alpha,k, 1); end\nif length(beta) ==1; beta = repmat(beta,k, 1); end\n%[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);\n%P=Wxkbg*Hktbg; %current approximation (XxT)\nP=Wxk*Hkt; %current approximation (XxT)\n\n%Poisson contribution\nt1=Vxt.*log(P) - P - factorialapprox(Vxt); %(XxT)\n%Gamma contribution\nt2a=bsxfun(@times,(alpha-1),log(Hkt)) - bsxfun(@times,beta,Hkt); % (KxT)\nt2b=-alpha.*log(beta)-log(gamma(alpha)); %(1xK)\n\nf=sum(t1(:))+sum(t2a(:))+sum(t2b(:));\n% Conjugate gradient is mimimizing! for this it needs to be f=-f; ", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/statfun/loglikGaPfromVWH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6422513712898051}} {"text": "function [to_fine, from_fine] = twoDquad_spline(x_fine,y_fine,x_knots,y_knots)\n% Create 2D quadratic polynomial based spline approximation\n%\n% by SeHyoun Ahn, July 2016\n%\n% REFERENCE: To be Written\n%\n% PARAMTERS:\n% x_fine,y_fine = fine grid points\n% x_knots,y_knots = coarser grid to reduce to\n%\n% OUTPUTS:\n% to_fine = change of basis from spline basis to finer grid points\n% from_fine = change of basis from finer grid points to spline basis\n%\n% EXAMPLES:\n% x = linspace(-1,1,100)';\n% y = linspace(-1,1,100)';\n%\n% % z = e^(-(x^2+y^2));\n% z = exp(-bsxfun(@plus,x.^2,y'.^2));\n% \n% knot_x = linspace(-1,1,4)';\n% knot_y = linspace(-1,1,4)';\n% \n% [to_fine, from_fine] = twoDquad_spline(x,y,knot_x,knot_y);\n% \n% z_approxed = to_fine*from_fine*z(:);\n% \n% surf(z);\n% hold on;\n% disp('press any key');\n% pause();\n% surf(reshape(z_approxed,100,100));\n%\n% SYNTAX:\n% [to_fine, from_fine] = twoDquad_spline(x_fine,y_fine,x_knots,y_knots)\n\n \nn_x_fine = length(x_fine);\nn_y_fine = length(y_fine);\n\nn_x_knots = length(x_knots);\nn_y_knots = length(y_knots);\nh_x = diff(x_knots);\nh_y = diff(y_knots);\n\n% Find the Location of Rectangle\nx_locs = sum(bsxfun(@ge,x_fine,x_knots'),2);\nx_locs = min(x_locs,n_x_knots-1);\nx_adjusted = (x_fine - x_knots(x_locs))./h_x(x_locs);\n\ny_locs = sum(bsxfun(@ge,y_fine,y_knots'),2);\ny_locs = min(y_locs,n_y_knots-1);\ny_adjusted = (y_fine - y_knots(y_locs))./h_y(y_locs);\n\nxx = bsxfun(@times,x_adjusted,ones(1,n_y_fine));\nyy = bsxfun(@times,ones(n_x_fine,1),y_adjusted');\n\nxx_locs = bsxfun(@times,x_locs,ones(1,n_y_fine));\nyy_locs = bsxfun(@times,ones(n_x_fine,1),y_locs');\n\n% Stacked value of which rectangle the grid point is in\nposition = xx_locs(:) + (yy_locs(:)-1)*(n_x_knots-1);\n\n% Evaluation of Polynomial Basis\npolynomials_stacked = [ones(n_x_fine*n_y_fine,1), xx(:), yy(:), ...\n xx(:).^2, xx(:).*yy(:), yy(:).^2, ...\n xx(:).^2.*yy(:), xx(:).*yy(:).^2];\n\nevaluation = zeros(n_x_fine*n_y_fine,8*(n_x_knots-1)*(n_y_knots-1));\n\nfor i=(n_x_knots-1)*(n_y_knots-1):-1:1\n locs = find(position==i);\n evaluation(locs,(i-1)*8+1:8*i) = polynomials_stacked(locs,:);\nend\n\nevaluation = sparse(evaluation);\n\ncoeff_change = [1, 0, 0, 0, 0, 0, 0, 0; % f(0,0)\n 1, 1, 0, 1, 0, 0, 0, 0; % f(1,0)\n 1, 0, 1, 0, 0, 1, 0, 0; % f(0,1)\n 1, 1, 1, 1, 1, 1, 1, 1; % f(1,1)\n 0, 1, 0, 0, 0, 0, 0, 0; % dx(0,0)\n 0, 0, 1, 0, 0, 0, 0, 0; % dy(0,0)\n 0, 0, 1, 0, 1, 0, 1, 0; % dy(1,0)\n 0, 1, 0, 0, 1, 0, 0, 1]; % dx(0,1)\n\nrevert_change = sparse(inv(coeff_change));\naux = kron(speye(n_y_knots-1),spdiags(ones(n_x_knots-1,1),0,n_x_knots-1,n_x_knots));\n\n%% Unpack Values-Derivatives to Proper Location\nf00 = [aux,sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_y_knots)]';\nf10 = [sparse((n_x_knots-1)*(n_y_knots-1),1),aux,sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_y_knots-1)]';\nf01 = [sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots),aux,sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_x_knots-n_y_knots)]';\nf11 = [sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots+1),aux,sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_x_knots-n_y_knots-1)]';\ndx00 = [sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots*n_y_knots),spdiags(repmat(h_x,n_y_knots-1,1),0,(n_x_knots-1)*(n_y_knots-1),(n_x_knots-1)*(n_y_knots-1)),sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots*n_y_knots-1)]';\ndx01 = [sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots*n_y_knots+n_x_knots-1),spdiags(repmat(h_x,n_y_knots-1,1),0,(n_x_knots-1)*(n_y_knots-1),(n_x_knots-1)*(n_y_knots-1)),sparse((n_x_knots-1)*(n_y_knots-1),n_x_knots*n_y_knots-n_x_knots)]';\naux = kron(spdiags(h_y,0,n_y_knots-1,n_y_knots-1),spdiags(ones(n_x_knots-1,1),0,n_x_knots-1,n_x_knots));\ndy00 = [sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_y_knots),aux]';\ndy10 = [sparse((n_x_knots-1)*(n_y_knots-1),2*n_x_knots*n_y_knots-n_y_knots+1),aux(:,1:end-1)]';\n\n% Warning: Overwriting aux matrix here\naux = [f00(:),f10(:),f01(:),f11(:),dx00(:),dy00(:),dy10(:),dx01(:)]';\n\n% Change Value/Derivatives to Coefficient Basis\naux = revert_change*aux;\n\n%% A nightmare set of transformations. Good luck!\n% These are supposed to reorder things to match location of the basis\n% expansion\naux = reshape(aux,8*(3*n_x_knots*n_y_knots-n_x_knots-n_y_knots),(n_x_knots-1)*(n_y_knots-1));\npermute = reshape(1:8*(3*n_x_knots*n_y_knots-n_x_knots-n_y_knots),8,3*n_x_knots*n_y_knots-n_x_knots-n_y_knots)';\naux = reshape(aux(permute(:),:),3*n_x_knots*n_y_knots-n_x_knots-n_y_knots,8*(n_x_knots-1)*(n_y_knots-1))';\n\n%% Finally Basis Change\nto_fine = evaluation*aux;\n\n% Sometimes less than full basis are required up to machine accuarcy, so reduce with SVD\n[u,d,~] = svd(full(to_fine),'econ');\nsingles = find(diag(d)>d(1,1)*eps*10);\n\n% Basis Change Functions\nto_fine = u(:,singles)*d(singles,singles);\n% Since we took an SVD, so we can just invert by multiplication\nfrom_fine = (d(singles,singles)\\u(:,singles)');\n", "meta": {"author": "gregkaplan", "repo": "phact", "sha": "4cd7ff0c013b082db9c2ca070225feaff1056123", "save_path": "github-repos/MATLAB/gregkaplan-phact", "path": "github-repos/MATLAB/gregkaplan-phact/phact-4cd7ff0c013b082db9c2ca070225feaff1056123/twoDquad_spline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6421987476747506}} {"text": "function [x, timing] = blendenpik_under_alternative(A, b, params)\n% [x, timing] = blendenpik_under(A, b, params)\n%\n% Alternative function for solving the equation \n% x = arg min norm(A * x - b, 2) using Blendenpik, where A has \n% more columns than rows. Less stable than the regular version.\n% \n% \"params\" - parameters governning the method.\n% params.type - type of mixing transform. Optional values: 'DCT', 'DHT', 'WHT'.\n% Default is DHT.\n% params.gamma - gamma * m columns will be sampled (A is m-by-n). \n% Default is 4.\n% params.preprocess_steps - number of mixing steps to do in advance. \n% Default is 1.\n% params.maxcond - maximum condition number of the preconditioner.\n% Default is 1 / (5 * epsilon_machine).\n% params.tol - convergence thershold for LSQR.\n% Default is 1e-14.\n% params.maxit - maximum number of LSQR iterations.\n% Default is 1000.\n% params.lsvec - whether to output in \"timing\" the LSQR residuals.\n% Default is false.\n% params.use_full_lsqr - whether to use LSQR with full\n% orthogonalization. Useful for \n% preprocess_steps=0.\n% Default is false.\n%\n% Output:\n% x - the solution.\n% timing - statistics on the time spent on various phases.\n% \n% 6-December 2009, Version 1.3\n% Copyright (C) 2009, Haim Avron and Sivan Toledo.\n\n\nif (nargin < 3)\n params = struct;\nend\n\nif (~isfield(params, 'type'));\n params.type = 'DHT';\nend\n\nif (~isfield(params, 'gamma'))\n params.gamma = 4;\nend\n\nif (~isfield(params, 'preprocess_steps'))\n params.preprocess_steps = 1;\nend\n\nif (~isfield(params, 'tol'))\n params.tol = 1e-14;\nend\n\nif (~isfield(params, 'maxit'))\n params.maxit = 1000;\nend\n\nif (~isfield(params, 'maxcond'))\n params.maxcond = 1 / (5 * eps);\nend\n\nif (~isfield(params, 'lsvec'))\n params.lsvec = false;\nend\n\nif (~isfield(params, 'slight_coherence'))\n params.slight_coherence = 0;\nend\n\nif (~isfield(params, 'use_full_lsqr'))\n params.use_full_lsqr = false;\nend\n\ntstart = wtime;\n\n%% Build preconditioner\nt1 = wtime;\n\n[m, n] = size(A);\nAT = A';\nt0 = wtime;\nfrut_D = sign(randn(n, 1));\nB = fast_unitary_transform(AT, frut_D, params.type);\nnn = size(B, 1);\nfrut_D(n+1:nn) = 0;\nfrut_time = wtime - t0;\ndisp(sprintf('\\t\\tRandom unit diagonal + unitary transformation time: %.2f sec', frut_time));\ntiming.precond_timing.timing.frut_time = frut_time;\n\nt0 = wtime;\nt = params.gamma * m / nn;\ns = rand(nn, 1);\nSB = B(find(s < t), :);\nsample_time = wtime - t0;\ndisp(sprintf('\\t\\tRandom sampling time: %.2f sec', sample_time));\ntiming.precond_timing.sample_time = sample_time;\n\nt0 = wtime;\n[Y, tau] = mex_dgeqrf(SB); \nqr_time = wtime - t0;\ndisp(sprintf('\\t\\tQR on random sample time: %.2f sec', qr_time));\ntiming.qr_time = qr_time;\n \ntiming.preprocess_total_time = wtime - t1;\ndisp(sprintf('\\tPreprocessing time: %.2f sec', timing.preprocess_total_time));\n\n%% One solution\nt1 = wtime;\ny = mex_dtrsm(Y, b, 1.0, 'L', 'U', 'T', 'N');\nssz = size(Y, 1);\np0 = mex_dormqr(Y, tau, [y; zeros(ssz-m, 1)], 'L', 'N');\np1 = zeros(nn, 1); p1(s < t) = p0;\np2 = fast_unitary_transform(p1, frut_D, ['I' params.type]);\np = p2(1:n);\ntiming.find_non_min_time = wtime - t1;\ndisp(sprintf('\\tFind a non-minimal solution: %.2f sec', timing.find_non_min_time));\n\n%% LSQR\nt1 = wtime;\nR = triu(Y(1:m, 1:m)); \n% clear Y;\n% clear SB\n% clear tau;\nif (~params.lsvec)\n if (~params.use_full_lsqr)\n [x0, timing.lsqr_its] = dense_lsqr(AT, p, R, params.tol, params.maxit);\n else\n [x0, timing.lsqr_its] = dense_full_lsqr(AT, p, R, params.tol, params.maxit);\n end\nelse\n [x0, timing.lsqr_its, timing.lsvec, timing.resvec] = dense_lsqr(AT, p, R, params.tol, params.maxit);\nend\ntiming.lsqr_time = wtime - t1;\ndisp(sprintf('\\tLSQR time: %.2f sec', timing.lsqr_time));\n\n%% Mult by AT to get final solution\nt1 = wtime;\nx = AT * x0;\ntiming.multAT_time = wtime - t1;\ndisp(sprintf('\\tMultiply by A'' time: %.2f sec', timing.multAT_time));\ntiming.total_time = wtime - tstart;\ndisp(sprintf('Total time: %.2f sec', timing.total_time));\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25241-blendenpik/blendenpik/blendenpik_under_alternative.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6421531254222506}} {"text": "function [f,J] = spm_fx_phase (phi,u,P,M)\n% State equation for a phase-coupled oscillator\n% FORMAT [f,J] = spm_fx_phase (phi,u,P,M)\n%\n% phi state variable\n% u []\n% P model (variable) parameter structure\n% M model (fixed) parameter structure\n%\n% f Flow vector, dphi/dt\n% J Jacobian, J(i,j)=df_i/dphi_j\n%__________________________________________________________________________\n% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging\n \n% Will Penny\n% $Id: spm_fx_phase.m 2908 2009-03-20 14:54:03Z will $\n\n% Sin terms\nif isfield(P,'As')\n Nr=size(P.As,1);\n Ns=size(P.As,3);\n \n % negative abs\n Ahs=~(P.As==0);\n As=-abs(P.As).*Ahs;\nelse\n Ns=0;\nend\n\n% Cos terms\nif isfield(P,'Ac')\n Nc=size(P.Ac,3);\n Nr=size(P.Ac,1);\n \n % Positive abs\n Ahc=~(P.Ac==0);\n Ac=abs(P.Ac).*Ahc;\nelse\n Nc=0;\nend\n\n% Flow vector\nf=zeros(Nr,1);\nfor i=1:Nr,\n change=0;\n for j=1:Nr,\n phi_diff=phi(i)-phi(j);\n for n=1:Ns,\n change=change+As(i,j,n)*sin(n*phi_diff);\n end\n for n=1:Nc,\n change=change+Ac(i,j,n)*cos(n*phi_diff);\n end\n end\n exc=M.freq+P.df(i)+change;\n f(i)=2*pi*exc;\nend\n\nif nargout == 1; return, end\n\n% Jacobian\nAs=-As;\nfor i=1:Nr,\n for j=1:Nr,\n jac=0;\n if i==j\n % Diagonal\n for jj=1:Nr,\n for n=1:Ns,\n jac=jac-n*As(i,jj,n);\n end\n end\n else\n % Off-diagonal\n phi_diff=phi(i)-phi(j);\n for n=1:Ns,\n jac=jac+n*As(i,j,n)*cos(n*phi_diff);\n end\n for n=1:Nc,\n jac=jac+n*Ac(i,j,n)*sin(n*phi_diff);\n end\n end\n J(i,j)=jac;\n end\nend\nJ=J*2*pi;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/dcm_meeg/spm_fx_phase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6420623391895632}} {"text": "function [x, R] = orth_at(x, pos, dir, apply)\n %ORTH_AT Orthogonalize single core.\n % X = ORTH_AT( X, POS, 'LEFT') left-orthogonalizes the core at position POS\n % and multiplies the corresponding R-factor with core POS+1. All other cores\n % are untouched. The modified tensor is returned.\n %\n % X = ORTH_AT( X, POS, 'RIGHT') right-orthogonalizes the core at position POS\n % and multiplies the corresponding R-factor with core POS-1. All other cores\n % are untouched. The modified tensor is returned.\n %\n % See also ORTHOGONALIZE.\n\n % TTeMPS Toolbox.\n % Michael Steinlechner, 2013-2016\n % Questions and contact: michael.steinlechner@epfl.ch\n % BSD 2-clause license, see LICENSE.txt\n\n if ~exist('apply', 'var')\n apply = true;\n end\n\n sz = size(x.U{pos});\n\n if length(sz) == 2\n sz = [sz, 1];\n end\n\n if strcmpi(dir, 'left')\n [Q, R] = qr_unique(unfold(x.U{pos}, 'left'));\n x.U{pos} = reshape(Q, [sz(1), sz(2), size(Q, 2)]);\n\n if apply\n x.U{pos + 1} = tensorprod_ttemps(x.U{pos + 1}, R, 1);\n end\n\n elseif strcmpi(dir, 'right')\n % mind the transpose as we want to orthonormalize rows\n [Q, R] = qr_unique(unfold(x.U{pos}, 'right')');\n x.U{pos} = reshape(Q', [size(Q, 2), sz(2), sz(3)]);\n\n if apply\n x.U{pos - 1} = tensorprod_ttemps(x.U{pos - 1}, R, 3);\n end\n\n else\n error('Unknown direction specified. Choose either LEFT or RIGHT')\n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/@TTeMPS/orth_at.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.641967931017478}} {"text": "% example_nufft1_antenna.m\n%\n% This m-file is an example of applying the NUFFT method to compute\n% the far-field beam pattern of a 2D array of nonuniformly spaced\n% (point?) antenna elements.\n% In the nomenclature of the 1999 SIAM J Sci. Comput. paper by Nguyen and Liu,\n% this is \"Problem 1.\"\n%\n% This provides an example of how to compute \"the Fourier transform\"\n% of nonuniformly spaced data.\n%\n% The user should think very carefully about whether it is truly meaningful\n% to compute \"the FT\" of unequally spaced data first. It certainly is\n% meaningful for attenna beam patterns, but may not always be what is really\n% useful for all applications with nonuniformly sampled data.\n%\n% Copyright 2007, Jeff Fessler, University of Michigan\n\n%\n% antenna element locations in 2d plane\n%\nclf, pl = @(p) subplot(220+p);\nfor choice=1:2\n\ttmp = [0:40]'/41 * 2 * pi;\n\tyc = sin(choice*tmp); % funny bowtie pattern for illustration\n\txc = cos(tmp); clear tmp\n\tpl(choice), plot(xc, yc, 'o'), axis square\n\txlabel 'x', ylabel 'x', title 'antenna locations'\n\n\t% create NUFFT structure\n\tN = [1 1]*2^8;\n\tJ = [5 5];\t% interpolation neighborhood\n\tK = N*2;\t% two-times oversampling\n\tom = [xc yc];\t% 'frequencies' are locations here!\n\n\t% the following line probably needs to be changed\n\t% to get the proper scaling/dimensions in the pattern\n\t% but for now i just make it fill up [-pi/20,pi/20]\n\t% in hopes of getting a nice 'picture' of pattern\n\tom = (pi/20) * om / max(om(:));\n\tst = nufft_init(om, N, J, K, N/2, 'minmax:kb');\n\n\tweights = ones(size(xc)); % equal weights on each element; could change\n\n\t% call the *adjoint* NUFFT; this is what does \"the FT of unequal data\"\n\tpattern = nufft_adj(weights, st);\n\n\tpl(2+choice)\n\tim(pattern, 'pattern')\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/example_nufft_antenna.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6419679266412497}} {"text": "%% \n% \\documentclass[12pt]{article}\n%\n% \\title{ODEbox: A Toolbox for Ordinary Differential Equations\\\\\n% Getting Started with the odeSolveIVP Tool}\n% \n% \\author{Matthew Harker and Paul O'Leary\\\\\n% Institute for Automation\\\\\n% University of Leoben\\\\\n% A-8700 Leoben,\n% Austria\\\\\n% URL: automation.unileoben.ac.at\\\\\n% \\\\\n% Original: January 9, 2013\\\\\n% $\\copyright$ 2013\\\\\n% \\\\\n% Last Modified: \\today}\n%%\n% This is the documentation for the \\lstinline{odeSolveIVP.m} file. This is\n% a tool for the solution of initial value problems. It offers a very\n% simple interface to solving such problems. Two different examples are\n% documented here to show the different possible calls to the tool. The\n% examples which have been selected are from Kreyszig~\\cite{Kreyszig2010} \n% and Adams~\\cite{Adams}, since this\n% give the analytical results enabling a comparison with the numerical\n% solutions.\n%\n%%\n% \\section{Tidy up the Workspace}\nclear all;\nclose all;\nsetUpGraphics;\n%\n%%\n% \\section{IVP Example 1}\n%\n% The equation being considered here is:\n% %\n% \\begin{equation}\n% \\dddot{y} + 3 \\, \\ddot{y} + 3 \\, \\dot{y} + y = 30 \\, \\mathrm{e}^{-x},\n% \\end{equation}\n% %\n% with the initial conditions\n% %\n% \\begin{equation}\n% y(0) = 3,\n% \\hspace{2mm}\n% \\dot{y}(0) = -3,\n% \\hspace{2mm}\n% \\text{and}\n% \\hspace{2mm}\n% \\ddot{y}(0) = -47.\n% \\end{equation}\n% %\n% The analytical solution to this equation is,\n% %\n% \\begin{equation}\n% (3 - 25 \\, x^2 + 5 \\, x^3) \\, \\mathrm{e}^{-x}\n% \\end{equation}\n%\n% this example is from~\\cite[Chapter 2]{Kreyszig2010}.\n%%\n% \\subsection{Define the paramates for $x$.}\n% \n% Define the minimum, maximum x values and the number of points desired for\n% the solution.\n%\nxMin = 0 ;\nxMax = 10 ;\nnoPts = 73 ;\n%%\n% Setup the paramater vector\n%\nparams = [xMin, xMax, noPts ];\n%%\n% \\subsection{Call the \\lstinline{odeSolveIVP}}\n%\n% A vector cof constant coefficients are used for this example equation.\n%\n[y, x, vals] = odeSolveIVP( [1;3;3;1] , '30*exp(-x)', [ 3 ; -3; -47 ] , params, 13);\n%%\n% Defining a MATLAB inline function for the analytical solution.\n%\nf = inline('(3 - 25 * x.^2).* exp(-x) + 5 * (x.^3).*exp(-x)') ;\n%%\n% \\subsection{Plot the Results}\n%\n% The inline analytical solution is computed during plotting.\n%\nfig1 = figure;\nplot( x, f(x), 'k');\nhold on;\nplot( x, y, 'ro');\ngrid on;\nxlabel('$$x$$');\nylabel('$$y(x)$$');\nlegend('Analytic','Numerical','Location','SouthEast');\n%\n%\\caption{Comparison of the analytical and the numerical solution for the first example.}\n%%\n% \\section{IVP Example 2}\n%\n% The equation being considered here is:\n% %\n% \\begin{equation}\n% x^2 \\ddot{y} - 3 \\, x\\, \\dot{y} + 13 y = 0,\n% \\end{equation}\n% %\n% with the initial conditions\n% %\n% \\begin{equation}\n% y(0) = 5,\n% \\hspace{2mm}\n% \\text{and}\n% \\hspace{2mm}\n% \\dot{y}(0) = 0,\n% \\end{equation}\n% %\n% The analytical solution to this equation is,\n% %\n% \\begin{equation}\n% 5 \\, x^2 \\, \\cos(3 \\log(x)) - (10/3) \\, x^2 \\, \\sin(3 \\log(x))\n% \\end{equation}\n%\n% this example if from~\\cite{Adams}.\n%%\n% \\subsection{Define the paramates for $x$.}\n% \n% Define the minimum, maximum x values and the number of points desired for\n% the solution.\n%\nnoPts = 73 ;\nxMin = 1 ;\nxMax = 5 ;\n%%\n% Generate the vector of x values for which the equation should be solved.\n% We are now artifically generating a nonuniformly spaced set of pointe to\n% compute the solution. This is done to demonstrate the possibility of\n% working with arbitrary nodes.\n%\nz = linspace( 0, 1, noPts )';\nz = z.^2;\n%\nx = xMin + z * (xMax - xMin);\n%\n%%\n% \\subsection{Call the \\lstinline{odeSolveIVP}}\n%\n% This is an equation with variable coefficients, i.e., the coefficients\n% are functions of $x$. the functions are defines as strings which can be\n% computed to inline functions. the notation [] is used to indicate that \n% its is a homogeneous equation, i.e., the forcing function is identically \n% zero. This call is with x as a vector of points where the solution should \n% be computed.\n%\n[y, x, vals] = odeSolveIVP( {'x.^2';'-3*x';'13'} , [], [ 5 ; 0 ] , x, 13);\n%% \n% The inline for the analytical solution is, this is only needed for\n% comparison purposes.\n%\nf = inline('5*x.^2.*cos(3*log(x)) - (10/3)*x.^2.*sin(3*log(x))') ;\n%%\n% \\subsection{Plot the Results}\nfig1 = figure;\nplot( x, f(x), 'k');\nhold on;\nplot( x, y, 'ro');\ngrid on;\nxlabel('$$x$$');\nylabel('$$y(x)$$');\nlegend('Analytic','Numerical','Location','NorthWest');\n%\n%\\caption{Comparison of the analytical and the numerical solution for the \n% second example. Note the non-uniform spacing of the nodes.}\n%\n%% Define the Bibliography\n%\n% \\bibliographystyle{plain}\n% \\bibliography{odebib}", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41354-ordinary-differential-equation-toolbox-odebox-version-1-1/ODEBoxV1-1/Documentation/odeSolveIVPDoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.8933094103149355, "lm_q1q2_score": 0.6419271223159947}} {"text": "% INVWISHIRND - Inverse Wishart Random Matrix\n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n%\n% [IW] = invwishirnd(S,d) \n%\n% S = p x p symmetric, postitive definite \"scale\" matrix \n% d = \"degrees of freedom\" parameter\n% = \"precision\" parameter \n% (d must be an integer for this routine, see INVWISHRND)\n%\n% IW = random matrix from the inverse Wishart distribution\n%\n% Note:\n% different sources use different parameterizations w.r.t. nu\n% this routine uses that of Press and Shigemasu (1989):\n% density(IW) is proportional to \n% exp[-.5*trace(S*inv(IW))] / [det(IW) ^ (d/2)].\n%\n% With this density definition:\n% mean(IW) = S/(d-2p-2) when d>2p+2,\n% mode(IW) = S/d.\n%\n% See also: INVWISHRND, WISHRND\n\nfunction [IW] = invwishirnd(S,d) \n[p,p2] = size(S) ;\nW = wishirnd(inv(S),d-p-1) ;\nIW = inv(W) ;\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/198-mcmc/mcmc/invwishirnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6419271205557308}} {"text": "function [ CONDXY ] = ConditionalHist( X,Y,varargin)\n%[CONDXY] = ConditionalHist(X,Y) Calculates the conditional probabilty \n%of Y given X\n%\n%INPUT\n% X\n% Y\n% (options)\n% 'numXbins' (default: 50)\n% 'numYbins' (default: 50)\n% 'Xbounds'\n% 'Ybounds'\n% 'Xbinoverlap' (default: 1)\n% 'minX' (default: 25)\n% 'conditionby' condition on X with different occupancy from datapoints\n% \n%\n%OUTPUT\n% CONDXY\n% .pYX a [numXbins x numYbins] matrix in which the [x,y]th element is P(y|x) \n% .XYhist joint histogram of X and Y\n% .XYprop joint probability of X and Y\n% .Xhist histogram of X\n% .Xbins X bins\n% .Ybins Y bins\n%\n%DLevenstein 2019\n%%\np = inputParser;\naddParameter(p,'numXbins',50)\naddParameter(p,'numYbins',50)\naddParameter(p,'Xbounds',[])\naddParameter(p,'Ybounds',[])\naddParameter(p,'minX',25)\naddParameter(p,'Xbinoverlap',1)\naddParameter(p,'conditionby',[])\nparse(p,varargin{:})\nnumXbins = p.Results.numXbins;\nnumYbins = p.Results.numYbins;\nXbounds = p.Results.Xbounds;\nYbounds = p.Results.Ybounds;\nminX = p.Results.minX;\nXbinoverlap = p.Results.Xbinoverlap;\nconditionby = p.Results.conditionby;\n\n\n%% For cell input\n\nif iscell(Y) && iscell(X)\n CONDXY = cellfun(@(x,y) ConditionalHist(x,y,varargin{:}),...\n X,Y,'UniformOutput',false);\n CONDXY = bz_CollapseStruct([CONDXY{:}],3);\n CONDXY.Xbins = CONDXY.Xbins(1,:,1);\n CONDXY.Ybins = CONDXY.Ybins(1,:,1);\n return\nend\n\n\n%% For multiple columns in X - conditonal probabilty of each\n\nif size(Y,2)>1 && size(X,2)==1\n for yy = 1:size(Y,2)\n CONDXY(yy) = ConditionalHist(X,Y(:,yy),varargin{:});\n end\n CONDXY = bz_CollapseStruct(CONDXY,3);\n return\nend\n\n\n\n%%\nif isempty(Xbounds)\n Xbounds(1) = min(X); Xbounds(2) = max(X);\nend\nif isempty(Ybounds)\n Ybounds(1) = min(Y(~isinf(Y))); Ybounds(2) = max(Y(~isinf(Y)));\nend\n\nXedges = linspace(Xbounds(1),Xbounds(2),numXbins+1);\nXbins = Xedges(1:end-1)+ 0.5.*diff(Xedges([1 2]));\nXedges(1) = -inf;Xedges(end) = inf;\n\nYedges = linspace(Ybounds(1),Ybounds(2),numYbins+1);\nYbins = Yedges(1:end-1)+ 0.5.*diff(Yedges([1 2]));\nYedges(1) = -inf;Yedges(end) = inf;\n\n%First calculate the marginal probability of X\n[Xhist,~,XbinID] = histcounts(X,Xedges);\n\n\n%Then calculate the joint probabilty of X and Y\nif length(Ybins) ==1\n XYhist = Xhist;\nelseif isempty(Y)\n warning('Y is empty... using nans')\n Y = nan(size(X));\n XYhist = nan(length(Xbins),length(Ybins));\nelse\n [XYhist] = hist3([X,Y],{Xbins,Ybins});\nend\n\n% Conditional probability of Y given X\nif isempty(conditionby)\n Xhist4norm = Xhist;\nelse\n Xhist4norm = histcounts(conditionby,Xedges);\nend\nXhist4norm(Xhist4norm<=minX) = nan; %Remove bins that don't have enough sampling\npYX = bsxfun(@(x,y) x./y,XYhist,Xhist4norm');\n\n%Mean Y given X\nfor xx = 1:length(Xbins)\n meanYX(xx) = nanmean(Y(XbinID==xx));\n meanYX(isnan(Xhist4norm)) = nan;\nend\n\nCONDXY.pYX = pYX;\nCONDXY.XYhist = XYhist;\nCONDXY.XYprob = XYhist./nansum(XYhist(:));\nCONDXY.meanYX = meanYX;\nCONDXY.Xhist = Xhist;\nCONDXY.pX = Xhist./nansum(Xhist);\nCONDXY.Xbins = Xbins;\nCONDXY.Ybins = Ybins;\n\n\n%%\n% figure\n% imagesc(CONDXY.Xbins,CONDXY.Ybins,CONDXY.pYX')\n% axis xy\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/utilities/ConditionalHist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6418628594365307}} {"text": "function [output, fs] = eldar_reconstruction(inp_fs, input, time_skew)\n % Reconstruction of a signal from non-uniform samples\n \n N = length(time_skew); % number of samplers\n fs = inp_fs * N; % full sampling frequency\n T_Q = 1 / fs; % Nyquist sampling period\n T = N * T_Q; % single sampler period\n \n % index_mapping is used to reorded filters in case the first input \n % signal is actually delayed comparing to the second and not vice versa\n [time_skew, index_mapping] = sort(time_skew);\n \n H = construct_filters(N, T, time_skew);\n \n filtered = cell(N, 1);\n for i = 1:N\n % upsampling - according to the interpolation identity\n upsampled_input = upsample(input{index_mapping(i)}, N);\n filtered{i} = filter(H{i}, 1, upsampled_input);\n end\n \n min_len = min(cellfun('length', filtered));\n filtered_mat = zeros(min_len, N);\n for i=1:N\n filtered_mat(:, i) = filtered{i}(1:min_len);\n end\n output = real(sum(filtered_mat, 2)); % sum filterbank outputs\nend\n\nfunction filter_value = get_filter_value(N, T, a, time_skew, p, t)\n tp = time_skew(p + 1);\n sine_product_elements = ones(N, 1);\n for q = 0:N-1\n if q == p\n continue;\n end\n \n tq = time_skew(q + 1);\n sine_product_elements(q+1) = sin(pi*(t + tp - tq)/T);\n end\n sine_product = prod(sine_product_elements);\n filter_value = a(p + 1) * sinc((t)/T) * sine_product;\nend\n\nfunction H = construct_filters(N, T, tau)\n a = build_coefficients(N, T, tau);\n \n TAPS = 48;\n Tq = T/N;\n H = cell(N, 1);\n for p = 0:N-1\n H{p+1} = zeros(TAPS, 1);\n tp = tau(p+1);\n for n = 0:TAPS-1\n t = (n*Tq - tp);\n H{p+1}(n+1) = get_filter_value(N, T, a, tau, p, t); \n end\n \n% H{p+1}(tp/Tq+1) = 1;\n fvtool(H{p+1});\n end\nend\n\nfunction a = build_coefficients(N, T, tau)\n % compute a coefficients according to Sindhi-Prabhu\n a = ones(N, 1);\n for p = 1:N\n for q = 1:N\n if q ~= p\n a(p) = a(p) / sin(pi*(tau(p) - tau(q)) / T);\n end\n end\n end\nend", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/eldar_reconstruction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6417678902715956}} {"text": "function [P] = unmixP_NCM(X,E,Sigma,Parameters)\n%% Input:\n% X - d-by-N HSI data, matrix\n% E - d-by-M endmember mean set, matrix\n% Sigma - d-by-d-by-M endmember covariance set, matrix\n% Output:\n% P - M-by-N proportion matrix\n% Author: Alina Zare et al. Rewriten by Sheng Zou\n% Department of Electrical and Computer Engineering, University of Florida\n% 09/07/2017\n\n%% Initialization of P\n[d,N] = size(X);\nM = size(E,2);\nP = 1/M.*ones(M,N); % intialize proportion values to be 1/M\n\n%Initialize all Likelihood and Prior Values\nLogLikelihoodOld = ComputeLogLikelihoodAll(X, E, P, Sigma, N);\n\n\nfor iteration = 2:Parameters.NumberIterations+1\n Y = randg(1, N, M) ;\n v = sum(Y,2);\n samples = (Y./repmat(v,[1,size(Y,2)]))';\n LogLikelihoodNew = ComputeLogLikelihoodAll(X, E, samples, Sigma, N);\n Ratios = exp(LogLikelihoodNew - LogLikelihoodOld);\n rands = rand(1,N);\n Vals = rands < Ratios;\n Vrep = repmat(Vals,M,1);\n P = samples.*Vrep + P.*(1-Vrep);\n \n LogLikelihoodOld = (1-Vals).*LogLikelihoodOld + (Vals).*LogLikelihoodNew;\n if mod(iteration, round(Parameters.NumberIterations/10)) == 0\n disp(strcat('iteration = ',num2str(iteration)));\n disp(strcat('loglikelihood = ',num2str(sum(LogLikelihoodOld))));\n end\nend\n\nend\n\nfunction [LogLikelihoodAll] = ComputeLogLikelihoodAll(X, E, P, cov, N)\n% compute log likelihood of all points\n\nterm1 = zeros(1,N);\nterm2 = zeros(1,N);\n\nfor s = 1:size(E,2)\n statement(s)=isdiag(squeeze(cov(:,:,s))) && length(unique(diag(cov(:,:,s))))==1; % check if all the covariance matrices are diagonal and isotropic\nend\n\nif mean(statement) ==1 % all diagonal and isotropic\n for z = 1:size(P,1)\n a(z) = unique(diag(cov(:,:,z)));\n end\n term1 = -.5*size(X,1)*log(a*(P.^2));\n term2 = -.5*(sum((X-E*P).^2)./(a*(P.^2)));\nelse\n \n parfor t = 1:N\n P3D = zeros(1,1,size(E,2));\n P3D(:,:,1:size(E,2)) = P(:,t).^2;\n P3D_full = repmat(P3D,size(X,1),size(X,1));\n term1(t) = -.5*logdet(sum(P3D_full.*cov,3));\n term2(t) = -.5*(X(:,t)-E*P(:,t))'*(sum(P3D_full.*cov,3)\\(X(:,t)-E*P(:,t)));\n end\n \nend\n\nLogLikelihoodAll = term1 + term2;\nend\n\n\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM_SantaBarbara/competing_methods/unmixP_NCM/unmixP_NCM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6417678877966165}} {"text": "function [out] = interception_5(p1,p2,In)\n%interception_5 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Interception excess after a combined absolute amount and fraction are intercepted\n% Constraints: f >= 0\n% @(Inputs): p1 - fraction that is not throughfall [-]\n% p2 - constnat interception and evaporation [mm/d]\n% In - incoming flux [mm/d]\n\nout = max(p1.*In-p2,0);\n\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/interception_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.641767882769458}} {"text": "% STE_SWLP Stabilized weighted linear prediction using short-time-energy\n% weighting\n% [A,w] = ste_swlp(s,p,m,k)\n%\n% Description\n% This function fits linear prediction coefficients to the analysis\n% frame using the basic form of stabilized weighted linear prediction\n% (SWLP) that weights each value of the squared prediction error by the\n% short-time energy (STE) of the previous samples.\n%\n% Inputs\n% s : Speech signal frame [samples]\n% p : Order of SWLP analysis\n% m : Length of the STE window (default to p)\n% k : Delay of the STE window (default to 1)\n%\n% Outputs\n% A : Linear prediction inverse filter coefficients\n% w : the STE weighting function\n%\n% Notes\n% SWLP generally gives smoother spectral shapes than the corresponding\n% weighted linear prediction (WLP) using the same weighting function.\n%\n% Example\n% A = ste_swlp(s,p) gives the linear predictive inverse filter\n% coefficients optimized using STE-SWLP\n%\n% References\n% [1] C. Magi, J. Pohjalainen, T. Bäckström and P. Alku, \"Stabilised\n% weighted linear prediction\", Speech Communication, vol. 51, no. 5, pp.\n% 401–411, 2009.\n% [2] J. Pohjalainen, H. Kallasjoki, K. J. Palomäki, M. Kurimo and P.\n% Alku, \"Weighted linear prediction for speech analysis in noisy\n% conditions\", in Proc. Interspeech, Brighton, UK, pp. 1315-1318,\n% 2009.\n%\n% Copyright (c) 2013 Aalto University\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 Common Speech Processing Repository \n% http://covarep.github.io/covarep/\n%\n% Octave Compatible\n% \n% Author\n% Jouni Pohjalainen jouni.pohjalainen@aalto.fi\n%\n% $Id $\n\nfunction [A,w] = ste_swlp(s,p,m,k)\n\n% handle the special case of all-zero frames\nif all(s==0)\n s = eps*randn(size(s));\nend\n\nN = length(s);\n\n% default value for the STE window length\nif nargin<3\n m = p;\nend\n\n% default value for the STE window lag\nif nargin<4\n k = 1;\nend\n\n% compute STE weighting function\nw = stew(s,m,p,k)+eps;\n\nw = w(1:(N+p));\n\n% initialize partial weights for recursive computation (see [2], Eqs.\n% (5)-(7), for the partial-weight formulation of SWLP)\nZ = zeros(N+p,p+1);\nZ(:,1) = sqrt(w);\n\n% delayed and weighted versions of the signal\nY = zeros(N+p,p+1);\nY(:,1) = Z(:,1).*[s;zeros(p,1)];\n\n% recursion for partial weights and weighting of differently lagged\n% versions of the signal\nfor i1=1:p\n Z((i1+1):(N+p),i1+1) = max([ones(N+p-i1,1) sqrt(w((i1+1):(N+p))./w(i1:(N+p-1)))],[],2) .* Z(i1:(N+p-1),i1);\n Y(:,i1+1) = Z(:,i1+1) .* [zeros(i1,1);s;zeros(p-i1,1)];\nend\n\n% compute weighted autocorrelations\nR = (Y'*Y)/N;\n\n% solve the p predictor coefficients\nA = R(2:end,2:end)\\R(2:end,1);\n\n% convert to inverse filter form\nA = [1;-A]';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction w = stew(x,m,p,k)\n% STE weighting for an order p predictor using window of length m delayed\n% by k samples\nw = conv([zeros(k,1);x(:)].^2,ones(m,1));\nw = [w;zeros(p-m,1)];\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/envelope/env_swlp_ste.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6417576202655771}} {"text": "function yval = dif_val ( ntab, xtab, diftab, xval )\n\n%*****************************************************************************80\n%\n%% DIF_VAL evaluates a divided difference polynomial at a point.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carl de Boor,\n% A Practical Guide to Splines,\n% Springer Verlag, 1978.\n%\n% Parameters:\n%\n% Input, integer NTAB, the number of divided difference\n% coefficients in DIFTAB, and the number of points XTAB.\n%\n% Input, real XTAB(NTAB), the X values upon which the\n% divided difference polynomial is based.\n%\n% Input, real DIFTAB(NTAB), the divided difference\n% polynomial coefficients.\n%\n% Input, real XVAL, the value where the polynomial\n% is to be evaluated.\n%\n% Output, real YVAL, the value of the polynomial at XVAL.\n%\n yval = diftab(ntab);\n for i = 1 : ntab-1\n yval = diftab(ntab-i) + ( xval - xtab(ntab-i) ) * yval;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/dif_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6416997686970173}} {"text": "function coef=framecoef2tf(F,coef)\n%FRAMECOEF2TF Convert coefficients to time-frequency plane\n% Usage: cout=framecoef2tf(F,cin);\n%\n% `framecoef2tf(F,cin)` converts the frame coefficients *cin* into the\n% time-frequency plane layout. The frame object *F* must have been\n% created using |frame|.\n%\n% The time-frequency plane layout is a matrix, where the first\n% dimension indexes frequency and the second dimension time. This is\n% similar to the output format from |dgt| and |wmdct|.\n%\n% Not all types of frames support this coefficient conversion. The supported \n% types of frames are: `'dgt'`, `'dgtreal'`, `'dwilt'`, `'wmdct'`, `'ufilterbank'`,\n% `'ufwt'`,`'uwfbt'` and `'uwpfbt'`.\n%\n% See also: frame, frametf2coef, framecoef2native\n \ncomplainif_notenoughargs(nargin,2,'FRAMECOEF2TF');\ncomplainif_notvalidframeobj(F,'FRAMECOEF2TF');\n\nswitch(F.type)\n case 'dgt'\n [MN,W]=size(coef);\n N=MN/F.M;\n coef=reshape(coef,[F.M,N,W]); \n case 'dgtreal'\n [MN,W]=size(coef);\n M2=floor(F.M/2)+1;\n N=MN/M2;\n coef=reshape(coef,[M2,N,W]); \n case 'dwilt'\n [MN,W]=size(coef);\n N=MN/F.M;\n coef=wil2rect(reshape(coef,[2*F.M,N/2,W])); \n case 'wmdct'\n [MN,W]=size(coef);\n N=MN/F.M;\n coef=reshape(coef,[F.M,N,W]); \n case 'ufilterbank'\n [MN,W]=size(coef);\n M=numel(F.g);\n N=MN/M;\n coef=permute(reshape(coef,[N,M,W]),[2,1,3]); \n case {'ufwt','uwfbt','uwpfbt'}\n coef = permute(F.coef2native(coef,size(coef)),[2,1,3]); \n otherwise\n error('%s: TF-plane layout not supported for this transform.',upper(mfilename));\nend;\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/frames/framecoef2tf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.641699736985539}} {"text": "%\n% Implementation of Exposure Fusion\n%\n% written by Tom Mertens, Hasselt University, August 2007\n% e-mail: tom.mertens@gmail.com\n%\n% This work is described in\n% \"Exposure Fusion\"\n% Tom Mertens, Jan Kautz and Frank Van Reeth\n% In Proceedings of Pacific Graphics 2007\n%\n%\n% Usage:\n% result = exposure_fusion(I,m);\n% Arguments:\n% 'I': represents a stack of N color images (at double\n% precision). Dimensions are (height x width x 3 x N).\n% 'm': 3-tuple that controls the per-pixel measures. The elements \n% control contrast, saturation and well-exposedness, respectively.\n%\n% Example:\n% 'figure; imshow(exposure_fusion(I, [0 0 1]);'\n% This displays the fusion of the images in 'I' using only the well-exposedness\n% measure\n%\n\nfunction [R, W]= exposure_fusion(I,m)\n\nr = size(I,1);\nc = size(I,2);\nN = size(I,4);\n\nW = ones(r,c,N);\n\n%compute the measures and combines them into a weight map\ncontrast_parm = m(1);\nsat_parm = m(2);\nwexp_parm = m(3);\n\nif (contrast_parm > 0)\n W = W.*contrast(I).^contrast_parm;\nend\nif (sat_parm > 0)\n W = W.*saturation(I).^sat_parm;\nend\nif (wexp_parm > 0)\n W = W.*well_exposedness(I).^wexp_parm;\nend\n\n%normalize weights: make sure that weights sum to one for each pixel\nW = W + 1e-12; %avoids division by zero\nW = W./repmat(sum(W,3),[1 1 N]);\n\n% create empty pyramid\npyr = gaussian_pyramid_(zeros(r,c,3));\nnlev = length(pyr);\n\n% multiresolution blending\nfor i = 1:N\n % construct pyramid from each input image\n\tpyrW = gaussian_pyramid_(W(:,:,i));\n\tpyrI = laplacian_pyramid_(I(:,:,:,i));\n \n % blend\n for l = 1:nlev\n w = repmat(pyrW{l},[1 1 3]);\n pyr{l} = pyr{l} + w.*pyrI{l};\n end\nend\n\n% reconstruct\nR = reconstruct_laplacian_pyramid_(pyr);\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% contrast measure\nfunction C = contrast(I)\nh = [0 1 0; 1 -4 1; 0 1 0]; % laplacian filter\nN = size(I,4);\nC = zeros(size(I,1),size(I,2),N);\nfor i = 1:N\n mono = rgb2gray(I(:,:,:,i));\n C(:,:,i) = abs(imfilter(mono,h,'replicate'));\nend\n\n% saturation measure\nfunction C = saturation(I)\nN = size(I,4);\nC = zeros(size(I,1),size(I,2),N);\nfor i = 1:N\n % saturation is computed as the standard deviation of the color channels\n R = I(:,:,1,i);\n G = I(:,:,2,i);\n B = I(:,:,3,i);\n mu = (R + G + B)/3;\n C(:,:,i) = sqrt(((R - mu).^2 + (G - mu).^2 + (B - mu).^2)/3);\nend\n\n% well-exposedness measure\nfunction C = well_exposedness(I)\nsig = .2;\nN = size(I,4);\nC = zeros(size(I,1),size(I,2),N);\nfor i = 1:N\n R = exp(-.5*(I(:,:,1,i) - .5).^2/sig.^2);\n G = exp(-.5*(I(:,:,2,i) - .5).^2/sig.^2);\n B = exp(-.5*(I(:,:,3,i) - .5).^2/sig.^2);\n C(:,:,i) = R.*G.*B;\nend\n\n\n", "meta": {"author": "mahmoudnafifi", "repo": "Exposure_Correction", "sha": "01300c3ff186123d405141202f8201ebd59965fa", "save_path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction", "path": "github-repos/MATLAB/mahmoudnafifi-Exposure_Correction/Exposure_Correction-01300c3ff186123d405141202f8201ebd59965fa/exFusion/exposure_fusion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.641677156452735}} {"text": "function [eigVec, eigVal] = dtiSplitTensor(tensor)\n% Derive eigenvector and eigenvalues from the volume of tensor data \n%\n% [eigVec, eigVal] = dtiSplitTensor(tensor)\n% \n% The input tensor array is in XxYxZx6xN format \n% The order of the value in the 4th dimension is [Dxx, Dyy, Dzz, Dxy, Dxz, Dyz])\n% \n% The routine returns a XxYxZx3x3xN volume of eigVec \n% and a the XxYxZx3xN volume of eigVal arrays\n% \n% X,Y,Z are positions in the volume\n% N is the number of subjects.\n%\n% SEE ALSO: dtiRebuildTensor\n%\n% HISTORY:\n% 2003.12.08 ASH (armins@stanford.edu) Wrote it.\n% 2004.02.03 DTM (merget@cs.stanford.edu) Sort eigVal from high to low\n% 2004.02.17 ASH: added extra dimension for subjects\n% 2005.01.06 ASH: truly added extra dimension for subjects\n%\n% The code is implemented in the mex file dtiSplitTensor.c. If you don't\n% have a that file compiled for you system, then the (very slow) code below\n% will be executed. In one test, the following code ran in 2.85 minutes,\n% and the compiled version ran in about 11 seconds.\n%\n% (c) Stanford VISTA Team 2003\n\ndisp('This function is mexified for speed- compile dtiSplitTensor.c.');\n\nsz = size(tensor);\nif (length(sz)<5),\n sz =[sz, 1];\nend\n\n% vec = zeros([sz(1:3), 3, 3, sz(5)]);\n% val = zeros([sz(1:3), 3, sz(5)]);\n\nh = mrvWaitbar(0, 'Computing tensors...');\nfor(x=1:sz(1))\n for(y=1:sz(2))\n for(z=1:sz(3))\n for(j=1:sz(5))\n D = [tensor(x, y, z, 1, j), tensor(x, y, z, 4, j), tensor(x, y, z, 5, j);\n tensor(x, y, z, 4, j), tensor(x, y, z, 2, j), tensor(x, y, z, 6, j);\n tensor(x, y, z, 5, j), tensor(x, y, z, 6, j), tensor(x, y, z, 3, j)];\n [vec, val] = eig(D);\n [val2, order] = sort(-diag(val));\n eigVec(x, y, z, :, :, j) = vec(:, order);\n eigVal(x, y, z, :, j) = -val2;\n end\n end\n end\n mrvWaitbar(x/sz(1),h);\nend\nclose(h);\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/src/dtiSplitTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6416559950720292}} {"text": "function T = build_toep( c, k, n )\n%\n% T = build_toep( c, k, n );\n%\n% Given:\n% c - the nonzero part of a central column of a banded Toeplitz\n% matrix\n% k - index of c containing the diagonal element of T\n% n - dimension of the banded Toeplitz matrix\n%\n% The banded Toeplitz matrix is constructed explicitly.\n%\n\n% J. Nagy 2/11/02\n\nm = length( c );\n\ncol = zeros(n,1);\nrow = col';\ncol(1:m-k+1,1) = c(k:m);\nrow(1,1:k) = c(k:-1:1)';\nT = toeplitz( col, row );\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/private/build_toep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.754914997895581, "lm_q1q2_score": 0.6416559882828426}} {"text": "function af = naca5gen(iaf)\n% \n% \"naca5gen\" Generates the NACA 5 digit airfoil coordinates with desired no.\n% of panels (line elements) on it.\n% Author : Divahar Jayaraman (j.divahar@yahoo.com)\n% \n% INPUTS-------------------------------------------------------------------\n% iaf.designation = NACA 5 digit designation (eg. '23012') - STRING !\n% iaf.n = no of panels (line elements) PER SIDE (upper/lower)\n% iaf.HalfCosineSpacing = 1 for \"half cosine x-spacing\" \n% = 0 to give \"uniform x-spacing\"\n% iaf.wantFile = 1 for creating airfoil data file (eg. 'naca2412.dat')\n% = 0 to suppress writing into a file\n% iaf.datFilePath = Path where the data file has to be created\n% (eg. 'af_data_folder/naca5digitAF/') \n% use only forward slash '/' (Just for OS portability)\n% \n% OUTPUTS------------------------------------------------------------------\n% Data:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n% af.x = x cordinate (nx1 array)\n% af.z = z cordinate (nx1 array)\n% af.xU = x cordinate of upper surface (nx1 array)\n% af.zU = z cordinate of upper surface (nx1 array)\n% af.xL = x cordinate of lower surface (nx1 array)\n% af.zL = z cordinate of lower surface (nx1 array)\n% af.xC = x cordinate of camber line (nx1 array)\n% af.zC = z cordinate of camber line (nx1 array)\n% af.name = Name of the airfoil\n% af.header = Airfoil name ; No of panels ; Type of spacing\n% (eg. 'NACA23012 : [50 panels,Uniform x-spacing]')\n% \n% \n% File:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n% First line : Header eg. 'NACA23012 : [50 panels,Half cosine x-spacing]'\n% Subsequent lines : (2*iaf.n+1) rows of x and z values\n% \n% Typical Inputs:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n% iaf.designation='23012';\n% iaf.n=56;\n% iaf.HalfCosineSpacing=1;\n% iaf.wantFile=1;\n% iaf.datFilePath='./'; % Current folder\n% iaf.is_finiteTE=0;\n\n\n% % [[Calculating key parameters-----------------------------------------]]\ncld=str2num(iaf.designation(1))*(3/2)/10;\np=0.5*str2num(iaf.designation(2:3))/100;\nt=str2num(iaf.designation(4:5))/100;\n\na0= 0.2969;\na1=-0.1260;\na2=-0.3516;\na3= 0.2843;\n\nif iaf.is_finiteTE ==1\n a4=-0.1015; % For finite thick TE\nelse\n a4=-0.1036; % For zero thick TE\nend\n\n% % [[Giving x-spacing---------------------------------------------------]]\nif iaf.HalfCosineSpacing==1\n beta=linspace(0,pi,iaf.n+1)';\n x=(0.5*(1-cos(beta))); % Half cosine based spacing\n iaf.header=['NACA' iaf.designation ' : [' num2str(2*iaf.n) 'panels,Half cosine x-spacing]'];\nelse\n x=linspace(0,1,iaf.n+1)';\n iaf.header=['NACA' iaf.designation ' : [' num2str(2*iaf.n) 'panels,Uniform x-spacing]'];\nend\n\nyt=(t/0.2)*(a0*sqrt(x)+a1*x+a2*x.^2+a3*x.^3+a4*x.^4);\n\nP=[ 0.05 0.1 0.15 0.2 0.25 ];\nM=[ 0.0580 0.1260 0.2025 0.2900 0.3910];\nK=[361.4 51.64 15.957 6.643 3.230 ];\n\nm=spline(P,M,p);\nk1=spline(M,K,m);\n\nxc1=x(find(x<=p));\nxc2=x(find(x>p));\nxc=[xc1 ; xc2];\n\nif p==0\n xu=x;\n yu=yt;\n\n xl=x;\n yl=-yt;\n \n zc=zeros(size(xc));\nelse\n yc1=(1/6)*k1*( xc1.^3-3*m*xc1.^2+m^2*(3-m)*xc1 );\n yc2=(1/6)*k1*m^3*(1-xc2);\n zc=(cld/0.3)*[yc1 ; yc2];\n\n dyc1_dx=(1/6)*k1*( 3*xc1.^2-6*m*xc1+m^2*(3-m) );\n dyc2_dx=repmat((1/6)*k1*m^3,size(xc2));\n dyc_dx=[dyc1_dx ; dyc2_dx];\n theta=atan(dyc_dx);\n\n xu=x-yt.*sin(theta);\n yu=zc+yt.*cos(theta);\n\n xl=x+yt.*sin(theta);\n yl=zc-yt.*cos(theta);\nend\naf.name=['NACA ' iaf.designation];\n\naf.x=[flipud(xu) ; xl(2:end)];\naf.z=[flipud(yu) ; yl(2:end)];\n\nindx1=1:min( find(af.x==min(af.x)) ); % Upper surface indices\nindx2=min( find(af.x==min(af.x)) ):length(af.x); % Lower surface indices\naf.xU=af.x(indx1); % Upper Surface x\naf.zU=af.z(indx1); % Upper Surface z\naf.xL=af.x(indx2); % Lower Surface x\naf.zL=af.z(indx2); % Lower Surface z\n\naf.xC=xc;\naf.zC=zc;\n\nlecirFactor=0.8;\naf.rLE=0.5*(a0*t/0.2)^2;\n\nle_offs=0.5/100;\ndyc_dx_le=(1/6)*k1*( 3*le_offs.^2-6*m*le_offs+m^2*(3-m) );\ntheta_le=atan(dyc_dx_le);\naf.xLEcenter=af.rLE*cos(theta_le);\naf.yLEcenter=af.rLE*sin(theta_le);\n\n% % [[Writing iaf data into file------------------------------------------]]\nif iaf.wantFile==1\n F1=iaf.header;\n F2=num2str([af.x af.z]);\n F=strvcat(F1,F2);\n fileName=[iaf.datFilePath 'naca' iaf.designation '.dat'];\n dlmwrite(fileName,F,'delimiter','')\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/23241-naca-5-digit-airfoil-generator/naca5gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6416559656157486}} {"text": "function [g,B,mu]=BaylissTapering(sidelobedB,N,xyPoints,a)\n%%BAYLISSTAPERING The Bayliss tapering is a set of complex amplitude\n% weights for a continuous circular (narrowband) aperture antenna\n% that will form a difference beam (odd symmetry about an axis)\n% and hold the four closest sidelobes to a desired level. Such a\n% tapering can be discretized and applied to the elements in a\n% circular phased array (An array of antenna elements can be\n% viewed as a discrete approximation to a continuous aperture).\n% This function will provide the tapering values at a set of\n% discrete points given by xyPoints (the origin is taken to be the\n% center of the aperture). The radius of the aperture can either\n% be provided or is taken as value of the farthest point provided.\n% This function also returns coefficients for one to efficiently\n% compute the tapering at points on their own. If xyPoints is\n% empty, only the coefficients are returned. The difference axis\n% generated by this function is the y-axis.\n%\n%INPUTS: sidelobedB The number of decibels of the ratio of the close-in\n% sidelobe voltages to the main lobe voltage. This must be a\n% negative number. A typical value is -30.\n% N The Bayliss tapering is computed using a certain number of\n% terms. Using too many terms can be undesirable as edge\n% illumination increases, as noted in [1]. If this parameter is\n% omitted or an empty matrix is passed, then the default of 17\n% is used. In [1], it is suggested that N be chosen to be\n% <2*a/lambda, where a is the radius of the aperture and\n% lambda the wavelength.\n% xyPoints A 2XnumPoints set of numPoints points in the aperture plane\n% at which the tapering values should be evaluated. If this\n% parameter is omitted or an empty matrix is passed, then an\n% empty matrix is returned for the output g. The center of the\n% aperture is taken to be the origin. \n% a The radius of the aperture. Tapering weights for points in\n% xyPoints outside of the aperture are taken to be zero. If\n% this parameter is omitted or an empty matrix is passed, then\n% the radius is taken to be the distance of the farthest point\n% from the origin in xyPoints.\n%\n%OUTPUTS: g The NX1 set of discretized Bayliss tapering values evaluated at\n% the points given in xyPoints. If xyPoints is omitted, then this\n% is an empty matrix. All Bayliss tapering values are imaginary.\n% The values are not normalized.\n% B, mu These two outputs can be used to evaluate the bayliss tapering\n% values at arbitrary points. B is an NX1 vector and mu is an\n% (N+1)X1 vector. Given a 2X1 point xy and a radius of the\n% aperture, set the normalized radius to p=pi*norm(xy)/a and\n% the Bayliss tapering weight g at the point is\n% g=(xy(1)/norm(xy))*sum(B.*besselj(1,mu(1:N)*p));\n%\n%This function implements the algorithm of [1] using the polynomial\n%interpolation values in the table below Figure 4. This approximation means\n%that low sidelobe patterns (-45 dB and below) will not have good fidelity\n%sidelobes.\n%\n%EXAMPLE 1:\n%Here, we evaluate the tapering values for 30dB down on a fine grid of\n%points to plot what the imaginary part of the tapering weights looks\n%like. The real part is all zero.\n% numPoints=300;\n% points1D=linspace(-1,1,numPoints);\n% [X,Y]=meshgrid(points1D,points1D);\n% %The Bayliss tapering weights, evaluated across the aperture. Points\n% %outside the aperture are assigned a weight of 0. All Bayliss weights are\n% %imaginary.\n% xyPoints=[X(:)';Y(:)'];\n% a=1;%Aperture radius=1.\n% gBayliss=BaylissTapering(-30,17,xyPoints,a);\n% gBayliss=reshape(gBayliss,numPoints,numPoints);\n% \n% figure(1)\n% clf\n% surface(X,Y,imag(gBayliss),'EdgeColor','None')\n% colormap(jet(256))\n% colorbar()\n% view(45,45)\n% light()\n% axis square\n% h1=xlabel('x');\n% h2=ylabel('y');\n% title('Bayliss Tapering Weight')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%EXAMPLE 2:\n%Here, we consider the array response when using tapering values for 30dB\n%sidelobes on a circular array with lambda/2 spacing between elements.\n%First, we create a circular array. The element locations are given in\n%terms of the wavelength lambda, so lambda will not appear in the\n%equations for the sum beam.\n% %First, we create a circular array. The element locations are given in\n% %terms of the wavelength lambda, so lambda will not appear in the\n% %equations for the sum beam.\n% xyVals=getShaped2DLattice([25;25],'circular');\n% %Get the tapering. It is -30dB and nBar=17;\n% N=17;\n% sidelobedB=-30;\n% g=BaylissTapering(sidelobedB,N,xyVals);\n% \n% %The tapering matrix\n% T=diag(g);\n% \n% %Now, display the response with the tapering. We normalize it with\n% %respect to the peak value and plot the result in decibels (power).\n% [Rsp,U,V]=standardUVBeamPattern(T,xyVals,'NormPowGain');\n% \n% figure(1)\n% clf\n% surface(U,V,10*log10(Rsp),'EdgeColor','None')\n% colormap(jet(256));\n% caxis([-40,0])\n% colorbar()\n% view(45,30)\n% light()\n% axis square\n% h1=xlabel('u');\n% h2=ylabel('v');\n% h3=zlabel('Response, Decibels');\n% title('Bayliss Weighted Array Response')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h3,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%Note that the difference pattern produced has a line of symmetry about\n%the y axis. To flip the symmetry axis (e.g. for a vertical difference\n%beam), then simply use g=BaylissTapering(sidelobedB,N,flipud(xyVals));\n%\n%REFERENCES:\n%[1] E. T. Bayliss, \"Design of monopulse antenna difference patterns with\n% low sidelobes,\" The Bell System Technical Journal, vol. 47, no. 5, pp.\n% 623-650, May-Jun. 1968.\n%\n%August 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(N))\n N=17; \nend\n\n%The definition og the mu_m terms in Equation 6 in [1]. The first zero is\n%the one indexed by 0 in the paper. Thus, this goes from mu_0 to mu_N.\nmu=BesselJDerivZeros(1,N+1)/pi;\n\n%This holds the coefficients for the interpolating polynomials given below\n%Figure 4 in [1]. The polynomials all take the desired sidelobe level in\n%decibels as an input parameter. The first row is for the term A, which\n%is a translation of the SNR parameter to a parameter in the paper. The\n%next four rows are xi_1 to xi_4, which are the locations of the first four\n%zeroes in the modified pattern. The final row is for p_0, which is related\n%to the point at which the peak of the asymptotic difference pattern=1.\npolyCoeffTable=[0.30387530,-0.05042922,-0.00027989,-0.00000343,-0.00000002;\n 0.98583020,-0.03338850, 0.00014064, 0.00000190, 0.00000001;\n 2.00337487,-0.01141548, 0.00041590, 0.00000373, 0.00000001;\n 3.00636321,-0.00683394, 0.00029281, 0.00000161, 0;\n 4.00518423,-0.00501795, 0.00021735, 0.00000088, 0;\n 0.47972120,-0.01456692,-0.00018739,-0.00000218,-0.00000001];\n\nA =polyCoeffTable(1,1)+sidelobedB*(polyCoeffTable(1,2)+sidelobedB*(polyCoeffTable(1,3)+sidelobedB*(polyCoeffTable(1,4)+sidelobedB*polyCoeffTable(1,5))));\nxi1=polyCoeffTable(2,1)+sidelobedB*(polyCoeffTable(2,2)+sidelobedB*(polyCoeffTable(2,3)+sidelobedB*(polyCoeffTable(2,4)+sidelobedB*polyCoeffTable(2,5))));\nxi2=polyCoeffTable(3,1)+sidelobedB*(polyCoeffTable(3,2)+sidelobedB*(polyCoeffTable(3,3)+sidelobedB*(polyCoeffTable(3,4)+sidelobedB*polyCoeffTable(3,5))));\nxi3=polyCoeffTable(4,1)+sidelobedB*(polyCoeffTable(4,2)+sidelobedB*(polyCoeffTable(4,3)+sidelobedB*(polyCoeffTable(4,4)+sidelobedB*polyCoeffTable(4,5))));\nxi4=polyCoeffTable(5,1)+sidelobedB*(polyCoeffTable(5,2)+sidelobedB*(polyCoeffTable(5,3)+sidelobedB*(polyCoeffTable(5,4)+sidelobedB*polyCoeffTable(5,5))));\n%p0 =polyCoeffTable(6,1)+sidelobedB*(polyCoeffTable(6,2)+sidelobedB*(polyCoeffTable(6,3)+sidelobedB*(polyCoeffTable(6,4)+sidelobedB*polyCoeffTable(6,5))));\n\nZ=zeros(N+1,1);\n%Equation 15\nZ(1)=0;%The Z(0) term\n%Now, the moved zeros\nZ(2)=xi1;\nZ(3)=xi2;\nZ(4)=xi3;\nZ(5)=xi4;\nfor k=5:N\n %The location of the non-moved zeros as given by Equation 13.\n Z(k+1)=sqrt(A^2+k^2);\nend\n%Equation 16 in [1].\nsigma=mu(N+1)/Z(N+1);\n\n%No normalization is performed. We just use C=1.\nC=1;\n\nB=zeros(N,1);%The first entry is B_0\n%Equation 24\nfor m=0:(N-1)\n num=prod(1-(mu(m+1)./(sigma*Z(2:N))).^2);\n denom=prod(1-(mu(m+1)./mu([1:m,(m+2):N])).^2);\n \n B(m+1)=-(C*1j*2*mu(m+1)^2/besselj(1,pi*mu(m+1)))*num/denom;\nend\n\n%If discretized tapering values are desired.\nif(nargin>2&&~isempty(xyPoints))\n numPoints=size(xyPoints,2);\n \n if(nargin<4||isempty(a))\n %The maximum distance from the origin to a point is taken to be the\n %radius of the aperture.\n a2=max(sum(xyPoints.^2,1));\n a=sqrt(a2);\n end\n \n g=zeros(numPoints,1);\n for curPoint=1:numPoints\n rho2=sum(xyPoints(:,curPoint).^2,1);\n\n if(rho2<=a2)\n rho=sqrt(rho2);\n %The normalized radius at this point.\n p=pi*rho/a;\n \n x=xyPoints(1,curPoint);\n cosVal=x/rho;\n \n %Equation 7 in [1].\n g(curPoint)=cosVal*sum(B.*besselj(1,mu(1:N)*p));\n end\n end\nelse%If no tapering values are requested, return an empty matrix.\n g=[];\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Signal_Processing/Array_Processing/Tapering/BaylissTapering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6416450254225969}} {"text": "% SP_HCURL_ERROR: Evaluate the error in H(curl) norm.\n%\n% [errhcurl, errl2, errcurl] = sp_hcurl_error (space, msh, u, uex, curluex);\n%\n% INPUT:\n%\n% space: struct defining the space of discrete functions (see sp_vector/sp_evaluate_col)\n% msh: struct defining the domain partition and the quadrature rule (see msh_cartesian/msh_evaluate_col)\n% u: vector of dof weights\n% uex: function handle to evaluate the exact solution\n% curluex: function handle to evaluate the curl of the exact solution\n%\n% OUTPUT:\n%\n% errhcurl: error in H(curl) norm\n% errl2: error in L^2 norm\n% errcurl: error of the curl in L^2 norm\n%\n% Copyright (C) 2010 Carlo de Falco, Rafael Vazquez\n% Copyright (C) 2011, 2015 Rafael Vazquez\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with Octave; see the file COPYING. If not, see\n% .\n\nfunction [errhcurl, errl2, errcurl] = sp_hcurl_error (sp, msh, u, uex, curluex)\n\n w = msh.quad_weights(:) .* msh.jacdet(:);\n\n for idim = 1:msh.rdim\n x{idim} = reshape (msh.geo_map(idim,:,:), msh.nqn*msh.nel, 1);\n end\n \n curl_valex = feval (curluex, x{:});\n errcurl = 0;\n \n switch (msh.rdim)\n case {2}\n valnum = zeros (msh.nqn, msh.nel);\n for ish = 1:sp.nsh_max\n valnum = valnum + ...\n reshape (sp.shape_function_curls(:, ish, :), msh.nqn, msh.nel) .* ...\n u(repmat(sp.connectivity(ish, :), msh.nqn, 1));\n end\n errcurl = errcurl + sum((valnum(:) - curl_valex).^2 .* w);\n\n case{3}\n for idir = 1:msh.rdim\n valnum = zeros (msh.nqn, msh.nel);\n for ish = 1:sp.nsh_max\n valnum = valnum + ...\n reshape (sp.shape_function_curls(idir, :, ish, :), msh.nqn, msh.nel) .* ...\n\t reshape (u(repmat(sp.connectivity(ish,:), msh.nqn, 1)), msh.nqn, msh.nel);\n end\n valex = curl_valex(idir, :);\n errcurl = errcurl + sum ((valnum(:) - valex(:)).^2 .* w);\n end\n end\n\n errl2 = sp_l2_error (sp, msh, u, uex);\n errhcurl = sqrt (errl2^2 + errcurl);\n errcurl = sqrt (errcurl);\n\nend", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/sp_hcurl_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6416450182123473}} {"text": "% Fig. 2.15 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\ng=9.81; % m/sec^2\nL=1; % m \nm=1; % Kg\nr2d=57.295; % radians to degrees\n\nnum = 1/(m*L^2);\nden = [1 0 g/L];\nt=0:.02:10;\n\ny = step(num,den,t); % output in radians\nplot(t,r2d*y),grid\nxlabel('Time (sec)')\nylabel('Pendulum angle \\theta (deg)')\ntitle('Fig. 2.15')\nnicegrid\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig2_15.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6414869381788658}} {"text": "function [mmps2] = uGal2mmps2(uGal)\n% Convert acceleration from microgals to millimeters per square second. \n% Chad A. Greene 2012\nmmps2 = uGal*1e-5; \nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/uGal2mmps2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6414556254935972}} {"text": "%PAY Joint forces from payload for SerialLink objects\n%\n% Calculates the joint loads due to a payload for SerialLink objects,\n% It uses the formula Q = J'w, where w is a wrench vector applied at\n% the end effector, w = [Fx Fy Fz Mxx Myy Mzz]'. The Jacobian can be\n% supplied or computed by RTB\n%\n% Copyright (C) Bryan Moutrie, 2013-2014\n% Licensed under the GNU Lesser General Public License\n% see full file for full statement\n%\n% This file requires file(s) from The Robotics Toolbox for MATLAB (RTB)\n% by Peter Corke (www.petercorke.com), see file for statement\n%\n% Syntax:\n% (1) tauP = pay(w, J)\n% (2) tauP = robot.pay(q, w, f)\n%\n% (1) Uses a supplied Jacobian\n% (2) Calculates the Jacobian for joint configuration q in frame f,\n% using either robot.jacob0(q) or robot.jacob0(q) for Jacobian\n%\n% Outputs:\n% tauP : Generalised joint force/torques\n%\n% Inputs:\n% robot : SerialLink object with n joints\n% w : Wrench vector [Fx Fy Fz Mxx Myy Mzz]' in same frame as J\n% J : Jacobian (supplied): 6-by-n or 6-by-n-m for trajectory\n% q : Joint row vector, or trajectory matrix of joint row vectors\n% f : '0' for world frame, 'n' for end-effector frame\n%\n% See also jacob0, jacobn, paycap, SerialLink.payload\n\n% LICENSE STATEMENT:\n%\n% This file is part of pHRIWARE.\n% \n% pHRIWARE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as \n% published by the Free Software Foundation, either version 3 of \n% the License, or (at your option) any later version.\n%\n% pHRIWARE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public \n% License along with pHRIWARE. If not, see .\n%\n% RTB LIBRARY:\n%\n% Copyright (C) 1993-2014, by Peter I. Corke\n% http://www.petercorke.com\n% Released under the GNU Lesser General Public license\n\nfunction tauP = pay(varargin)\n\nif length(varargin) == 3\n w = varargin{2};\n J = varargin{3};\n n = size(J,2);\nelseif length(varargin) == 4\n robot = varargin{1};\n q = varargin{2};\n w = varargin{3};\n f = varargin{4};\n n = robot.n;\n J = zeros(6,n,size(q,1));\n if f == '0'\n for i= 1: size(q,1)\n J(:,:,i) = robot.jacob0(q(i,:));\n end\n elseif f == 'n'\n for i= 1: size(q,1)\n J(:,:,i) = robot.jacobn(q(i,:));\n end\n end\nend\n\ntauP = -reshape(J(:,:)'*w,n,[])';\n\nend\n\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/contrib/pHRIWARE/@SerialLinked/pay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6414556244273654}} {"text": "% This example shows a simple comparison of two different algorithm for tensor completion:\n%\n% -- ALS completion\n% -- Riemannian tensor completion (RTTC)\n%\n% in a very similar comparison as Figure 5.2. in\n% \n% Michael Steinlechner, Riemannian optimization for high-dimensional tensor completion,\n% Technical report, March 2015, revised December 2015. \n% To appear in SIAM J. Sci. Comput. \n%\n% See this report for more details about the algorithms and the setup. \n% The different to the therein described setup is only a reduced problem size (d, n, r) so \n% that it takes less time to compute the results.\n\n% TTeMPS Toolbox. \n% Michael Steinlechner, 2013-2016\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\nrng(13);\nd = 10;\n\nranks = [4, 6, 8];\n\ncost = cell(1,length(ranks));\ntest = cell(1,length(ranks));\nstats = cell(1,length(ranks));\n\nfor j = 1:length(ranks)\n r = ranks(j);\n rr = [1, r*ones(1,d-1), 1];\n\n nn = 20;\n n = nn*ones(1,d);\n\n opts = struct('maxiter', 50, 'tol', 0, 'reltol',0, 'gradtol',0);\n opts_tt = struct('maxiter', 60, 'tol', 0, 'reltol',0, 'gradtol',0);\n \n dof = d*nn*r^2;\n sizeOmega = 10*dof;\n sizeGamma = sizeOmega;\n \n Omega = makeOmegaSet_mod(n, sizeOmega);\n Gamma = makeOmegaSet_mod(n, sizeGamma);\n\n A = TTeMPS_rand( rr, n );\n A = 1/norm(A) * A;\n \n A_Omega = A(Omega);\n A_Gamma = A(Gamma);\n\n\n X0 = TTeMPS_rand( rr, n );\n X0 = 1/norm(X0) * X0;\n X0 = orthogonalize( X0, X0.order );\n\n [X,cost_als{j},test_als{j},stats_als{j}] = completion_als( A_Omega, Omega, A_Gamma, Gamma, X0, opts );\n [X,cost_tt{j},test_tt{j},stats_tt{j}] = completion_orth( A_Omega, Omega, A_Gamma, Gamma, X0, opts_tt );\nend\n\nl = lines(7);\nmidred = l(end,:);\ndarkred = brighten(l(end,:),-0.7);\nlightred = brighten(midred,0.7);\n\nmidblue = l(1,:)\ndarkblue = brighten(midblue,-0.7);\nlightblue = brighten(midblue,0.7);\n\nsubplot(1,2,1)\nsemilogy( test_als{1}(1:end),'color',darkred,'linewidth',2)\nhold on\nsemilogy( test_als{2}(1:end),'color',midred,'linewidth',2)\nsemilogy( test_als{3}(1:end),'color',lightred,'linewidth',2)\nsemilogy( test_tt{1},'--','color',darkblue,'linewidth',2)\nsemilogy( test_tt{2},'--','color',midblue,'linewidth',2)\nsemilogy( test_tt{3},'--','color',lightblue,'linewidth',2)\n\nxlabel('Iterations')\nylabel('Error on test set')\nlegend({'ALS, rank 4','ALS, rank 6', 'ALS, rank 8','RTTC, rank 4', 'RTTC, rank 6', 'RTTC, rank 8'})\n\n\nsubplot(1,2,2)\nloglog( stats_als{1}.time(1:end), test_als{1}(1:end),'color',darkred,'linewidth',2)\nhold on\nloglog( stats_als{2}.time(1:end), test_als{2}(1:end),'color',midred,'linewidth',2)\nloglog( stats_als{3}.time(1:end), test_als{3}(1:end),'color',lightred,'linewidth',2)\nloglog( stats_tt{1}.time, test_tt{1},'--','color',darkblue,'linewidth',2)\nloglog( stats_tt{2}.time, test_tt{2},'--','color',midblue,'linewidth',2)\nloglog( stats_tt{3}.time, test_tt{3},'--','color',lightblue,'linewidth',2)\nxlim([1e-1,1e3])\n\nxlabel('Time [s]')\nylabel('Error on test set')\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/examples/ex_completion_compare_als_riemann.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6414286548561542}} {"text": "function c=ref_dftiv(f)\n%REF_DFT Reference Discrete Fourier Transform Type IV\n% Usage: c=ref_dftiv(f);\n%\n% This is highly experimental!\n\nL=size(f,1);\nW=size(f,2);\n\n% Create weights.\nw=sqrt(1/L);\n\n% Create transform matrix.\nF=zeros(L);\n\nfor m=0:L-1\n for n=0:L-1\n F(m+1,n+1)=w*exp(2*pi*i*(m+.5)*(n+.5)/L);\n end;\nend;\n\n% Compute coefficients.\nc=F'*f;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_dftiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6414145406924081}} {"text": "function news ( filename, thresh )\n\n%*****************************************************************************80\n%\n%% NEWS demonstrates the NEWS stencil for edge detection.\n%\n% Discussion:\n%\n% Given a black and white image A, which we regard as an M by N array\n% of pixels, we want to produce an array E of the same shape, which\n% contains information describing the location of edges.\n%\n% A simple algorithm for trying to detect edges in an array that\n% represents an image is the NEWS scheme. For each pixel A(C),\n% we consider its North, East, West, and South pixel neighbors. The\n% indexing of arrays and images do not correspond, so we will use\n% these directions instead:\n%\n% A(N)\n% |\n% |\n% A(W)---A(C)---A(E)\n% |\n% |\n% A(S)\n%\n% Entry E(C) of the edge array will be computed by\n%\n% E(C) = abs ( A(N) - A(S) ) + abs ( A(E) - A(W) )\n%\n% Pixels of A that represent edges will tend to have high values\n% of E, while pixels that are interior to a region of roughly the\n% same shade will tend to have low values.\n%\n% Thus, an edge detection scheme would use the NEWS stencil to\n% compute the E array, determine E_MAX, the maximum entry in E,\n% choose some threshold value E_THRESH, and declare pixel A(I,J)\n% to be associated with an edge whenever E(I,J) is greater than E_THRESH.\n%\n% In this program, we demonstrate the NEWS stencil using a PGM\n% grayscale image of coins. At the end, we use the edge information\n% to produce a color image in which the edges of the coins have been\n% outlined in red.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string FILENAME, the name of the file containing the image.\n% The image should be a grayscale image, not color!\n%\n% Input, integer THRESH, the threshhold for the edge detection.\n% 0 <= THRESH <= 255 is required. A value of 50 is the default.\n% Higher values are more selective.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NEWS\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Demonstrate the NEWS stencil for edge detection\\n' );\n fprintf ( 1, ' in images.\\n' );\n\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n filename = input ( 'Enter the name of the image file: ' );\n end\n\n if ( nargin < 2 )\n thresh = 50;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Reading \"%s\".\\n', filename );\n%\n% Read the file into \"A\".\n%\n a = imread ( filename );\n%\n% Get the size of the array.\n% We'll use it later when we add a border to the data.\n%\n [ m, n ] = size ( a );\n%\n% Display the input image.\n%\n figure ( 1 )\n imshow ( a );\n title ( 'Initial image' )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 1:\\n' );\n fprintf ( 1, ' This is the original gray scale image.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press return.\\n' );\n pause\n%\n% For neatness, we add a border of zeros to the image,\n% then fill in the border by copying the nearby original values.\n% This will be our M+2 by N+2 data array B.\n%\n b = zeros ( m + 2, n + 2 );\n b(2:m+1,2:n+1) = double ( a );\n\n b(1, 2:n+1) = b(2,2:n+1);\n b(m+2,2:n+1) = b(m+1,2:n+1);\n\n b(2:m+1,1) = b(2:m+1,2);\n b(2:m+1,n+2) = b(2:m+1,n+1);\n\n b(1,1) = ( b(1,2) + b(2,1) ) / 2.0;\n b(m+2,1) = ( b(m+2,2) + b(m+1,1) ) / 2.0;\n b(1,n+2) = ( b(1,n+1) + b(2,n+2) ) / 2.0;\n b(m+2,n+2) = ( b(m+2,n+1) + b(m+1,n+2) ) / 2.0;\n\n figure ( 2 )\n imshow ( uint8 ( b ) );\n title ( 'Same image, with a 1-pixel border.' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 2:\\n' );\n fprintf ( 1, ' We have added a border of 1-pixel thickness.\\n' );\n fprintf ( 1, ' Now all the pixels in the original picture \\n' );\n fprintf ( 1, ' have a 3x3 pixel neighborhood.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press return.\\n' );\n pause\n%\n% Apply the NEWS Operator. We don't process the boundary pixels.\n%\n% The stencil we use is:\n%\n% | 0 +1 0 | | 0 0 0 |\n% | 0 0 0 | + | -1 0 +1 |\n% | 0 -1 0 | | 0 0 0 |\n%\n e(2:m+1,2:n+1) = abs ( - b(1:m,2:n+1) + b(3:m+2,2:n+1) ) ...\n + abs ( - b(2:m+1,1:n) + b(2:m+1,3:n+2) );\n%\n% The values in E must be rescaled to run from 0 to 255\n% if we are going to display them.\n%\n emin = min ( min ( e ) );\n emax = max ( max ( e ) );\n e = round ( 255 * ( e - emin ) / ( emax - emin ) );\n\n figure ( 3 )\n imshow ( uint8 ( e ) );\n title ( 'All the E data.' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 3:\\n' );\n fprintf ( 1, ' We computed the value of E for each pixel,\\n' );\n fprintf ( 1, ' and scaled it to [0,255].\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press return.\\n' );\n pause\n%\n% Threshold the data.\n%\n e = 255 * ( thresh < e );\n\n figure ( 4 )\n imshow ( uint8 ( e ) );\n title ( 'E data above the threshold.' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 4:\\n' );\n fprintf ( 1, ' We zeroed all the pixels with a value of E\\n' );\n fprintf ( 1, ' less than the threshold of %d\\n', thresh )\n fprintf ( 1, ' so the edges show up better.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press return.\\n' );\n pause\n%\n% Reverse the image.\n%\n e_reverse = 255 - e;\n\n figure ( 5 )\n imshow ( uint8 ( e_reverse ) );\n title ( 'E data above the threshold (reverse video).' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 5:\\n' );\n fprintf ( 1, ' Black lines on white background are MUCH easier\\n' );\n fprintf ( 1, ' to read.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Press return.\\n' );\n pause\n%\n% Make an RGB image of the gray picture, with red highlights.\n%\n e2 = max ( e(2:m+1,2:n+1), double ( a ) );\n a2 = uint8 ( e2 );\n\n r = a2;\n g = a;\n b = a;\n\n rgb = cat ( 3, r, g, b );\n\n figure ( 6 )\n imshow ( rgb );\n title ( 'Original gray data, with edges in red.' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Figure 6:\\n' );\n fprintf ( 1, ' This is actually an RGB \"color\" image.\\n' );\n fprintf ( 1, ' This way, we can show the detected edges in red.\\n' );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NEWS:\\n' );\n fprintf ( 1, ' Normal end of execution.\\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/image_edge/news.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.6413016844732184}} {"text": "function node_rhs = rhs ( node_num, node_xy )\n\n%*****************************************************************************80\n%\n%% RHS gives the right-hand side of the differential equation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM),\n% the coordinates of the points.\n%\n% Output, real NODE_RHS(NODE_NUM,1), the value of the\n% right hand side function at the points.\n%\n node_rhs = zeros ( node_num, 1 );\n\n for j = 1 : node_num\n z = 4.0 - sqrt ( ( node_xy(1,j) - 2.0 ).^2 + ( node_xy(2,j) - 2.0 ).^2 );\n node_rhs(j,1) = max ( z, 0.0 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_poisson_sparse_baffle/rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6413016776764763}} {"text": "function [dose_ratio] = dicomrt_doseratio(doseone,dosetwo)\n% dicomrt_doseratio(doseone,dosetwo)\n%\n% Calculate dose ratio between two 3D matrices\n%\n% doseone and dosetwo can be rtplan and/or monte carlo 3D dose distributions.\n%\n% NOTE:\n% Warnings for divisions by zero are switched off during the call to this function.\n% Infinite values are set to nan (not-a-number).\n%\n% Example:\n%\n% [doseratio]=dicomrt_doseratio(doseone,dosetwo)\n%\n% returns in doseratio the ratio: dosetwo/doseone. \n%\n% See also: dicomrt_dosediff\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check case and set-up some parameters and variables\n[doseone_dose_temp,type_doseone_dose,labeld1,PatientPosition]=dicomrt_checkinput(doseone);\n[dosetwo_dose_temp,type_dosetwo_dose,labeld1,PatientPosition]=dicomrt_checkinput(dosetwo);\n\ndoseone_dose=dicomrt_varfilter(doseone_dose_temp);\ndosetwo_dose=dicomrt_varfilter(dosetwo_dose_temp);\n\n% Perform ratio: swith off and back on warnings\nwarning off MATLAB:divideByZero;\ndose_ratio=dosetwo_dose./doseone_dose;\nwarning on MATLAB:divideByZero;\n\n% Discard infinite values\ndose_ratio(find(isinf(dose_ratio)==1))=nan;\n\n% Restore original variable format\n[dose_ratio]=dicomrt_restorevarformat(dosetwo,dose_ratio);\n\n% Label Plan and update time of creation\nif iscell(dose_ratio)==1\n dose_ratio{1,1}{1}.RTPlanLabel=[dose_ratio{1,1}{1}.RTPlanLabel,'-DRATIO'];\n dose_ratio{1,1}{1}.RTPlanDate=date;\n time=fix(clock);\n creationtime=[num2str(time(4)),':',num2str(time(5))];\n dose_ratio{1,1}{1}.RTPlanTime=creationtime;\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/Importing/dicomrt-toolbox-v2/analysis/dicomrt_doseratio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6412889189259565}} {"text": "% HealpixBorderGetNext for the north polar cap area\n% flag = 0 : where dTheta_dPhi >= 0\n% flag = 1 : where dTheta_dPhi <= 0\nfunction [phi, theta, dTheta_dPhi] = HealpixBorderGetNextPC(n, k, prev_phi, delta_phi, flag)\n\nphi = prev_phi + delta_phi;\na = 1;\nb = - k^2 * pi^2 / (12 * n^2);\n\nif flag == 0\n theta = acos(a + b / phi^2);\n dTheta_dPhi = 2 * b / (phi^3* sin(theta)); \nelse\n theta = acos(a + b / (phi - pi/2)^2);\n dTheta_dPhi = 2 * b / ((phi - pi/2)^3 * sin(theta)); \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/extern/HealpixLib/HealpixBorderGetNextPC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6412889076799431}} {"text": "function [Bt]=GetCentrifugalMatrix_2(T,Pcii,Icii,mcii,dq)\n%% About the function: this is a function that is used to calculate\n% Centrifugal matrix of the serially linked manipulator, the return value of\n% the function is (nxn) Centrifugal matrix from which when multiplied by\n% the joints' velocity vector the torques of the centrifugal forces \n% is going to be calculated \n% The input parameters are as the following:\n% T is (4x4xn) transformation matrix of the serially linked robot, each\n% (4x4) matrix represents the transform for each link in the base frame. \n% Pcii is 3Xn matrix while each column represents the local coordinates\n% of the center of mass of each link.\n% Icii is (3x3xn) matrix, each 3x3 matrix of which represnets the\n% associated link inertial tensor represented in its local inertial frame\n% mcii is (1xn) vector, each element of which specifies a mass of one of\n% the links\n\n% Copyright Mohammad SAFEEA 2nd,April,2018\n\nn=max(size(mcii));\n%% Initialization of Ai and Bi.\nBi=zeros(3,n,n);\nDi=zeros(3,n,n);\nKj=zeros(3,n);\nhalf_Kj=zeros(3,n);\n%% Calculate === some auxuliary variables\nPcii_A=zeros(3,n);\nmcii_Pcii_A=zeros(3,n);\nPcii_A(:,1)=T(1:3,1:3,1)*Pcii(:,1);\nmcii_Pcii_A(:,1)=mcii(1)*Pcii_A(:,1);\nKj(:,1)=T(1:3,3,1);\nhalf_Kj(:,1)=0.5*Kj(:,1);\nfor i=2:n\n Pcii_A(:,i)=T(1:3,1:3,i)*Pcii(:,i);\n mcii_Pcii_A(:,i)=mcii(i)*Pcii_A(:,i);\n Kj(:,i)=T(1:3,3,i);\n half_Kj(:,i)=0.5*Kj(:,i);\nend\n%% calculating the links model, Mci and ddPci\nfor i=1:n\n %% calculating the Mci term\n Pci=Pcii_A(:,i)+T(1:3,4,i);\n L=T(1:3,1:3,i)*(trace(Icii(:,:,i))*eye(3)-2*Icii(:,:,i))*T(1:3,1:3,i)';\n for j=1:i\n %Calculating inertial moment due to normal acceleration due to\n %effect of each frame j.\n Bi(:,j,i)=cross(L*half_Kj(:,j),Kj(:,j));\n %Calculating acceleration of center of mass of link i due to\n %injection of each frame j\n Pcij=Pci-T(1:3,4,j);\n Di(:,j,i)=Kj(:,j)*(Kj(:,j)'*Pcij)-Pcij;\n end\nend\nBt=zeros(n,n);\nFac_D=zeros(3,n);\nMac_B=zeros(3,n);\nPjp1_j=zeros(3,1);\n%% calculating Mac for all of the links, then calculating two by filling At\n%% and Bt\n\nstart=n-1;\nj=n;\n%% recursive rprocedure on moments and forces\n for k=1:n %% iterate through the matrix\n Mac_B(:,k)=Bi(:,k,j)+cross(mcii_Pcii_A(:,j),Di(:,k,j)); \n end\n %% on forces\n Fac_D=mcii(j)*Di(:,:,j); \n Bt(j,:)=T(1:3,3,j)'*Mac_B;\n \nfor j=start:-1:1 %% iterate through the joints\n Pjp1_j=T(1:3,4,j+1)-T(1:3,4,j);\n %% recursive rprocedure on moments and forces\n for k=1:j %% iterate through the matrix\n Mac_B(:,k)=Mac_B(:,k)+Bi(:,k,j)+cross(Pjp1_j,Fac_D(:,k))+cross(mcii_Pcii_A(:,j),Di(:,k,j)); \n end\n for k=j+1:n\n Mac_B(:,k)=Mac_B(:,k)+cross(Pjp1_j,Fac_D(:,k));\n end\n %% on forces\n Fac_D(:,1:j)=Fac_D(:,1:j)+mcii(j)*Di(:,1:j,j); \n Bt(j,:)=T(1:3,3,j)'*Mac_B;\n \nend\n%% close the function\nend\n\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/GetCentrifugalMatrix_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6411986677438639}} {"text": "function [ A,E,Z,iter1 ] = core_RMAMR( D,lambda, I, J, tol, maxiter )\n%MC_RPCA_MIXED_NOISE implements the inexact augmented lagrange multiplier\n% method for matrix recovery with erase and sparse noise\n% D - m*n matrix of observations\n%\n% lambda - weight on sparse error term in the cost function\n%\n% I, J - two dimension index of the regions containing values \n%\n% tol - tolerance for stopping criterion\n% -DEFAULT 1e-3 if omitted or -1\n%\n% maxiter - maximum number of iterations\n% -DEFAULT 500 if omitted or -1\n%\n% Model:\n% min |A|_* +lambda*|ProjectionOnOmega(E)|_1 + gamma*|ProjectionOnOmega(Z)|_F^2\n% subj A+E+Z=D;\n% Copyright:Xinchen YE, Tianjin University, 2014\n\n[m,n] = size(D);\nif nargin < 5\n tol = 1e-3;\nelseif tol == -1\n tol = 1e-3;\nend\nif nargin < 6\n maxiter = 500;\nelseif maxiter == -1\n maxiter = 500;\nend\n\nrho = 1.2;%1.1+2.5*rho_s;\n% lambda = 10;%1/sqrt(m);\ngamma =1; % weight on noise term in the cost function\nnorm_two = lansvd(D, 1, 'L'); %computes the 1 largest singular value\nmuk = 10/norm_two; %can be tuned\nd_norm=norm(D,'fro');\n\nEk=zeros(m,n);Yk=zeros(m,n);\nZk=zeros(m,n);\niter1=0;\nconverged1=false;\nsv = 5;\nwhile ~converged1\n iter1 = iter1+1;\n [U, S, V]=lansvd(D-Ek-Zk+(1/muk)*Yk,sv,'L');\n diagS = diag(S);\n diagS = diagS(1:sv);\n svn = length(find(diagS > 1/muk));\n svp = svn;\n \n ratio = diagS(1:end-1)./diagS(2:end);\n [max_ratio, max_idx] = max(ratio);\n if max_ratio > 2\n svp = min(svn, max_idx);\n end\n if svp < sv %|| iter < 10\n sv = min(svp + 1, n);\n else\n sv = min(svp + 10, n);\n end\n Ak=U(:,1:svp)*diag(diagS(1:svp)-1/muk)*V(:,1:svp)';\n% [U,S,V] = svd(D-Ek-Zk+(1/muk)*Yk);\n% Ak = U*(shrink(S,1/muk))*V';\n \n Ek = MtOmega(shrink(D-Ak-Zk+(1/muk)*Yk,lambda/muk),I,J,m,n)+...\n D-Ak-Zk+(1/muk)*Yk-MtOmega(D-Ak-Zk+(1/muk)*Yk,I,J,m,n);\n \n Zk = (muk/(muk+2*gamma))*MtOmega(D-Ak-Ek+(1/muk)*Yk,I,J,m,n)+...\n D-Ak-Ek+(1/muk)*Yk-MtOmega(D-Ak-Ek+(1/muk)*Yk,I,J,m,n);\n Yk=Yk+muk*(D-Ak-Ek-Zk);\n muk=rho*muk;\n \n stopCriterion = norm(D-Ak-Ek-Zk, 'fro') / d_norm;\n disp([ ' r(F) ' num2str(rank(Ak))...\n ' |E|_0 ' num2str(length(find(abs(Ek)>0)))...\n ' |Z|_0 ' num2str(length(find(abs(Zk)>0)))...\n ' stopCriterion ' num2str(stopCriterion) ' iter1 ' num2str(iter1) ' mu ' num2str(muk)]);\n if stopCriterion < tol\n converged1 = true;\n end \n if ~converged1&&iter1>=maxiter\n disp('Maximum iterations reached');\n converged1=true;\n end\nend\n\nA=Ak;\nE=Ek;\nZ=Zk;\nend\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/ttd/RMAMR/core_RMAMR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6411986482360222}} {"text": "function [Et,Vt,Ft]=hexahedral_hexagon_beam(r,ne,hz,nz,XYZ_centre)\n\n%%\n\n\n%% CREATING 2D SECTION MESH\n\n%Basic regular quad mesh\n[X,Y]=meshgrid(linspace(0,1,ne+1));\nZ=zeros(size(X));\nV=[X(:) Y(:) Z(:)];\n[F,V] = surf2patch(X,Y,Z);\n\n%Creating 3 sheared quad meshes to construct hexagon\n\n%V1 \nV1=V;\nSH=eye(3,3); SH(1,2)=0; SH(2,1)=0.5;\nV1=V1*SH; \nS=eye(3,3); S(1,1)=1; S(2,2)=sqrt(3/4);\nV1=V1*S; \n\n%V2\na=pi/3;\nR=[cos(a) sin(a) 0; -sin(a) cos(a) 0; 0 0 0;];\nV2=V1*R; \n\n%V3\nV3=V;\nSH=eye(3,3); SH(1,2)=0; SH(2,1)=-0.5;\nV3=V3*SH; \nS=eye(3,3); S(1,1)=1; S(2,2)=sqrt(3/4);\nV3=V3*S; \nV3(:,1)=V3(:,1)+0.5; V3(:,2)=V3(:,2)+sqrt(3/4); \n\n%Composing hexagon\nVu=[V1;V2;V3];\nFu=[F;F+size(V1,1);F+2.*size(V1,1)];\n\n%Removing double points\n[Fu,Vu,~,~,~,~]=unique_patch(Fu,Vu,[]);\n\n%Scaling radius\n[THETA,R] = cart2pol(Vu(:,1),Vu(:,2));\n[Vu(:,1),Vu(:,2)] = pol2cart(THETA,r.*R);\n\n%% CREATING 3D EXTRUDED MESH\n\nF=Fu; V=Vu; \n\nz_range=linspace(0,hz,nz+1);\nVt=repmat(V,numel(z_range),1);\nZ_add=ones(size(V,1),1)*z_range; Z_add=Z_add(:);\nVt(:,3)=Vt(:,3)+Z_add;\nVt=Vt-ones(size(Vt,1),1)*mean(Vt,1); %centering around mean\nVt=Vt+ones(size(Vt,1),1)*XYZ_centre; %Translate to desired centre\n\nEt=[];\nfor iz=1:1:numel(z_range)-1\n % bottom top \n Et=[Et; F+(size(V,1).*(iz-1)) F+(size(V,1).*iz)];\nend\n\n% f_order=[4 3 2 1 8 7 6 5];\n% Et=Et(:,f_order);\n\n[Ft]=hex2patch(Et);\n\nend\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/hexahedral_hexagon_beam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6411986414024013}} {"text": "function amax_index = r8vec_amax_index ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_AMAX_INDEX returns the index of the maximum absolute value in an R8VEC.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8 values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the array.\n%\n% Input, real A(N), the array.\n%\n% Output, integer AMAX_INDEX, the index of the entry of largest magnitude.\n%\n if ( n <= 0 )\n\n amax_index = -1;\n\n else\n\n amax_index = 1;\n amax = abs ( a(1) );\n\n for i = 2 : n\n if ( amax < abs ( a(i) ) )\n amax_index = i;\n amax = abs ( a(i) );\n end\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_amax_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.6411232500227797}} {"text": "function [m_0, m_1, m_2] = quad_moments(fun, a, b, rtol, atol, minsubs)\n% QUAD_MOMENTS Calculate the 0th, 1st and 2nd moment of a given\n% (unnormalized) probability distribution\n%\n% [m_0, m_1, m_2] = quad_moments(fun, a, b, varargin) \n% Inputs:\n% fun = Function handle to the unnormalized probability distribution\n% a,b = integration limits [a,b]\n% rtol = relative tolerance for the integration (optional, default 1e-6)\n% atol = absolute tolerance for the integration (optional, default 1e-10)\n% \n% Returns the first three moments:\n% m0 = int_a^b fun(x) dx\n% m1 = int_a^b x*fun(x) dx / m0\n% m2 = int_a^b x^2*fun(x) dx / m0\n%\n% The function uses an adaptive Gauss-Kronrod quadrature. The same set of \n% integration points and intervals are used for each moment. This speeds up \n% the evaluations by factor 3, since the function evaluations are done only \n% once.\n% \n% The quadrature method is described by:\n% L.F. Shampine, \"Vectorized Adaptive Quadrature in Matlab\",\n% Journal of Computational and Applied Mathematics, 211, 2008, \n% pp. 131-140.\n\n% Copyright (c) 2010 Jarno Vanhatalo, Jouni Hartikainen\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 maxsubs = 650;\n \n if nargin < 4\n rtol = 1.e-6;\n end\n if nargin < 5\n atol = 1.e-10;\n end\n if nargin < 6\n minsubs = 10;\n end\n \n rtol = max(rtol,100*eps);\n atol = max(atol,0);\n minsubs = max(minsubs,2); % At least two subintervals are needed\n \n % points and weights\n points15 = [0.2077849550078985; 0.4058451513773972; 0.5860872354676911; ...\n 0.7415311855993944; 0.8648644233597691; 0.9491079123427585; ...\n 0.9914553711208126];\n points = [-points15(end:-1:1); 0; points15];\n \n w15 = [0.2044329400752989, 0.1903505780647854, 0.1690047266392679, ...\n 0.1406532597155259, 0.1047900103222502, 0.06309209262997855, ...\n 0.02293532201052922];\n w = [w15(end:-1:1), 0.2094821410847278, w15];\n \n w7 = [0,0.3818300505051189,0,0.2797053914892767,0,0.1294849661688697,0];\n ew = w - [w7(end:-1:1), 0.4179591836734694, w7];\n \n samples = numel(w);\n \n % split the interval.\n if b-a <= 0\n c = a; a = b; b=c;\n warning('The start of the integration interval was less than the end of it.')\n end\n apu = a + (1:(minsubs-1))./minsubs*(b-a);\n apu = [a,apu,b];\n subs = [apu(1:end-1);apu(2:end)];\n \n % Initialize partial sums.\n Ifx_ok = 0;\n Ifx1_ok = 0;\n Ifx2_ok = 0;\n % The main loop\n while true\n % subintervals and their midpoints\n midpoints = sum(subs)/2; \n halfh = diff(subs)/2; \n x = bsxfun(@plus,points*halfh,midpoints);\n x = reshape(x,1,[]);\n \n fx = fun(x);\n fx1 = fx.*x;\n fx2 = fx.*x.^2;\n \n fx = reshape(fx,samples,[]);\n fx1 = reshape(fx1,samples,[]);\n fx2 = reshape(fx2,samples,[]);\n \n % Subintegrals.\n Ifxsubs = (w*fx) .* halfh;\n errsubs = (ew*fx) .* halfh;\n Ifxsubs1 = (w*fx1) .* halfh;\n Ifxsubs2 = (w*fx2) .* halfh;\n\n % Ifx and tol.\n Ifx = sum(Ifxsubs) + Ifx_ok;\n Ifx1 = sum(Ifxsubs1) + Ifx1_ok;\n Ifx2 = sum(Ifxsubs2) + Ifx2_ok;\n tol = max(atol,rtol*abs(Ifx));\n \n % determine the indices ndx of Ifxsubs for which the\n % errors are acceptable and remove those from subs\n ndx = find(abs(errsubs) <= (2/(b-a)*halfh*tol));\n subs(:,ndx) = [];\n if isempty(subs)\n break\n end\n \n % Update the integral.\n Ifx_ok = Ifx_ok + sum(Ifxsubs(ndx));\n Ifx1_ok = Ifx1_ok + sum(Ifxsubs1(ndx));\n Ifx2_ok = Ifx2_ok + sum(Ifxsubs2(ndx));\n \n % Quit if too many subintervals.\n nsubs = 2*size(subs,2);\n if nsubs > maxsubs\n warning('quad_moments: Reached the limit on the maximum number of intervals in use.');\n break\n end\n midpoints(ndx) = []; \n subs = reshape([subs(1,:); midpoints; midpoints; subs(2,:)],2,[]); % Divide the remaining subintervals in half\n end\n \n % Scale moments\n m_0 = Ifx;\n m_1 = Ifx1./Ifx;\n m_2 = Ifx2./Ifx;\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/private/quad_moments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6411232393792791}} {"text": "function [f,g,H] = autoHess(x,type,funObj,varargin)\n% Numerically compute Hessian of objective function from gradient values\n\np = length(x);\n\nif type == 1\n\t% Use finite differencing\n\tmu = 2*sqrt(1e-12)*(1+norm(x));\n\t\n\t[f,g] = funObj(x,varargin{:});\n\tdiff = zeros(p);\n\tfor j = 1:p\n\t\te_j = zeros(p,1);\n\t\te_j(j) = 1;\n\t\t[f diff(:,j)] = funObj(x + mu*e_j,varargin{:});\n\tend\n\tH = (diff-repmat(g,[1 p]))/mu;\nelseif type == 3 % Use Complex Differentials\n\tmu = 1e-150;\n\t\n\tdiff = zeros(p);\n\tfor j = 1:p\n\t\te_j = zeros(p,1);\n\t\te_j(j) = 1;\n\t\t[f(j) diff(:,j)] = funObj(x + mu*i*e_j,varargin{:});\n\tend\n\tf = mean(real(f));\n\tg = mean(real(diff),2);\n\tH = imag(diff)/mu;\nelse % Use central differencing\n\tmu = 2*sqrt(1e-12)*(1+norm(x));\n\n\tf1 = zeros(p,1);\n\tf2 = zeros(p,1);\n\tdiff1 = zeros(p);\n\tdiff2 = zeros(p);\n\tfor j = 1:p\n\t\te_j = zeros(p,1);\n\t\te_j(j) = 1;\n\t\t[f1(j) diff1(:,j)] = funObj(x + mu*e_j,varargin{:});\n\t\t[f2(j) diff2(:,j)] = funObj(x - mu*e_j,varargin{:});\n\tend\n\tf = mean([f1;f2]);\n\tg = mean([diff1 diff2],2);\n\tH = (diff1-diff2)/(2*mu);\nend\n\n% Make sure H is symmetric\nH = (H+H')/2;\n\nif 0 % DEBUG CODE\n\t[fReal gReal HReal] = funObj(x,varargin{:});\n\t[fReal f]\n\t[gReal g]\n\t[HReal H]\n\tpause;\nend", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/minFunc_2012/autoDif/autoHess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.641107160825163}} {"text": "function x=randiscr(p,n,a)\n%RANDISCR Generate discrete random numbers with specified probabiities [X]=(P,N,A)\n%\n% Usage: (1) randiscr([],10) % generate 10 uniform random binary values\n% (2) randiscr(2:6,10) % generate 10 random numbers in the range 1:5\n% with probabilities [2 3 4 5 6]/20\n% (3) randiscr([],10,'abcd') % generate a string of 10 random\n% characters equiprobable from 'abcd'\n%\n% Inputs: P vector of probabilities (not necessarily normalized) [default = uniform]\n% N number of random values to generate [default = 1]\n% A output alphabet [default = 1:length(p) or 0:1 if p is empty]\n%\n% Outputs: X vector of not necessarily distinct values taken from alphabet A\n%\n% The vector P is internally normalized by dividing by its sum.\n% If P is an M-dimensional matrix (and A is unspecified), then X will\n% have dimensions (N,M) with the corresponding indices for each dimension.\n\n% Somewhat similar in function to RANDSRC in the comms toolbox\n\n% Copyright (c) 2005-2012 Mike Brookes, mike.brookes@ic.ac.uk\n% Version: $Id: randiscr.m 2189 2012-07-20 13:47:00Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ngota=nargin>2;\nif nargin<1 || ~numel(p)\n if gota\n p=ones(1,length(a));\n else\n p=ones(1,2);\n a=(0:1)';\n gota=1;\n end\nend\nif nargin<2 || ~numel(n)\n n=1;\nend\nd=length(p(:)); % size of output alphabet\nz=zeros(d+n-1,1); % array to hold random numbers\nz(1:d)=cumsum(p(:)/sum(p(:))); % last value is actually overwritten in the next line\nz(d:d+n-1)=rand(n,1);\n[y,iy]=sort(z);\ny(iy)=(1:d+n-1)';\nm=zeros(d+n-1,1);\nm(y(1:d-1))=1;\nm(1)=m(1)+1;\nmc=cumsum(m);\nx=mc(y(d:d+n-1));\nif gota\n x=a(x);\nelseif length(p(:))>length(p) % need multiple dimensions\n v=x-1;\n s=cumprod(size(p));\n m=length(s);\n s(2:end)=s(1:end-1);\n s(1)=1;\n x=zeros(n,m);\n for i=m:-1:1\n x(:,i)=1+floor(v/s(i));\n v=rem(v,s(i));\n end\nend", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/randiscr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6411071450143924}} {"text": "function [ a, rank ] = npart_sf_lex_successor ( n, npart, a, rank )\n\n%*****************************************************************************80\n%\n%% NPART_SF_LEX_SUCCESSOR computes SF NPART partition.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer N, the integer to be partitioned.\n% N must be positive.\n%\n% Input, integer NPART, the number of parts of the partition.\n% 1 <= NPART <= N.\n%\n% Input/output, integer A(NPART), contains the partition.\n% A(1) through A(NPART) contain the nonzero integers which\n% sum to N. The values in A must be in DESCENDING order.\n%\n% Input/output, integer RANK, the rank.\n% If RANK = -1 on input, then the routine understands that this is\n% the first call, and that the user wishes the routine to supply\n% the first element in the ordering, which has RANK = 0.\n% In general, the input value of RANK is increased by 1 for output,\n% unless the very last element of the ordering was input, in which\n% case the output value of RANK is 0.\n%\n\n%\n% Return the first element.\n%\n if ( rank == -1 )\n a = i4vec_part2 ( n, npart );\n rank = 0;\n return\n end\n%\n% Check.\n%\n ierror = part_sf_check ( n, npart, a );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NPART_SF_LEX_SUCCESSOR - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal.\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'NPART_SF_LEX_SUCCESSOR - Fatal error!' );\n end\n%\n% Find the last entry that is 2 or more.\n%\n for i = npart : -1 : 1\n if ( 1 < a(i) )\n indx = i;\n break\n end\n end\n%\n% As long as the last nonunit occurs after the first position,\n% have it donate 1 to the left.\n%\n if ( 1 < indx )\n\n a(indx) = a(indx) - 1;\n a(indx-1) = a(indx-1) + 1;\n indx = indx - 1;\n\n while ( 1 )\n\n if ( indx <= 1 )\n break\n end\n\n if ( a(indx) <= a(indx-1) )\n break\n end\n\n temp = a(indx);\n a(indx) = a(indx-1);\n a(indx-1) = temp;\n\n indx = indx - 1;\n\n end\n%\n% Sum the tail.\n%\n temp = sum ( a(indx+1:npart) );\n%\n% Partition the tail sum equally over the tail.\n%\n a(indx+1:npart) = i4vec_part2 ( temp, npart - indx );\n\n rank = rank + 1;\n%\n% If A(2) through A(NPART) are 1, then this is the last element.\n% Return the first one.\n%\n else\n\n a = i4vec_part2 ( n, npart );\n rank = 0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/npart_sf_lex_successor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6410826986953233}} {"text": "function [om2,T2,dom2dom,dom2dT,dT2dom,dT2dT] = inverse_motion(om,T);\n\n% This function computes the inverse motion corresponding to (om,T)\n\n\nom2 = -om;\ndom2dom = -eye(3);\ndom2dT = zeros(3,3);\n\n\n[R,dRdom] = rodrigues(om);\nRinv = R';\ndRinvdR = zeros(9,9);\ndRinvdR([1 4 7],[1 2 3]) = eye(3);\ndRinvdR([2 5 8],[4 5 6]) = eye(3);\ndRinvdR([3 6 9],[7 8 9]) = eye(3);\ndRinvdom = dRinvdR * dRdom;\n\nTt = Rinv * T;\n[dTtdRinv,dTtdT] = dAB(Rinv,T);\n\nT2 = -Tt;\n\ndT2dom = - dTtdRinv * dRinvdom;\ndT2dT = - dTtdT;\n\n\nreturn;\n\n% Test of the Jacobians:\n\nom = randn(3,1);\nT = 10*randn(3,1);\n[om2,T2,dom2dom,dom2dT,dT2dom,dT2dT] = inverse_motion(om,T);\n\ndom = randn(3,1) / 100000;\ndT = randn(3,1) / 100000;\n\n[om3r,T3r] = inverse_motion(om+dom,T+dT);\n\nom3p = om2 + dom2dom*dom + dom2dT*dT;\nT3p = T2 + dT2dom*dom + dT2dT*dT;\n\n%norm(om3r - om2) / norm(om3r - om3p) %-> Leads to infinity, since the opreation is linear!\nnorm(T3r - T2) / norm(T3r - T3p)\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/inverse_motion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6410504338149806}} {"text": "function order = tetra_unit_size ( rule )\n\n%*****************************************************************************80\n%\n%% TETRA_UNIT_SIZE sizes quadrature weights and abscissas in the unit tetrahedron.\n%\n% Integration region:\n%\n% 0 <= X,\n% and\n% 0 <= Y,\n% and\n% 0 <= Z, \n% and\n% X + Y + Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Hermann Engels,\n% Numerical Quadrature and Cubature,\n% Academic Press, 1980,\n% ISBN: 012238850X,\n% LC: QA299.3E5.\n%\n% Patrick Keast,\n% Moderate Degree Tetrahedral Quadrature Formulas,\n% Computer Methods in Applied Mechanics and Engineering,\n% Volume 55, Number 3, May 1986, pages 339-348.\n%\n% Olgierd Zienkiewicz,\n% The Finite Element Method,\n% Sixth Edition,\n% Butterworth-Heinemann, 2005,\n% ISBN: 0750663200,\n% LC: TA640.2.Z54\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n% 1, order 1, precision 0, Newton Cotes formula #0, Zienkiewicz #1.\n% 2, order 4, precision 1, Newton Cotes formula #1.\n% 3, order 4, precision 2, Zienkiewicz #2.\n% 4, order 10, precision 2, Newton Cotes formula #2\n% 5, order 5, precision 3, Zienkiewicz #3.\n% 6, order 8, precision 3, Newton Cotes formula #3.\n% 7, order 35, precision 4, Newton Cotes formula #4.\n% 8, order 11, precision 4, a Keast rule.\n%\n% Output, integer ORDER, the order of the rule.\n%\n\n%\n% Newton Cotes #0.\n%\n if ( rule == 1 )\n\n order = 1;\n%\n% Newton Cotes #1.\n%\n elseif ( rule == 2 )\n\n order = 4;\n%\n% Zienkiewicz #2.\n%\n elseif ( rule == 3 )\n\n order = 4;\n%\n% Newton Cotes #2.\n%\n elseif ( rule == 4 )\n\n order = 10;\n%\n% Zienkiewicz #3.\n%\n elseif ( rule == 5 )\n\n order = 5;\n%\n% Newton Cotes #3.\n% (This is actually formally a 20 point rule, but with 12 zero coefficients%)\n%\n elseif ( rule == 6 )\n\n order = 8;\n%\n% Newton Cotes #4.\n%\n elseif ( rule == 7 )\n\n order = 35;\n%\n% Keast Rule of order 11\n%\n elseif ( rule == 8 )\n\n order = 11;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TETRA_UNIT_SIZE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of RULE = %d\\n', rule );\n error ( 'TETRA_UNIT_SIZE - Fatal error!' );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/tetra_unit_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6410504245604045}} {"text": "function g = s2g(s, epsilon);\n\n% G = s2g(S, EPSILON)\n%\n% Scattering to Hybrid-G transformation\n% G and S are matrices of size [2,2,F]\n% where F is the number of frequencies\n% (the number of ports is always 2)\n% \n% EPSILON is a limit used in finding correspondent Hybrid-G matrices in the\n% vicinity of singularities; by default 1e-12, should be enough for most\n% realistic problems; could be increased for a gain in speed\n%\n% written by tudor dima, tudima@zahoo.com, change the z into y\n\nif nargin < 2, epsilon = 1e-12; end;\n\nd = (1+s(1,1,:)).*(1-s(2,2,:)) + s(1,2,:).*s(2,1,:);\n[n,i] = min(abs(d));\nexact_g = 1;\nwhile n <= epsilon\n exact_g = 0;\n p1 = 1+round(rand); p2 = 1+round(rand);\n s(p1,p2,i) = s(p1,p2,i)+(rand-0.5)*epsilon;\n d = (1+s(1,1,:)).*(1-s(2,2,:)) + s(1,2,:).*s(2,1,:);\n [n,i] = min(abs(d));\nend;\n\nif exact_g == 0\n fprintf(1,'%s\\n%s\\n', 's2g: correspondent G-hybrid matrix non-existent', ...\n 'an approximation is produced');\nend;\n\ng(1,1,:) = ((1 - s(1,1,:)) .* (1 - s(2,2,:)) - s(1,2,:).*s(2,1,:))./d;\ng(1,2,:) = -2*s(1,2,:)./d;\ng(2,1,:) = 2*s(2,1,:)./d;\ng(2,2,:) = ((1 + s(1,1,:)) .* (1 + s(2,2,:)) - s(1,2,:).*s(2,1,:))./d;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/s2g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6410138258521363}} {"text": "function v = rtd(X)\n% Dc RTD output\n% R1 R2 R3 R4 R5 R6 R7 R8 R9 RT E1\n% 1 2 3 4 5 6 7 8 9 10 11\n%\nY=4; % N = 0, U = 4, and M = 1 not required for dc.\n%\n% The following adds to execution time, but is given for clarity.\n%\nR1=X(1);R2=X(2);R3=X(3);R4=X(4);R5=X(5);R6=X(6);R7=X(7);\nR8=X(8);R9=X(9);RT=X(10);E1=X(11);\n%\n% Simplify A1 with the following substitutions\n%\nG1=1/R1+1/R4+1/RT;\nG2=1/R5+1/R6+1/RT;\nG3=1/R2+1/R3+1/R4;\nG4=1/R5+1/R7;\n%\nA1=[G1 -1/RT -1/R4 0 -1/R1;\n -1/RT G2 -1/R5 0 0;\n -1/R4 0 G3 -1/R3 0;\n 0 -1/R5 G4 0 0;\n 0 0 0 0 1];\n%\nB2=[0; E1/R6;E1/R2;0;-E1*R9/R8];\n% \nV=A1\\B2;v=V(Y);\n% For dc circuits (no inductors or capacitors), this is as\n% far as we have to go. \n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/rtd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6409536907944952}} {"text": "function d = distmat3(x, y)\n%DISTMAT3 Distance matrix (three nested for-loops).\n%\n% D = DISTMAT3(X, Y) returns the distance matrix with all distances\n% between the points represented by the rows of X and Y.\n%\n% DISTMAT3(X) is equivalent to DISTMAT3(X, X), but the former computes the\n% distance matrix faster.\n%\n% Distance is Euclidean.\n%\n% The calculation is done with three for-loops.\n%\n% See also DISTMAT0, DISTMAT1, DISTMAT2.\n\n% Author: Peter J. Acklam\n% Time-stamp: 2002-03-03 13:51:22 +0100\n% E-mail: pjacklam@online.no\n% URL: http://home.online.no/~pjacklam\n\n error(nargchk(1, 2, nargin));\n\n if nargin == 1 % DISTMAT3(X)\n\n if ndims(x) ~= 2\n error('Input must be a matrix.');\n end\n\n [m, p] = size(x);\n d = zeros(m, m); % initialise output matrix\n\n for i = 1:m-1\n for j = i+1:m\n ssq = 0; % sum of squares\n for k = 1:p\n ssq = ssq + abs(x(i,k) - x(j,k))^2;\n end\n d(i,j) = sqrt(ssq);\n d(j,i) = d(i,j);\n end\n end\n\n else % DISTMAT3(X)\n\n if ndims(x) ~= 2 | ndims(y) ~= 2\n error('Input must be two matrices.');\n end\n\n [mx, nx] = size(x);\n [my, ny] = size(y);\n\n if nx ~= ny\n error('Both matrices must have the same number of columns.');\n end\n\n m = mx; % number of rows in distance matrix\n n = my; % number of columns in distance matrix\n p = nx; % dimension of each point\n d = zeros(m, n); % initialise output matrix\n\n for i = 1:m\n for j = 1:n\n ssq = 0; % Sum of squares.\n for k = 1:p\n ssq = ssq + abs(x(i,k) - y(j,k))^2;\n end\n d(i,j) = sqrt(ssq);\n end\n end\n\n end\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/util/matutil/distmat3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6408829141925203}} {"text": "function f = dec2fix(x, nfracbits, nbits)\n\n% DEC2FIX Convert decimal integer to binary string fixed point.\n% \n% Usage: F = DEC2FIX(X, NFRACBITS, NBITS)\n% \n% Converts the signed decimal integer given by X (either a scalar, vector,\n% or matrix) to the two's complement representation as a string. If X is a\n% vector or matrix, F(i, :) is the representation for X(i) (the shape of X\n% is not preserved). Note that many fractional numbers that can be\n% represented with a finite number of fractional digits cannot be\n% represented by a finite number of fractional bits (specifically\n% non-powers-of-two like 0.3), so input NFRACBITS is required to specify\n% the precision for the number of fractional bits. Even powers-of-two\n% fractional decimal numbers (like 0.5) require this input.\n% \n% Example:\n% >> dec2fix([2.3 2.4 -2.3 -2.4], 3)\n% \n% ans =\n% \n% 010.010\n% 010.011\n% 101.110\n% 101.101\n% \n% Inputs:\n% -X: decimal integers to convert to two's complement.\n% -NFRACBITS: number of bits to represent fractional part.\n% -NBITS: total number of bits in the representation including the\n% fractional bits (optional, default is the fewest number of bits\n% necessary to represent the integer portion).\n% \n% Outputs:\n% -F: fixed point representation of X as a string.\n% \n% See also: FIX2DEC, TWOS2DEC, DEC2TWOS, DEC2BIN, DEC2HEX, DEC2BASE.\n\nerror(nargchk(2, 3, nargin));\nx = x(:);\nmaxx = max(abs(x));\nnbits_min = max([nextpow2(maxx + (any(x == maxx))) + 1 + nfracbits, ...\n nfracbits]);\n\n% Default number of bits.\nif nargin < 3\n nbits = nbits_min;\nelseif nbits < nbits_min\n warning('dec2twos:nbitsTooSmall', ['Minimum number of bits to ' ...\n 'represent maximum input x is %i, which is greater than ' ...\n 'input nbits = %i. Setting nbits = %i.'], ...\n nbits_min, nbits, nbits_min)\n nbits = nbits_min;\nend\n\n% Convert to two's complement string.\nf = dec2twos(round(x * 2.^nfracbits), nbits);\n\n% Insert binary point.\nf(:, end+1) = '.';\nf = f(:, [1:(nbits-nfracbits), nbits+1, (nbits-nfracbits+1):nbits]);", "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/38889-twos-complement-binary-strings/dec2fix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6408541366629897}} {"text": "function [Hq,tq,hq,Dq,Fq] = MFDFA1(signal,scale,q,m,Fig)\n% Multifractal detrended fluctuation analysis (MFDFA)\n%\n% [Hq,tq,hq,Dq,Fq]=MFDFA(signal,scale,q,m,Fig);\n%\n% INPUT PARAMETERS---------------------------------------------------------\n%\n% signal: input signal\n% scale: vector of scales\n% q: q-order that weights the local variations \n% m: polynomial order for the detrending\n% Fig: 1/0 flag for output plot of Fq, Hq, tq and multifractal\n% spectrum (i.e. Dq versus hq).\n%\n% OUTPUT VARIABLES---------------------------------------------------------\n%\n% Hq: q-order Hurst exponent\n% tq: q-order mass exponent \n% hq: q-order singularity exponent\n% Dq: q-order dimension \n% Fq: q-order scaling function\n%\n% EXAMPLE------------------------------------------------------------------\n%\n% load fractaldata\n% scmin=16;\n% scmax=1024;\n% scres=19;\n% exponents=linspace(log2(scmin),log2(scmax),scres);\n% scale=round(2.^exponents);\n% q=linspace(-5,5,101);\n% m=1;\n% signal1=multifractal;\n% signal2=monofractal;\n% signal3=whitenoise;\n% [Hq1,tq1,hq1,Dq1,Fq1]=MFDFA1(signal1,scale,q,m,1);\n% [Hq2,tq2,hq2,Dq2,Fq2]=MFDFA1(signal2,scale,q,m,1);\n% [Hq3,tq3,hq3,Dq3,Fq3]=MFDFA1(signal3,scale,q,m,1);\n%--------------------------------------------------------------------------\nwarning off\nX=cumsum(signal-mean(signal));\nif min(size(X))~=1||min(size(scale))~=1||min(size(q))~=1;\n error('Input arguments signal, scale and q must be a vector');\nend\nif size(X,2)==1;\n X=transpose(X);\nend\nif min(scale)qm0, 1 ))];\n qm2=qm1-qm0;\n midind= qm2==min(qm2);\n q_middle=qm2(midind(1));\n end\n q_mid=num2str(q_middle);\n q_start=num2str(min(q));\n\n % Create figure\n figure1 = figure('PaperSize',[20.98 29.68],'Color',[1 1 1]);\n\n scaleInd=floor(min(log2(scale))):ceil(max(log2(scale)));\n for ns=1:length(scaleInd),\n scaletick{ns}=num2str(2^scaleInd(ns));\n end\n Fqind=floor(log2(min(min(Fq)))):ceil(log2(max(max(Fq))));\n for nf=1:length(Fqind),\n Fqtick{nf}=num2str(Fqind(nf));\n end\n\n % Create subplot\n subplot1 = subplot(2,2,1,'Parent',figure1,...\n 'YTickLabel',Fqtick,...\n 'XTickLabel',scaletick,...\n 'XTick',scaleInd,...\n 'LineWidth',2,...\n 'FontSize',14);\n hold(subplot1,'all');\n\n % Create multiple lines using matrix input to plot\n plot1 = plot(X1,YMatrix1,'Parent',subplot1);\n set(plot1(1),'MarkerFaceColor',[1 0 0],'MarkerEdgeColor',[0 0 0],...\n 'Marker','o',...\n 'LineStyle','none',...\n 'Color',[1 0 0],...\n 'DisplayName',strcat('q = ',num2str(min(q))));\n set(plot1(2),'MarkerFaceColor',[0 0 1],'MarkerEdgeColor',[0 0 0],...\n 'Marker','o',...\n 'LineStyle','none',...\n 'Color',[0 0 1],...\n 'DisplayName',strcat('q = ',num2str(q_middle)));\n set(plot1(3),'MarkerFaceColor',[0 0.498 0],'MarkerEdgeColor',[0 0 0],...\n 'Marker','o',...\n 'LineStyle','none',...\n 'Color',[0 0.498 0],...\n 'DisplayName',strcat('q = ',num2str(max(q))));\n set(plot1(4),'LineWidth',2,'Color',[1 0 0],'DisplayName',strcat('q = ',num2str(min(q))));\n set(plot1(5),'MarkerFaceColor',[1 0 0],'MarkerEdgeColor',[1 1 1],...\n 'LineWidth',2,...\n 'Color',[0 0 1],...\n 'DisplayName',strcat('q = ',num2str(q_middle)));\n set(plot1(6),'LineWidth',2,'Color',[0 0.498 0],'DisplayName',strcat('q = ',num2str(max(q))));\n\n % Create xlabel\n xlabel('Scale (segment sample size)','FontSize',14);\n\n % Create ylabel\n ylabel('log_2(Fq)','FontSize',14);\n\n % Create title\n title('Scaling function Fq (q-order RMS)','FontSize',14);\n\n qInd=floor(min(q)):ceil(max(q));\n for nq=1:length(qInd),\n qtick{nq}=num2str(qInd(nq));\n end\n\n % Create subplot\n subplot2 = subplot(2,2,2,'Parent',figure1,...\n 'XTickLabel',qtick,...\n 'XTick',qInd,...\n 'LineWidth',2,...\n 'FontSize',14);\n hold(subplot2,'all');\n\n % Create plot\n plot(X2,Y1,'Parent',subplot2,'Marker','o','LineStyle','none',...\n 'Color',[0 0 1]);\n\n % Create xlabel\n xlabel('q','FontSize',16);\n\n % Create ylabel\n ylabel('Hq','FontSize',16);\n\n % Create title\n title('q-order Hurst exponent','FontSize',14);\n\n % Create plot\n plot(qstart1,Hqstart1,'Parent',subplot2,'MarkerFaceColor',[1 0 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[1 0 0],...\n 'DisplayName',strcat('Hq(',num2str(min(q)),') = ',num2str(Hq(q==min(q)))));\n\n % Create plot\n plot(qmid1,Hqmid1,'Parent',subplot2,'MarkerFaceColor',[0 0 1],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0 1],...\n 'DisplayName',strcat('Hq(',num2str(q_middle),') = ',num2str(Hq(q==q_middle))));\n\n % Create plot\n plot(qstop1,Hqstop1,'Parent',subplot2,'MarkerFaceColor',[0 0.498 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0.498 0],...\n 'DisplayName',strcat('Hq(',num2str(max(q)),') = ',num2str(Hq(q==max(q)))));\n\n % Create subplot\n subplot3 = subplot(2,2,3,'Parent',figure1,...\n 'XTickLabel',qtick,...\n 'XTick',qInd,...\n 'LineWidth',2,...\n 'FontSize',14);\n hold(subplot3,'all');\n\n % Create plot\n plot(X2,Y3,'Parent',subplot3,'Marker','o','LineStyle','none',...\n 'Color',[0 0 1]);\n\n % Create xlabel\n xlabel('q','FontSize',16);\n\n % Create ylabel\n ylabel('tq','FontSize',16);\n\n % Create title\n title('q-order Mass exponent','FontSize',14);\n\n % Create plot\n plot(qstop1,tqstop1,'Parent',subplot3,'MarkerFaceColor',[0 0.498 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0.498 0],...\n 'DisplayName',strcat('tq(',num2str(max(q)),') = ',num2str(tq(q==max(q)))));\n\n % Create plot\n plot(qstart1,tqstart1,'Parent',subplot3,'MarkerFaceColor',[1 0 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[1 0 0],...\n 'DisplayName',strcat('Hq(',num2str(min(q)),') = ',num2str(Hq(q==min(q)))));\n\n % Create plot\n plot(qmid1,tqmid1,'Parent',subplot3,'MarkerFaceColor',[0 0 1],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0 1],...\n 'DisplayName',strcat('Hq(',num2str(q_middle),') = ',num2str(Hq(q==q_middle))));\n\n % Create subplot\n subplot4 = subplot(2,2,4,'Parent',figure1,'LineWidth',2,'FontSize',12);\n % Uncomment the following line to preserve the X-limits of the axes\n % xlim(subplot4,[0.2 1.8]);\n hold(subplot4,'all');\n\n % Create plot\n plot(X4,Y5,'Parent',subplot4,'Marker','o','LineStyle','none',...\n 'Color',[0 0 1]);\n\n % Create xlabel\n xlabel('hq','FontSize',16);\n\n % Create ylabel\n ylabel('Dq','FontSize',16);\n\n % Create title\n title('Multifractal spectrum','FontSize',14);\n\n % Create plot\n plot(hqstart2,Dqstart1,'Parent',subplot4,'MarkerFaceColor',[1 0 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[1 0 0],...\n 'DisplayName',[strcat('Dq(',num2str(min(q)),') = ',num2str(Dq(q==min(q)))),sprintf('\\n'),strcat('hq(',num2str(min(q)),') = ',num2str(hq(q==min(q))))]);\n\n % Create plot\n plot(hqmid2,Dqmid1,'Parent',subplot4,'MarkerFaceColor',[0 0 1],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0 1],...\n 'DisplayName',[strcat('Dq(',num2str(q_middle),') = ',num2str(Dq(q==q_middle))),sprintf('\\n'),strcat('hq(',num2str(q_middle),') = ',num2str(hq(q==q_middle)))]);\n\n % Create plot\n plot(hqstop2,Dqstop1,'Parent',subplot4,'MarkerFaceColor',[0 0.498 0],...\n 'MarkerEdgeColor',[0 0 0],...\n 'MarkerSize',8,...\n 'Marker','o',...\n 'LineWidth',2,...\n 'LineStyle','none',...\n 'Color',[0 0.498 0],...\n 'DisplayName',[strcat('Dq(',num2str(max(q)),') = ',num2str(Dq(find(q==max(q))-1))),sprintf('\\n'),strcat('hq(',num2str(max(q)),') = ',num2str(hq(find(q==max(q))-1)))]);\n\n % Create legend\n %legend1 = legend(subplot1,'show');\n %set(legend1,'Position',[0.4174 0.6072 0.09288 0.2055]);\n % Create legend\n legend1 = legend(subplot1,'show');\n set(legend1,'Position',[0.4126 0.6072 0.1024 0.2055]);\n\n % Create legend\n legend2 = legend(subplot3,'show');\n set(legend2,'Position',[0.3414 0.1576 0.1458 0.1714]);\n\n % Create legend\n legend3 = legend(subplot2,'show');\n set(legend3,'Position',[0.8171 0.7456 0.1528 0.1714]);\n\n % Create legend\n legend4 = legend(subplot4,'show');\n set(legend4,'Position',[0.8338 0.2436 0.1354 0.2764]);\n\n % Create textbox\n annotation(figure1,'textbox',[0.2726 0.638 0.1111 0.05249],...\n 'String',{'Slope = Hq'},...\n 'HorizontalAlignment','center',...\n 'FontSize',14,...\n 'FitBoxToText','off');\n\n % Create textbox\n annotation(figure1,'textbox',[0.6355 0.1669 0.2013 0.05518],...\n 'String',{strcat('hq_m_a_x - hq_m_i_n = ',num2str(max(hq)-min(hq)))},...\n 'HorizontalAlignment','center',...\n 'FontSize',14,...\n 'FitBoxToText','off',...\n 'LineStyle','none');\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/38262-multifractal-detrended-fluctuation-analyses/Introduction_to_MFDFA4/MFDFA1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.640708153945938}} {"text": "function dFdz = deriv(F,z0,Fz0,type)\n%DERIV Approximate gradient and Jacobian.\n% For real x0, deriv(F,x0) computes the gradient dF(x0)/dx or Jacobian\n% dF(x0)/dx^T of a real-valued function F(x) in the real variables x,\n% assuming F is analytic in x when x is complex. If this assumption is\n% not satisfied (e.g., when f is function of x' instead of x.'), use the\n% finite difference methods below. The input variables x may be a scalar,\n% vector, matrix, tensor or even a (nested) cell array of tensors.\n%\n% For complex z0, deriv(F,z0) and deriv(F,z0,Fz0) are equivalent to\n% deriv(F,z0,Fz0,'gradient') if F(z0) is a real scalar, and\n% deriv(F,z0,Fz0,'Jacobian') otherwise. The input variables z may be a\n% scalar, vector, matrix, tensor or even a cell array of tensors.\n%\n% deriv(f,z0,fz0,'gradient') approximates the real gradient df(z0)/dx or\n% scaled conjugate cogradient 2*conj(df(z0)/dz) of a real-valued function\n% f in the real variables x or complex variables z, respectively. The\n% scaled conjugate cogradient is defined as twice the complex conjugate\n% of the partial derivative of f w.r.t. the complex variables z, while\n% treating conj(z) as constant. The real gradient is returned if z0 is\n% real, else the scaled conjugate cogradient is returned. Note that the\n% former is equal to the latter if both z0 and f(z) are real. The input\n% fz0 should supply f(z0). If fz0 is [], it is computed as f(z0).\n%\n% deriv(F,z0,Fz0,'Jacobian') approximates the Jacobian dF(z0)/dz^T in the\n% real or complex variables z. If F(z) is nonanalytic in z and depends on\n% conj(z), use 'Jacobian-C' instead. The input Fz0 should supply F(z0).\n% If Fz0 is [], it is computed as F(z0).\n%\n% deriv(F,z0,Fz0,'Jacobian-C') approximates the complex Jacobian\n% [dF(z0)/dz^T dF(z0)/dconj(z)^T] of a function F in the complex\n% variables z. The partial derivatives in the complex Jacobian are w.r.t.\n% the complex variables z and conj(z), while treating conj(z) and z as\n% constant, respectively. The input Fz0 should supply F(z0). If Fz0 is\n% [], it is computed as F(z0).\n%\n% See also gradient, diff.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] L. Sorber, M. Van Barel, L. De Lathauwer, \"Unconstrained\n% optimization of real functions in complex variables\", SIAM J. Opt.,\n% Vol. 22, No. 3, 2012, pp. 879-898.\n\n% If possible, use the i-trick.\ndim = structure(z0);\nz0 = serialize(z0);\nF = @(z)serialize(F(deserialize(z,dim)));\nif nargin < 3 && all(isreal(z0))\n % Assume F is analytic and both F and z0 are real-valued; return dF/dx.\n e = 2^floor(log2(nthroot(realmin(class(z0)),3)));\n p = zeros(size(z0));\n p(1) = e;\n dFdz = imag(F(z0+p*1i))/e;\n dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];\n for n = 2:length(z0)\n p(n-1) = 0; p(n) = e;\n dFdz(:,n) = imag(F(z0+p*1i))/e;\n end\n if size(dFdz,1) == 1\n dFdz = deserialize(dFdz(:),dim);\n end\n return;\nelseif nargin < 3 || isempty(Fz0)\n Fz0 = F(z0);\nend\nFz0 = serialize(Fz0);\n\n% Define type of derivative.\nif nargin < 4\n if numel(Fz0) == 1 && isreal(Fz0), type = 'gradient';\n else type = 'Jacobian'; end\nend\ndFdzIsGrad = any(strfind(type,'gradient'));\ndFdzIsRealGrad = dFdzIsGrad && all(isreal(z0));\ndFdzIsAnaJac = ~dFdzIsGrad && ~any(strfind(type,'-C'));\n\n% Else use finite (complex) derivatives.\ne = sqrt(eps(class(z0)));\np = zeros(size(z0));\np(1) = e*max(1,abs(real(z0(1))));\ndFdx = (F(z0+p)-Fz0)/p(1);\nif ~dFdzIsRealGrad || ~dFdzIsAnaJac\n p(1) = e*max(1,abs(imag(z0(1))))*1i;\n dFdy = (F(z0+p)-Fz0)/imag(p(1));\nend\nswitch strtok(type,'-')\n case 'gradient'\n if dFdzIsRealGrad, dFdz = dFdx;\n else dFdz = real(dFdx)+real(dFdy)*1i; end\n dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];\n case 'Jacobian'\n if dFdzIsAnaJac\n dFdz = dFdx;\n dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];\n else\n dFdz = 0.5*cat(3,dFdx-dFdy*1i,dFdx+dFdy*1i);\n dFdz = cat(2,dFdz,zeros(size(dFdz,1),length(z0)-1,2));\n end\nend\nfor n = 2:length(z0)\n p(n-1) = 0; p(n) = e*max(1,abs(real(z0(n))));\n dFdx = (F(z0+p)-Fz0)/p(n);\n if ~dFdzIsRealGrad || ~dFdzIsAnaJac\n p(n) = e*max(1,abs(imag(z0(n))))*1i;\n dFdy = (F(z0+p)-Fz0)/imag(p(n));\n end\n switch strtok(type,'-')\n case 'gradient'\n if dFdzIsRealGrad, dFdz(:,n) = dFdx;\n else dFdz(:,n) = real(dFdx)+real(dFdy)*1i; end\n case 'Jacobian'\n if dFdzIsAnaJac, dFdz(:,n) = dFdx;\n else dFdz(:,n,:) = 0.5*cat(3,dFdx-dFdy*1i,dFdx+dFdy*1i); end\n end\nend\ndFdz = dFdz(:,:);\nif size(dFdz,1) == 1 && dFdzIsGrad\n dFdz = deserialize(dFdz(:),dim);\nend\n\nend\n\nfunction [z,offset] = deserialize(z,dim,offset)\n if iscell(dim)\n v = z;\n z = cell(size(dim));\n if nargin < 3, offset = 0; end\n for i = 1:numel(z)\n if iscell(dim{i})\n [z{i},offset] = deserialize(v,dim{i},offset);\n else\n n = prod(dim{i}(:));\n z{i} = reshape(v(offset+(1:n)),dim{i});\n offset = offset+n;\n end\n end\n elseif ~isempty(dim)\n z = reshape(z,dim);\n end\nend\n\nfunction z = serialize(z)\n if iscell(z)\n for i = find(cellfun(@iscell,z(:).'))\n z{i} = serialize(z{i});\n end\n s = cellfun(@numel,z(:)); o = [0; cumsum(s)];\n c = z; z = zeros(o(end),1);\n for i = 1:length(s), z(o(i)+(1:s(i))) = c{i}(:); end\n else\n z = z(:);\n end\nend\n\nfunction dim = structure(z)\n if iscell(z)\n dim = cellfun(@size,z,'UniformOutput',false);\n for i = find(cellfun(@iscell,z(:).'))\n dim{i} = structure(z{i});\n end\n else\n dim = size(z);\n if numel(z) == dim(1), dim = []; end\n end\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6407081519460691}} {"text": "function [me,ASAcontrol] = moderr_e(varargin)\n%MODERR_E Model error\n% ME = MODERR_E(AR_EST,MA_EST,AR_REF,MA_REF,N_OBS) is the model error\n% of an ARMA model estimated from N_OBS observations, with parameter \n% vectors AR_EST and MA_EST, applied for modeling a reference process \n% with ARMA parameters AR_REF and MA_REF. It is a measure for the \n% accuracy of the estimated model. The lower the model error, the \n% better is the model accuracy. For estimated models, its asymptotic \n% minimum value equals the AR-order plus the MA-order of the reference \n% process.\n% \n% MODERR_E is an ARMASA main function.\n\n% References: P. M. T. Broersen, The Quality of Models for ARMA\n% Processes, IEEE Transactions on Signal Processing,\n% Vol. 46, No. 6,, June 1998, pp. 1749-1752.\n\n%Header\n%==============================================================================\n\n%Declaration of variables\n%------------------------\n\n%Declare and assign values to local variables\n%according to the input argument pattern\n[ar_est,ma_est,ar_ref,ma_ref,n_obs,ASAcontrol]=ASAarg(varargin, ...\n{'ar_est' ;'ma_est' ;'ar_ref' ;'ma_ref' ;'n_obs' ;'ASAcontrol'}, ...\n{'isnumeric';'isnumeric';'isnumeric';'isnumeric';'isnumeric';'isstruct' }, ...\n{'ar_est' ;'ma_est' ;'ar_ref' ;'ma_ref' ;'n_obs' });\n\nif isequal(nargin,1) & ~isempty(ASAcontrol)\n %ASAcontrol is the only input argument\n ASAcontrol.error_chk = 0;\n ASAcontrol.run = 0;\nend\n\n%ARMASA-function version information\n%-----------------------------------\n\n%This ARMASA-function is characterized by\n%its current version,\nASAcontrol.is_version = [2000 12 30 20 0 0];\n%and its compatability with versions down to,\nASAcontrol.comp_version = [2000 12 30 20 0 0];\n\n%This function calls other functions of the ARMASA\n%toolbox. The versions of these other functions must\n%be greater than or equal to:\nASAcontrol.req_version.convol_e = [2000 12 13 21 0 0];\nASAcontrol.req_version.arma2cor_e = [2000 12 30 20 0 0];\n\n%Checks\n%------\n\nif ~isfield(ASAcontrol,'error_chk') | ASAcontrol.error_chk\n %Perform standard error checks\n %Input argument format checks\n ASAcontrol.error_chk = 1;\n if ~isnum(ar_est)\n error(ASAerr(11,'ar_est'))\n elseif ~isvector(ar_est)\n error(ASAerr(15,'ar_est'))\n elseif size(ar_est,1)>1\n ar_est = ar_est';\n warning(ASAwarn(25,{'column';'ar_est';'row'},ASAcontrol)) \n end\n if ~isnum(ma_est)\n error(ASAerr(11,'ma_est'))\n elseif ~isvector(ma_est)\n error(ASAerr(15,'ma_est'))\n elseif size(ma_est,1)>1\n ma_est = ma_est';\n warning(ASAwarn(25,{'column';'ma_est';'row'},ASAcontrol)) \n end\n if ~isnum(ar_ref)\n error(ASAerr(11,'ar_ref'))\n elseif ~isvector(ar_ref)\n error(ASAerr(15,'ar_ref'))\n elseif size(ar_ref,1)>1\n ar_ref = ar_ref';\n warning(ASAwarn(25,{'column';'ar_ref';'row'},ASAcontrol)) \n end\n if ~isnum(ma_ref)\n error(ASAerr(11,'ma_ref'))\n elseif ~isvector(ma_ref)\n error(ASAerr(15,'ma_ref'))\n elseif size(ma_ref,1)>1\n ma_ref = ma_ref';\n warning(ASAwarn(25,{'column';'ma_ref';'row'},ASAcontrol)) \n end\n if ~isnum(n_obs) | ~isintscalar(n_obs)\n error(ASAerr(17,'n_obs'))\n end\n\n %Input argument value checks\n if ~(isreal(ar_est) & isreal(ma_est) & ...\n isreal(ar_ref) & isreal(ma_ref))\n error(ASAerr(13))\n end\n if ar_est(1)~=1\n error(ASAerr(23,{'ar_est','parameter'}))\n end\n if ma_est(1)~=1\n error(ASAerr(23,{'ma_est','parameter'}))\n end\n if ar_ref(1)~=1\n error(ASAerr(23,{'ar_ref','parameter'}))\n end\n if ma_ref(1)~=1\n error(ASAerr(23,{'ma_ref','parameter'}))\n end\n if n_obs<1\n error(ASAerr(41,'n_obs'))\n end\nend\n\nif ~isfield(ASAcontrol,'version_chk') | ASAcontrol.version_chk\n %Perform version check\n ASAcontrol.version_chk = 1;\n \n %Make sure the requested version of this function\n %complies with its actual version\n ASAversionchk(ASAcontrol);\n \n %Make sure the requested versions of the called\n %functions comply with their actual versions\n arma2cor_e(ASAcontrol);\n convol_e(ASAcontrol);\nend\n\nif ~isfield(ASAcontrol,'run') | ASAcontrol.run\n ASAcontrol.run = 1;\nend\n\nif ASAcontrol.run %Run the computational kernel\n ASAcontrol.version_chk = 0;\n ASAcontrol.error_chk = 0;\n\n%Main \n%=====================================================\n\n%Determine the model error by evaluating the power\n%gain of a modified ARMA model\n[cor,gain] = arma2cor_e...\n (convol_e(ar_ref,ma_est,ASAcontrol),...\n convol_e(ar_est,ma_ref,ASAcontrol),0,ASAcontrol);\nme = n_obs*(gain-1);\n \n%Footer\n%=====================================================\n\nelse %Skip the computational kernel\n %Return ASAcontrol as the first output argument\n if nargout>1\n warning(ASAwarn(9,mfilename,ASAcontrol))\n end\n me = ASAcontrol;\n ASAcontrol = [];\nend\n\n%Program history\n%======================================================================\n%\n% Version Programmer(s) E-mail address\n% ------- ------------- --------------\n% former versions P.M.T. Broersen broersen@tn.tudelft.nl\n% [2000 12 30 20 0 0] W. Wunderink wwunderink01@freeler.nl", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3680-automatic-spectral-analysis/AutomaticSpectra/TimserTools/moderr_e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.640679224983606}} {"text": "% HARRIS - Harris corner detector\n%\n% Usage: cim = harris(im, sigma)\n% [cim, r, c] = harris(im, sigma, thresh, radius, disp)\n% [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)\n%\n% Arguments: \n% im - image to be processed.\n% sigma - standard deviation of smoothing Gaussian. Typical\n% values to use might be 1-3.\n% thresh - threshold (optional). Try a value ~1000.\n% radius - radius of region considered in non-maximal\n% suppression (optional). Typical values to use might\n% be 1-3.\n% disp - optional flag (0 or 1) indicating whether you want\n% to display corners overlayed on the original\n% image. This can be useful for parameter tuning. This\n% defaults to 0\n%\n% Returns:\n% cim - binary image marking corners.\n% r - row coordinates of corner points.\n% c - column coordinates of corner points.\n% rsubp - If five return values are requested sub-pixel\n% csubp - localization of feature points is attempted and\n% returned as an additional set of floating point\n% coords. Note that you may still want to use the integer\n% valued coords to specify centres of correlation windows\n% for feature matching.\n%\n% If thresh and radius are omitted from the argument list only 'cim' is returned\n% as a raw corner strength image. You may then want to look at the values\n% within 'cim' to determine the appropriate threshold value to use. Note that\n% the Harris corner strength varies with the intensity gradient raised to the\n% 4th power. Small changes in input image contrast result in huge changes in\n% the appropriate threshold.\n%\n% Note that this code computes Noble's version of the detector which does not\n% require the parameter 'k'. See comments in code if you wish to use Harris'\n% original measure.\n%\n% See also: NONMAXSUPPTS, DERIVATIVE5\n\n% References: \n% C.G. Harris and M.J. Stephens. \"A combined corner and edge detector\", \n% Proceedings Fourth Alvey Vision Conference, Manchester.\n% pp 147-151, 1988.\n%\n% Alison Noble, \"Descriptions of Image Surfaces\", PhD thesis, Department\n% of Engineering Science, Oxford University 1989, p45.\n\n% Copyright (c) 2002-2010 Peter Kovesi\n% Centre for Exploration Targeting\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk/research/matlabfns/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% March 2002 - Original version\n% December 2002 - Updated comments\n% August 2005 - Changed so that code calls nonmaxsuppts\n% August 2010 - Changed to use Farid and Simoncelli's derivative filters\n\nfunction [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)\n \n error(nargchk(2,5,nargin));\n if nargin == 4\n\tdisp = 0;\n end\n \n if ~isa(im,'double')\n\tim = double(im);\n end\n\n subpixel = nargout == 5;\n\n % Compute derivatives and elements of the structure tensor.\n [Ix, Iy] = derivative5(im, 'x', 'y');\n Ix2 = gaussfilt(Ix.^2, sigma);\n Iy2 = gaussfilt(Iy.^2, sigma); \n Ixy = gaussfilt(Ix.*Iy, sigma); \n\n % Compute the Harris corner measure. Note that there are two measures\n % that can be calculated. I prefer the first one below as given by\n % Nobel in her thesis (reference above). The second one (commented out)\n % requires setting a parameter, it is commonly suggested that k=0.04 - I\n % find this a bit arbitrary and unsatisfactory. \n\n cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred measure.\n% k = 0.04;\n% cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure.\n\n if nargin > 2 % We should perform nonmaximal suppression and threshold\n\n\tif disp % Call nonmaxsuppts to so that image is displayed\n\t if subpixel\n\t\t[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im);\n\t else\n\t\t[r,c] = nonmaxsuppts(cim, radius, thresh, im);\t\t\n\t end\n\telse % Just do the nonmaximal suppression\n\t if subpixel\n\t\t[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh);\n\t else\n\t\t[r,c] = nonmaxsuppts(cim, radius, thresh);\t\t\n\t end\n\tend\n end\n \n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/align2RGBD/align2RGBD/lib/peter/harris.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6406792089415093}} {"text": "function yearly_tmin_correction(filenameout)\n\n% this program is design to adjust the daily Tmin generated by WG using\n% new yearly Tmin series produced by FFT.\n\n% load the yearly averaged Tmin after FFT\nload('Pnew_tmin');\ntmin_FFT=Pnew_tmin';\n\n% load WG generated daily Tmin\nload(filenameout);\n[n,m]=size(gTmin);\ngTmin=gTmin';\ntmin_WG=reshape(gTmin,[],1);\n\nn=length(tmin_FFT); % years\nm=length(tmin_WG); % days\n\n% calculate yearly Tmin generated by WG, namely (Y)\nj=1;\nZ=zeros(n,1);\nfor i=1:365:m\n Z(j,1)=mean(tmin_WG(i:i+365-1,1));\n j=j+1;\nend\n\n% calculate the ratio of yearly Tmin between those after FFT and\n% generated by weather generator\nfor i=1:n\n tmin_ratio(i,1)=tmin_FFT(i,1)-Z(i,1);\nend\n\n% extend the yearly Tmin ratio to daily scale,the data in each\n% year are the same\ntmin_extent=zeros(m,1);\nj=1;\nfor i=1:365:m\n tmin_extent(i:i+365-1,1)=tmin_ratio(j,1);\n j=j+1;\nend\n\n% adjust the daily Tmin generated by WG using above ratios\ntmin_adjust=zeros(size(tmin_WG));\nfor i=1:m\n tmin_adjust(i,1)=tmin_WG(i,1)+tmin_extent(i,1);\nend\nyearly_corrected_tmin=tmin_adjust;\nsave('yearly_corrected_tmin','yearly_corrected_tmin')", "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/29136-stochastic-weather-generator-weagets/WeaGETS/yearly_tmin_correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6405936974768328}} {"text": "function inside = p07_inside ( m, n, point )\n\n%*****************************************************************************80\n%\n%% P07_INSIDE reports if a point is inside the region in problem 07.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real POINT(M,N), the coordinates of the points.\n%\n% Output, logical INSIDE(N), is TRUE if the point is in the region.\n%\n inside(1:n) = 1;\n\n [ lo, hi ] = p07_box ( m );\n%\n% Check whether points are in the bounding box.\n%\n for j = 1 : n\n\n for i = 1 : m\n if ( point(i,j) < lo(i) | hi(i) < point(i,j) )\n inside(j) = 0;\n continue\n end\n\n end\n\n end\n%\n% Check whether points in the bounding box are in the region.\n%\n for j = 1 : n\n\n if ( ~inside(j) )\n continue\n end\n\n if ( cos ( point(1,j) ) < point(2,j) )\n inside(j) = 0;\n continue\n end\n\n if ( point(2,j) < -5.0 + 5.0 * point(1,j)^4 / ( 2.5 * pi )^4 )\n inside(j) = 0;\n continue\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p07_inside.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6404835113328818}} {"text": "classdef CEC2017_F23 < PROBLEM\n% \n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n O; % Optimal decision vector\n Mat;\t% Rotation matrix\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n CallStack = dbstack('-completenames');\n load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n obj.O = Data{12}.o;\n obj.M = 1;\n if isempty(obj.D) || obj.D < 30\n obj.D = 10;\n obj.Mat = Data{12}.M_10;\n elseif obj.D < 50\n obj.D = 30;\n obj.Mat = Data{12}.M_30;\n elseif obj.D < 100\n obj.D = 50;\n obj.Mat = Data{12}.M_50;\n else\n obj.D = 100;\n obj.Mat = Data{12}.M_100;\n end\n obj.lower = zeros(1,obj.D) - 100;\n obj.upper = zeros(1,obj.D) + 100;\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n Z = Z*obj.Mat';\n PopObj = -20*exp(-0.2*sqrt(mean(Z.^2,2))) + 20 - exp(mean(cos(2*pi*Z),2)) + exp(1);\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n Z = Z*obj.Mat';\n PopCon(:,1) = sum(Z(:,2:end).^2,2) + 1 - abs(Z(:,1));\n PopCon(:,2) = abs(sum(Z.^2,2)-4) - 1e-4;\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Single-objective optimization/CEC 2017/CEC2017_F23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6404627700631706}} {"text": "function [Price, ProbaITM , CI] = GetOptionPrice(Paths,Exercise,TimeToExpiry,RiskFreeRate,Optiontype)\n\nswitch Optiontype\n case 'Asian'\n \n MeanPrices = mean(Paths,1) ;\n OptionPricesAtMaturity = max(MeanPrices- Exercise,0);\n case 'Vanilla'\n OptionPricesAtMaturity = max(Paths(end,:)- Exercise,0);\n \nend;\n[MeanPriceAtMaturity, dummy,CI] = normfit(OptionPricesAtMaturity,0.01);\nCI = CI* exp(-TimeToExpiry * RiskFreeRate);\nPrice = MeanPriceAtMaturity * exp(-TimeToExpiry * RiskFreeRate);\nProbaITM = 100 * sum(OptionPricesAtMaturity > 0) ./ length(OptionPricesAtMaturity);\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/17964-monte-carlo-simulations-using-matlab/MonteCarlo/Demos/PortSim/GetOptionPrice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.640452890789814}} {"text": "function [km2] = in22km2(in2)\n% Convert area from square inches to square kilometers.\n% Chad A. Greene 2012\nkm2 = in2*6.4516E-10;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/in22km2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6404528833735638}} {"text": "function [fStdDevB, fStdDevMc, fBValue, fMc, vBValues] = calc_BootstrapB(mCatalog, nNumberRuns, nMinNum, nCalculateMc, fBinning)\n % Computes standard deviation of b-value and Mc by bootstrapping the dataset.\n %\n % [fStdDevB, fStdDevMc, fBValue, fMc, vBValues] = calc_BootstrapB(mCatalog, nNumberRuns, nMinNum, nCalculateMc, fBinning)\n %\n %\n % Input parameters:\n % mCatalog Earthquake catalog to be used\n % nNumberRuns Number of simulation runs (Bootstrap)\n % nMinNum Minimum number of events > Mc for computing a b-value (after bottstrapping sample)\n % nCalculateMC Method to determine the magnitude of completeness (see also: help calc_Mc)\n % fBinning Magnitude binning of the catalog\n %\n % Output parameters:\n % fStdDevB Standard deviation of the computed b-values as the second moment of the b-value distribution\n % fStdDevMc Standard deviation of the computed Mc as the second moment of the Mc distribution\n % fBValue Mean b-value of bootstrapped samples\n % fMc Mean Mc of bootstrapped samples\n % vBValues Vector of all bootstrapped b-values\n %\n % Danijel Schorlemmer\n % June 18, 2003\n \n report_this_filefun();\n \n % Get number of events in catalog\n nLength = mCatalog.Count;\n % Init container\n mResult = [];\n % Bootstrap loop\n for nRuns = 1:nNumberRuns\n % Iniy the bootstrapped catalog\n mLoopCatalog = [];\n % Get the random selection of events (multiples allowed)\n vRnd = ceil(rand(nLength,1) * nLength);\n % Create the bootstrapped catalog\n mLoopCatalog = mCatalog.subset(vRnd);\n % Reduce bootstrapped catalog to all events with M >= Mc\n fMc = calc_Mc(mLoopCatalog, McMethods.McBestCombo, fBinning);\n vSel = mLoopCatalog(:,6) >= fMc;\n mLoopCatalog = mLoopCatalog(vSel,:);\n % If enough events remain, compute b-value\n if length(mLoopCatalog(:,1)) >= nMinNum\n % Calculate b-value from bootstrapped catalog\n [fBValue] = calc_bmemag(mLoopCatalog, fBinning);\n else\n % Not enough events available\n fBValue = nan;\n end\n % Store the results\n mResult = [mResult; fBValue fMc];\n end\n % Return values\n fBValue = mean(mResult(:,1), 'omitnan');\n fMc = mean(mResult(:,2), 'omitnan');\n % Compute the standard deviation of Mc as the second moment of the Mc distribution\n vSel = ~isnan(mResult(:,2));\n vDist = mResult(vSel,2);\n fStdDevMc = std(vDist,1,'omitnan');\n % Compute the standard deviation of b as the second moment of the b distribution\n vSel = ~isnan(mResult(:,1));\n vBValues = mResult(vSel,1);\n fStdDevB = std(vBValues,1,'omitnan');\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/danijel/calc/calc_BootstrapB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6404166861002093}} {"text": "% Fig. 9.30 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nh=0.1;\nN=1;\nnn=1;\nnb=nn*nn+1;\nai=0.1:0.001:nn;\nNA=(4*N./(pi*ai)).*exp(-sqrt(-1)*asin(h./ai));\nsubplot(2,1,1)\nplot(ai,abs(NA));\ngrid;\ntitle('Describing function for hysteresis nonlinearity')\nxlabel('a');\nylabel('Magnitude, |K_{eq}|');\npause;\nff=180/pi;\nsubplot(2,1,2)\nplot(ai,ff*angle(NA));\ngrid;\nxlabel('a')\nylabel('Phase, \\angle K_{eq}, deg')\nhold off", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig9_30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6404166730529746}} {"text": "function [error_x, error_y, fex, fey, ae] = stokespost_q1p0_p(jmpx,jmpy,els,xy,ev)\n%stokespost_q1p0_p computes Poisson error estimator for Q1-P0 \n% [err_x, err_y, fex, fey, ae] = stokespost_q1p0_p(jmpx,jmpy,els,xy,ev);\n% input\n% jmpx, jmpy component elementwise edge stress jumps\n% els elementwise edge lengths\n% xy vertex coordinate vector \n% ev element mapping matrix\n% output\n% err_x, err_y component of velocity elementwise error estimate\n% fex, fey component elementwise rhs vectors\n% ae elementwise Poisson problem matrices\n%\n% IFISS function: DJS; 8 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n fprintf('computing local error estimator... ')\n x=xy(:,1); y=xy(:,2);\n nel=length(ev(:,1));\n error_x=zeros(nel,1); error_y=zeros(nel,1);\n%\n% set up 3x3 Gauss points\n gpt=sqrt(0.6); \n s(1) = -gpt; t(1) = -gpt; wt(1)=25/81;\n s(2) = gpt; t(2) = -gpt; wt(2)=25/81;\n s(3) = gpt; t(3) = gpt; wt(3)=25/81; \n s(4) = -gpt; t(4) = gpt; wt(4)=25/81;\n s(5) = 0.0; t(5) = -gpt; wt(5)=40/81;\n s(6) = gpt; t(6) = 0.0; wt(6)=40/81;\n s(7) = 0.0; t(7) = gpt; wt(7)=40/81; \n s(8) = -gpt; t(8) = 0.0; wt(8)=40/81;\n s(9) = 0.0; t(9) = 0.0; wt(9)=64/81;\n%\n% inner loop over elements \n for ivtx = 1:4\n xl_v(:,ivtx) = x(ev(:,ivtx));\n yl_v(:,ivtx) = y(ev(:,ivtx)); \n\t\tend\n ae = zeros(nel,5,5); elerrx=zeros(5,nel); elerry=zeros(5,nel);\n fex = zeros(nel,5); fey = zeros(nel,5);\n% loop over Gauss points\n for igpt = 1:9\n sigpt=s(igpt);\n tigpt=t(igpt);\n wght=wt(igpt);\n% evaluate derivatives etc\n [jac_v,invjac_v,phi_v,dphidx_v,dphidy_v] = deriv(sigpt,tigpt,xl_v,yl_v);\n [psi_v,dpsidx_v,dpsidy_v] = qderiv(sigpt,tigpt,xl_v,yl_v); \n for j = 1:5\n for i = 1:5\n ae(:,i,j) = ae(:,i,j)+wght*dpsidx_v(:,i+4).*dpsidx_v(:,j+4).*invjac_v(:);\n ae(:,i,j) = ae(:,i,j)+wght*dpsidy_v(:,i+4).*dpsidy_v(:,j+4).*invjac_v(:);\n end\n end\n% end of Gauss point loop\n end\n%\n% include edge jumps (evaluated at the midpoint)\n for ee = 1:4\n fex(:,ee) = fex(:,ee) - jmpx(:,ee) .* els(:,ee)*(1/3);\n fey(:,ee) = fey(:,ee) - jmpy(:,ee) .* els(:,ee)*(1/3);\n end\n%\n% solve for local estimate \n% err=ae\\fe;\n% elerr_p(ielem,1) = err'*fe;\n%% sequential code\n for ielem = 1:nel\n\t\t elerrx(:,ielem) = squeeze(ae(ielem,1:5,1:5))\\(fex(ielem,1:5)'); \n\t\t elerry(:,ielem) = squeeze(ae(ielem,1:5,1:5))\\(fey(ielem,1:5)'); \n\t end\n%%\n for ivtx=1:5, \n\t error_x(:) = error_x(:) + fex(:,ivtx) .* elerrx(ivtx,:)';\n\t\t error_y(:) = error_y(:) + fey(:,ivtx) .* elerry(ivtx,:)';\n\t\t end\n%%\t \n fprintf('done.\\n')\t \n\t\t return\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/stokespost_q1p0_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6404072423950524}} {"text": "function I_out = vesselFilter(I_in, grid_spacing, scales, varargin)\n%VESSELFILTER Frangi's 3D vessel filter.\n% \n% DESCRIPTION:\n% vesselFilter filters a 3D image using Frangi's vessel filtering\n% algorithm [1-3]. The algorithm works by calculating the Hessian\n% matrix (containing second order gradients) at each image voxel. The\n% eigenvalues of this matrix are then ordered and used to classify\n% whether the voxel is part of a vessel. The algorithm is performed\n% over multiple scales by convolving the input image with a Gaussian\n% of the given input scales. The final output is taken as the maximum\n% of the vessel filtered image across all scales.\n%\n% USAGE:\n% I_out = vesselFilter(I_in, grid_spacing, scales)\n% I_out = vesselFilter(I_in, grid_spacing, scales, ...)\n%\n% INPUTS:\n% I_in - 3D image data to filter\n% grid_spacing - [dx, dy, dz] in [m]\n% scales - array of scales to use [m]\n%\n% OPTIONAL INPUTS:\n% Optional 'string', value pairs that may be used to modify the\n% default computational settings.\n%\n% alpha - Value of sensitivity parameter for metric that\n% distinguishes between plate-like and other\n% structures (vessel-like or ball-like).\n% (default = 0.5)\n% beta - Value of sensitivity parameter for metric that\n% distinguishes between ball-like and other structures\n% (vessel-like or plate-like). \n% (default = 0.5)\n% c - Value used to scale the sensitivity parameter for\n% the noise metric (the sensitivity parameter itself\n% is calculated automatically based on the magnitudes\n% of the eigenvalues). \n% (default = 1)\n% gamma - normalisation factor for scale-space derivatives\n% (default = 1)\n% DisplayUpdates - Boolean controlling whether command line updates\n% are displayed (default = true)\n% Plot - Boolean controlling whether a maximum intensity\n% projection of the vessel filtered image at each\n% scale is displayed (default = false)\n% Colormap - colormap to use if 'Plot' is set to true (default =\n% flipud(gray))\n% \n% OUTPUTS:\n% I_out - vessel filtered image\n%\n% ABOUT:\n% author - Bradley Treeby and Tanmayi Oruganti\n% date - 9th May 2012\n% last update - 21st August 2014\n%\n% This function is based on original code by Dean Barratt and Yipeng\n% Hu, CMIC, UCL, 2006-2009 \n%\n% REFERENCES:\n% [1] A. F. Frangi, W. J. Niessen, K. L. Vincken, M. A. Viergever (1998)\n% \"Multiscale vessel enhancement filtering,\" MICCAI, pp. 130-137.\n% [2] R. Manniesing, M.A. Viergever, W.J. Niessen (2006) \"Vessel\n% enhancing diffusion: A scale space representation of vessel\n% structures,\" Med. Image Anal. 10, pp. 815-25.\n% [3] T. Oruganti, J. Laufer, B. E. Treeby (2013) \"Vessel filtering of\n% photoacoustic images,\" Proc. of SPIE, vol. 8581, p. 85811W-1.\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also interpftn, smooth\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see . \n\n% start timer\nstart_time = clock;\n\n% set default parameters\nnum_req_input_variables = 3; % minimum number of input variables\nalpha = 0.5; % value of sensitivity parameter for plate vs vessel/ball measure\nbeta = 0.5; % value of sensitivity parameter for ball vs vessel/plate measure\nc_scale = 1; % scale value of sensitivity parameter for noise\ngamma = 0; % normalisation factor for scale-space derivatives\norigin_smoothness_const = 1e-6; % constant for Manniesing's origin smoothness term\ndisp_updates = true; % boolean controlling display of command line updates\nplot_updates = false; % boolean controlling MIP display \ncolor_map = flipud(gray); % colormap to use if images are displayed \ncardan_tol = 0.001; % tolerance for finding complex roots using cardanRoots\n\n% check user defined inputs\n% replace with user defined values if provided\nif nargin < num_req_input_variables\n error('Incorrect number of inputs');\nelseif ~isempty(varargin)\n for input_index = 1:2:length(varargin)\n switch varargin{input_index}\n case 'alpha'\n alpha = varargin{input_index + 1};\n case 'beta' \n beta = varargin{input_index + 1};\n case 'c'\n c_scale = varargin{input_index + 1};\n case 'gamma'\n gamma = varargin{input_index + 1};\n case 'Display'\n disp_updates = varargin{input_index + 1};\n case 'DisplayUpdates'\n disp_updates = varargin{input_index + 1}; \n case 'Plot'\n plot_updates = varargin{input_index + 1};\n case 'Colormap'\n color_map = varargin{input_index + 1};\n otherwise\n error('Unknown optional input');\n end\n end\nend\n\n% get size of input volume\nsz = size(I_in);\n\n% create k-space grid to use for spectral derivatives\nkgrid = makeGrid(sz(1), grid_spacing(1), sz(2), grid_spacing(2), sz(3), grid_spacing(3));\n\n% force wavenumber vectors to be in the correct directions for bsxfun\nkx_vec = kgrid.kx_vec;\nky_vec = kgrid.ky_vec.';\nkz_vec = permute(kgrid.kz_vec, [2 3 1]);\n\n% compute 3D fft of input image\nIk = fftn(I_in);\n\n% preallocate empty output image\nI_out = zeros(size(I_in));\n\n% loop through the scales defined by the user\nfor scale_index = 1:length(scales)\n \n % extract the current scale\n scale = scales(scale_index);\n \n % update command line status\n if disp_updates\n disp(['Computing Vesselness filter for scale ' num2str(scale) ':']);\n tic, fprintf(' Calculating derivatives... ');\n end\n\n % create normalised frequency domain gaussian at current scale\n FG = exp( (-0.5*scale^2)*(kgrid.kx.^2 + kgrid.ky.^2 + kgrid.kz.^2) );\n\n % compute components of Hessian matrix convolved with Gaussian\n Hxx = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec).^2, FG)) )), [], 1);\n Hyy = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*ky_vec).^2, FG)) )), [], 1);\n Hzz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kz_vec).^2, FG)) )), [], 1);\n Hxy = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec), bsxfun(@times, (1i*ky_vec), FG))) )), [], 1);\n Hxz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec), bsxfun(@times, (1i*kz_vec), FG))) )), [], 1);\n Hyz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*ky_vec), bsxfun(@times, (1i*kz_vec), FG))) )), [], 1);\n\n % update command line status\n if disp_updates\n toc, tic, fprintf(' Computing eigenvalues... ');\n end\n\n % compute trace of Hessian matrix\n P2 = -(Hxx + Hyy + Hzz);\n \n % compute principal minors of Hessian matrix\n M11 = Hyy.*Hzz - Hyz.^2;\n M22 = Hzz.*Hxx - Hxz.^2;\n M33 = Hxx.*Hyy - Hxy.^2;\n P1 = (M11 + M22 + M33);\n \n % compute determinant of Hessian matrix\n P0 = - Hxx.*M11 ...\n + Hxy.*(Hxy.*Hzz - Hyz.*Hxz) ...\n - Hxz.*(Hxy.*Hyz - Hyy.*Hxz);\n\n % find eigenvalues using roots of 3rd order polynomial\n P3 = 1;\n eigenval_mat = cardanRoots(P3, P2, P1, P0, cardan_tol).'; \n \n % update command line status\n if disp_updates\n toc, tic, fprintf(' Sorting eigenvalues... ');\n end\n\n % sort eigenvalues based on their absolute values\n [~, ind] = sort(abs(eigenval_mat));\n ind = bsxfun(@plus, (0:numel(I_in)-1)*3, ind);\n eigenval_mat = eigenval_mat(ind);\n\n % update command line status\n if disp_updates\n toc, tic, fprintf(' Evaluating vesselness measure... ');\n end\n\n % calculate noise parameter dynamically if not given\n Rs = sqrt( abs(eigenval_mat(1, :)).^2 + abs(eigenval_mat(2, :)).^2 + abs(eigenval_mat(3, :)).^2 );\n c = c_scale*0.5*max(Rs(:)); \n \n % calculate overall vesselness measure and scale by Lindeberg?s constant\n % term 1: plate vs vessel/ball measure\n % term 2: ball vs vessel/plate measure\n % term 3: noise measure (Frobenius matrix norm of the Hessian)\n % term 4: Manniesing's origin smoothness term\n V = scale.^(gamma) .* ...\n (1 - exp(-(abs(eigenval_mat(2, :))./abs(eigenval_mat(3, :))).^2./(2*alpha^2))) .* ...\n (exp(-(abs(eigenval_mat(1, :))./sqrt(abs(eigenval_mat(2, :).*eigenval_mat(3, :)))).^2./(2*beta^2))) .* ...\n (1 - exp(-Rs.^2./(2*c^2))) .* ...\n (exp(-(2*origin_smoothness_const.^2)./(abs(eigenval_mat(2, :)).*eigenval_mat(3, :).^2)));\n \n % eliminate structures with positive eigenvalues as these indicate\n % regions of low optical absorption on a background of high optical\n % absorption \n V(eigenval_mat(2, :) > 0 | eigenval_mat(3, :) > 0) = 0;\n\n % reshape to be the correct size\n V = reshape(V, sz);\n \n % take maximum response over multiple scales\n I_out = max(I_out, V);\n \n % display time elapsed\n if disp_updates\n toc\n end\n \n % plot steps if required\n if plot_updates\n \n % get suitable axis scaling\n [~, axis_scale, axis_prefix] = scaleSI(max([sz(1)*grid_spacing(1), sz(2)*grid_spacing(2)]));\n \n % plot figure\n figure;\n imagesc(kgrid.y_vec * axis_scale, kgrid.x_vec * axis_scale, max(V, [], 3));\n axis image;\n colormap(color_map);\n title(['Vessel Filtered Image (MIP), Scale = ' num2str(scale)]);\n ylabel(['x [' axis_prefix 'm]']);\n xlabel(['y [' axis_prefix 'm]']);\n colorbar;\n drawnow;\n \n % plot final multi-scale image\n if scale_index == length(scales) \n figure;\n imagesc(kgrid.y_vec * axis_scale, kgrid.x_vec * axis_scale, max(I_out, [], 3));\n axis image;\n colormap(color_map);\n title('Vessel Filtered Image (MIP), Multi-Scale');\n ylabel(['x [' axis_prefix 'm]']);\n xlabel(['y [' axis_prefix 'm]']);\n colorbar;\n drawnow;\n end\n end\nend\n\n% display total time elapsed\nif disp_updates\n disp([' Total computation time ' scaleTime(etime(clock, start_time))]);\nend\n\n% end of function\nend\n\n% =========================================================================\n% SUB FUNCTIONS\n% =========================================================================\n\nfunction roots = cardanRoots(varargin)\n% Find roots of third order polynomials using Cardan's formula\n%\n% INPUT\n% P: (n x 4) array, each row corresponds to coefficients of each\n% polynomial, P(:,1)*x^3 + P(:,2)*x^2 + P(:,3)*x + P(:,4)\n% OUTPUT\n% roots: (n x 3) array, each row correspond to the roots of P\n%\n% To adjust the parameter below which the the discriminant is considerered\n% as nil, use\n% CardanRoots(P, tol)\n% Adjusting tol is useful to avoid the real roots become complex due to\n% numerical accuracy. The default TOL is 0\n%\n% http://www.sosmath.com/algebra/factor/fac11/fac11.html\n% http://mathforum.org/dr.math/faq/faq.cubic.equations.html\n%\n% See also: roots, ParabolaRoots, eig3\n%\n% Author: Bruno Luong \n% History:\n% Original 20-May-2010\n\n% Copyright (c) 2010, Bruno Luong\n% All rights reserved.\n% \n% Redistribution and use in source and binary forms, with or without \n% modification, are permitted provided that the following conditions are \n% met:\n% \n% * Redistributions of source code must retain the above copyright \n% notice, this list of conditions and the following disclaimer.\n% * Redistributions in binary form must reproduce the above copyright \n% notice, this list of conditions and the following disclaimer in \n% the documentation and/or other materials provided with the distribution\n% \n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n% POSSIBILITY OF SUCH DAMAGE.\n\n% Adjustable parameter\ntol = 0;\n\nif nargin<4\n P = varargin{1};\n a = P(:,1);\n b = P(:,2);\n c = P(:,3);\n d = P(:,4);\n if nargin>=2\n tol = varargin{2};\n end\nelse\n [a, b, c, d] = deal(varargin{1:4});\n if nargin>=5\n tol = varargin{5};\n end\nend\n\nif ~isequal(a,1)\n b = b./a;\n c = c./a;\n d = d./a;\nend\n\nb2 = b.^2;\n\np = -b2/3 + c;\nq = ((2/27)*b2-(1/3)*c).*b + d;\ndelta = q.^2 + (4/27)*p.^3;\n\n% Three cases of discriminant sign\niscmplx = imag(p) | imag(q);\nnotcmplx = ~iscmplx;\ndeltanull = notcmplx & abs(delta)abs(v3);\n u = zeros(size(u3),class(u3));\n v = zeros(size(v3),class(v3));\n u(iu) = exp(log(u3(iu))/3);\n v(iu) = p(iu)./u(iu);\n v(~iu) = exp(log(v3(~iu))/3);\n u(~iu) = p(~iu)./v(~iu);\n\n S1 = u+v;\n\n j = complex(-0.5,sqrt(3)/2);\n j2 = complex(-0.5,-sqrt(3)/2);\n S2 = j*u+j2*v;\n S3 = j2*u+j*v;\n roots = [S1 S2 S3];\n\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/vesselFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6404072393532191}} {"text": "function wc = FWT2_PO(x,L,qmf)\n% FWT2_PO -- 2-d MRA wavelet transform (periodized, orthogonal)\n% Usage\n% wc = FWT2_PO(x,L,qmf)\n% Inputs\n% x 2-d image (n by n array, n dyadic)\n% L coarse level\n% qmf quadrature mirror filter\n% Outputs\n% wc 2-d wavelet transform\n%\n% Description\n% A two-dimensional Wavelet Transform is computed for the\n% array x. To reconstruct, use IWT2_PO.\n%\n% See Also\n% IWT2_PO, MakeONFilter\n%\n\t[n,J] = quadlength(x);\n\twc = x; \n\tnc = n;\n\tfor jscal=J-1:-1:L, % from fine (J) to coarse (L)\n\t\ttop = (nc/2+1):nc; bot = 1:(nc/2);\n\t\tfor ix=1:nc,\n\t\t\trow = wc(ix,1:nc);\n\t\t\twc(ix,bot) = DownDyadLo(row,qmf);\n\t\t\twc(ix,top) = DownDyadHi(row,qmf);\n\t\tend\n\t\tfor iy=1:nc,\n\t\t\trow = wc(1:nc,iy)';\n\t\t\twc(top,iy) = DownDyadHi(row,qmf)';\n\t\t\twc(bot,iy) = DownDyadLo(row,qmf)'; \n\t\t end\n\t\tnc = nc/2; % downsampling\n\tend \n \n%\n% Copyright (c) 1993. David L. Donoho\n% \n \n \n\n \n \n%\n% Part of Wavelab Version 850\n% Built Tue Jan 3 13:20:40 EST 2006\n% This is Copyrighted Material\n% For Copying permissions see COPYING.m\n% Comments? e-mail wavelab@stat.stanford.edu \n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@Wavelet/private/FWT2_PO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6404072393532191}} {"text": "function c=ref_fftreal(f)\n%REF_FFTREAL Reference FFTREAL\n%\n% FFTREAL is computed by doing an FFT, and keeping only the positive\n% frequencies.\n \n\nL=size(f,1);\nc=fft(f);\n\nc=c(1:floor(L/2)+1,:);\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_fftreal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6404072371187239}} {"text": "function BrainNet=SR(BOLD,lambda)\n% FC Network Construction using Sparse Representation (SR)\n%\n% Inpute:\n% BOLD. A cell array with size of N x 1, each cell is a matrix of BOLD signals (#time points x #ROIs) from one of N subject\n% Each subject may have different #time points but should have the same #ROIs\n% lambda. parameter for sparsity\n% \n% Output:\n% BrainNet. FC network (#ROIs x #ROIs x #Subjects)\n%\n% Requires SLEP toolbox: http://www.yelab.net/software/SLEP/\n%\n% By Yu Zhang, zhangyu0112@gmail.com\n% IDEA lab https://www.med.unc.edu/bric/ideagroup\n% Department of Radiology and BRIC, UNC Chapel Hill\n\n\n%% Initialize parameters for SLEP toolbox\nopts=[];\nopts.init=2; % starting point: starting from a zero point here\nopts.tFlag=0; % termination criterion\nopts.nFlag=0; % normalization option: 0-without normalization\nopts.rFlag=1; % regularization % the input parameter 'rho' is a ratio in (0, 1)\nopts.rsL2=0; % the squared two norm term in min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * ||x||_1\nopts.mFlag=0; % treating it as compositive function\nopts.lFlag=0; % Nemirovski's line search\n\n\n%% Construct FC networks using sparse representation\n[nTime,nROI]=size(BOLD{1});\nnSubj=length(BOLD);\nBrainNet=zeros(nROI,nROI,nSubj,'single');\nfor i=1:nSubj\n temp=BOLD{i};\n temp=temp-repmat(mean(temp,2),1,nROI); % centralization\n tempNet=zeros(nROI,nROI);\n for j=1:nROI\n ndic=setdiff(1:nROI,j);\n y=temp(:,j);\n A=temp(:,ndic);\n x=LeastR(A,y,lambda,opts);\n tempNet(ndic,j)=x;\n end\n tempNet=(tempNet+tempNet')/2; % form symmetric adjancency matrix (main diag are zeros)\n tempNet=tempNet-diag(diag(tempNet)); % ignore self connections\n BrainNet(:,:,i)=tempNet;\nend\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Function/SR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6404072371187238}} {"text": "function I = mutualinfo1(A,B)\n%==================================================\n%This is a prog in the MutualInfo 0.9 package written by \n% Hanchuan Peng.\n%\n% I = mutualinfo(vec1,vec2)\n% calculate the mutual information of two vectors\n% \n% For small images this function is faster than \n% function 'mutualinfo2'. \n%==================================================\n\npA = estpa(A);\nHA = estentropy(pA);\n\npB = estpa(B);\nHB = estentropy(pB);\n\npAB = estpab(A,B);\nHAB = estjointentropy(pAB);\n\nI = HA + HB - HAB;\nreturn", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/SRCF_Image_Fuion_Codes/Utils/Metrics/mutualinfo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6403831824289021}} {"text": "\nfunction test_gppde_2d\n\n% $$$ x_g = -5:0.5:5;\n% $$$ [x1_g, x2_g] = meshgrid(\nT = 1;\nL = 1;\n%[x1_g, x2_g] = meshgrid(linspace(-0*T,3*T,60), linspace(-1*L,2*L,40));\nmin_L = 0.0*L;\nmax_L = 1.0*L;\nmin_T = 0.0*T;\nmax_T = 1.0*T;\n[x1_g, x2_g] = meshgrid(linspace(min_T,max_T,40), linspace(min_L,max_L,40));\nX_g = [x1_g(:), x2_g(:)];\n[x1_f, x2_f] = meshgrid(linspace(0,T,45), linspace(0,L,45));\nX_f = [x1_f(:), x2_f(:)];\n\n\n\n% Define the partial differential equation\nN_g = size(X_g, 1);\nswitch 1\n case 1 \n %\n % HEAT EQUATION (d_t - d_x^2 = 0)\n %\n theta = [1 1/10]; % [scale, length scale]\n s2_y = theta(1)^2 * 1e-5;\n\n D = [1 0; % differentiation\n 0 2];\n alpha = [-1; % coefficients\n 0.02]; % (<- heat conduction)\n \n % Spatial boundary fixed to zero\n N_y = 30;\n bound1 = [linspace(min_T,max_T,N_y)', min_L*ones(N_y,1)];\n bound2 = [linspace(min_T,max_T,N_y)', max_L*ones(N_y,1)];\n X_y = [bound1; bound2];\n y = zeros(size(X_y,1),1);\n % Initial function at time T=min_T\n T_obs = min_T + 0.1*(max_T-min_T);\n bound_init = [T_obs*ones(N_y,1), linspace(min_L,max_L,N_y)'];\n X_y = [X_y; bound_init];\n y_init = 2*exp( -0.5*(bound_init(:,2)-0.5*(min_L+max_L)).^2 / 0.1^2);\n y = [y; y_init] + sqrt(s2_y)*randn(size(X_y,1),1);\n\n equation = 'Heat equation';\n \n case 2\n % \n % WAVE EQUATION (d_t^2 - d_x^2 = 0)\n %\n theta = [1 1/30]; % [scale, length scale]\n s2_y = theta(1)^2 * 1e-4;\n\n D = [2 0;\n 0 2];\n alpha = [-1;\n 16]; % speed ^ 2\n % Spatial boundary fixed to zero\n N_y = 100;\n bound1 = [linspace(min_T,max_T,N_y)', min_L*ones(N_y,1)];\n bound2 = [linspace(min_T,max_T,N_y)', max_L*ones(N_y,1)];\n X_y = [bound1; bound2];\n y = zeros(size(X_y,1),1);\n% $$$ % Initial function at time T=min_T\n% $$$ bound_init = [min_T*ones(N_y,1), linspace(min_L,max_L,N_y)'];\n% $$$ X_y = [X_y; bound_init];\n% $$$ y_init = 2*exp( -0.5*(bound_init(:,2)-0.5*(min_L+max_L)).^2 / 0.03^2);\n% $$$ y = [y; y_init];\n y = y + sqrt(s2_y)*randn(size(X_y,1),1);\n \n equation = 'Wave equation';\n\n case 3\n % \n % LAPLACE EQUATION (d_x^2 + d_y^2 = 0)\n %\n theta = [1 1/20]; % [scale, length scale]\n s2_y = theta(1)^2 * 1e-5;\n\n D = [2 0;\n 0 2];\n alpha = [1;\n 1];\n X_y = zeros(0,2);\n y = zeros(0,1);\n \nend\ng = zeros(N_g,1);\n\n% Inference: Get posterior predictive distribution\n[m_f, V_f] = gppde(X_y, y, s2_y, theta, X_g, g, alpha, D, X_f);\n% $$$ figure\n% $$$ imagesc(V_f);\n\n% Draw posterior predictive samples\nsamples = 1;\nI_f = speye(length(V_f));\ns2_f = 1e-8; % numerical reasons\nL_f = chol(V_f + s2_f*I_f, 'lower');\nf = bsxfun(@plus, L_f * randn(length(L_f),samples), m_f);\nfigure\nfor i = 1:samples\n subplot(ceil(sqrt(samples)), ceil(sqrt(samples)), i);\n% pcolor(reshape(f(:,i), size(x1_f)));\n contourf(x1_f, x2_f, reshape(f(:,i), size(x1_f)), 100);\n shading('flat')\n map_colormap();\n cl = max( abs(f(:,i)) );\n set(gca, 'clim', [-cl, cl])\n title(equation)\n xlabel('time');\n xlabel('time');\n ylabel('location');\n set(gca, 'xtick', [], 'ytick', []);\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppde/test_gppde_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6403673961775093}} {"text": "function [s, lambda_k] = tr_subsolver(problem, w, grad, tr_radius, sub_hess_indices, ...\n successful_flag, lambda_k, subproblem_solver,...\n exact_tol, krylov_tol)\n if strcmp(subproblem_solver, 'cauchy_point')\n %Hg = Hv_f(w, new_X, new_Y, grad,alpha);\n Hg = problem.hess_vec(w, grad, sub_hess_indices);\n gBg = grad'*Hg;\n tau = 1;\n if gBg > 0 % if model is convex quadratic the unconstrained minimizer may be inside the TR\n tau = min([(norm(grad))^3 / (tr_radius * gBg), 1]);\n end\n pc = - tau * tr_radius * (grad./norm(grad));\n s = pc;\n lamda_k = 0;\n elseif strcmp(subproblem_solver, 'dog_leg')\n %H = hessian_f(w, new_X, new_Y, alpha);\n H = problem.hess(w, sub_hess_indices);\n gBg = grad'*(H'*grad);\n if gBg <= 0\n error('dog_leg requires H to be positive definite in all steps!') ;\n end\n\n % Compute the Newton Point and return it if inside the TR\n L = chol(H,'lower');\n y = L\\grad;\n pn = -L'\\y;\n% cholesky_B = chol(H,'lower');\n% pn = - (cholesky_B\\grad);\n if (norm(pn) < tr_radius)\n s = pn;\n lambda_k = 0;\n return;\n end\n\n % Compute the 'unconstrained Cauchy Point'\n pc = -((grad'*grad)/gBg) * grad;\n pc_norm = norm(pc);\n\n % if it is outside the TR, return the point where the path intersects the boundary\n if pc_norm >= tr_radius\n p_boundary = pc * (tr_radius / pc_norm);\n s = p_boundary;\n lambda_k = 0;\n return;\n end\n\n\n % else, give intersection of path from pc to pn with tr_radius.\n [t_lower, t_upper] = solve_quadratic_equation(pc, pn, tr_radius);\n p_boundary = pc + t_upper * (pn - pc);\n s = p_boundary;\n lambda_k = 0;\n\n elseif strcmp(subproblem_solver, 'cg')\n grad_norm = norm(grad);\n p_start = zeros(size(grad,1),size(grad,2));\n\n if grad_norm < min([sqrt(norm(grad)) * norm(grad), krylov_tol])\n s = p_start;\n lambda_k = 0;\n return;\n end\n\n % initialize\n z = p_start;\n r = grad;\n d = -r;\n k = 0;\n \n while true\n %Bd = Hv_f(w, new_X, new_Y, d, alpha);\n Bd = problem.hess_vec(w, d, sub_hess_indices);\n dBd = d'*Bd;\n % terminate when encountering a direction of negative curvature with lowest boundary point along current search direction\n if dBd <= 0\n [t_lower, t_upper] = solve_quadratic_equation(z, d, tr_radius);\n p_low = z + t_lower * d;\n p_up = z + t_upper * d;\n %m_p_low = loss_f(w + p_low, X, Y, alpha) + grad'*p_low + 0.5 * p_low'*(H'*p_low);\n %m_p_up = loss_f(w + p_up, X, Y, alpha) + grad'*p_up + 0.5 * p_up'*(H'*p_up);\n \n H = problem.hess(w, sub_hess_indices); % Added by HK (Need to be checked.)\n m_p_low = problem.cost(w+p_low) + grad'*p_low + 0.5 * p_low'*(H'*p_low);\n m_p_up = problem.cost(w+p_up) + grad'*p_up + 0.5 * p_up'*(H'*p_up); \n problem.cost(w);\n if m_p_low < m_p_up\n s = p_low;\n lambda_k = 0;\n return;\n else\n s = p_up;\n lambda_k = 0;\n return;\n end\n end\n\n\n alpha = (r'*r) / dBd;\n z_next = z + alpha * d;\n % terminate if z_next violates TR bound\n if norm(z_next) >= tr_radius\n % return intersect of current search direction w/ boud\n [t_lower, t_upper] = solve_quadratic_equation(z, d, tr_radius);\n s = z + t_upper * d;\n lambda_k = 0;\n return;\n end\n \n r_next = r + alpha * Bd;\n if norm(r_next) < min([sqrt(norm(grad)) * norm(grad),krylov_tol])\n s = z_next;\n lambda_k = 0;\n return;\n end\n\n beta_next = (r_next'*r_next) / (r'*r);\n d_next = -r_next + beta_next * d;\n % update iterates\n z = z_next;\n r = r_next;\n d = d_next;\n k = k + 1;\n end\n elseif strcmp(subproblem_solver, 'GLTR')\n g_norm = norm(grad);\n s = zeros(size(grad,1), size(grad,2));\n \n if g_norm == 0\n % escape along the direction of the leftmost eigenvector as far as tr_radius permits\n fprintf('zero gradient encountered');\n %H = hessian_f(w, new_X, new_Y, alpha);\n H = problem.hess(w, sub_hess_indices);\n [s, lambda_k] = exact_TR_suproblem_solver(grad, H, tr_radius, exact_tol, successful_flag, lambda_k);\n else\n % initialize\n g = grad;\n p = -g;\n gamma = g_norm;\n T = zeros(1, 1);\n alpha_k = [];\n beta_k = [];\n interior_flag = true;\n k = 0;\n \n while true\n %Hp = Hv_f(w, new_X, new_Y, p, alpha);\n Hp = problem.hess_vec(w, p, sub_hess_indices);\n pHp = p'*Hp;\n alpha = g'*g / pHp;\n \n alpha_k = [alpha_k; alpha];\n \n %Lanczos Step 1: Build up subspace \n % a) Create g_lanczos = gamma*e_1\n \n e_1 = zeros(k + 1, 1);\n e_1(1) = 1.0;\n g_lanczos = gamma .* e_1;\n \n % b) Create T for Lanczos Model \n T_new = zeros(k + 1, k + 1);\n if k == 0\n T(k+1, k+1) = 1.0/alpha;\n T_new(1:k+1, 1:k+1) = T;\n else\n T_new(1:size(T,1), 1:size(T,2)) = T;\n T_new(k+1, k+1) = 1.0 / alpha + beta_/ alpha_k(k);\n T_new(k, k+1) = sqrt(beta_) / abs(alpha_k(k));\n T_new(k+1, k) = sqrt(beta_) / abs(alpha_k(k));\n T = T_new; \n end\n \n if (interior_flag == true && alpha < 0) || norm(s + alpha * p) >= tr_radius\n interior_flag = false;\n end\n \n if interior_flag == true\n s = s + alpha * p;\n else\n % Lanczos Step 2: solve problem in subspace\n [h, lambda_k] = exact_TR_suproblem_solver(g_lanczos, T, tr_radius, exact_tol, successful_flag, lambda_k);\n end\n g_next = g + alpha * Hp;\n \n % test for convergence\n e_k = zeros(k + 1,1);\n e_k(k+1) = 1.0;\n \n if interior_flag == true && norm(g_next) < min([sqrt(norm(grad)) * norm(grad), krylov_tol])\n break;\n end\n if interior_flag == false && norm(g_next) * abs(h'*e_k) < min([sqrt(norm(grad)) * norm(grad), krylov_tol]) \n break;\n end\n \n if k == problem.d\n fprintf('Krylov dimensionality reach full space! Breaking out..\\n');\n break;\n end\n beta_ = (g_next'*g_next) / (g'*g);\n beta_k = [beta_k; beta_];\n p = -g_next + beta_ * p;\n g = g_next;\n k = k + 1;\n end\n \n if interior_flag == false\n % Recover Q by building up the lanczos space, TBD: keep storable Qs in memory\n n = size(grad,1);\n Q1 = zeros(n, k + 1);\n \n g = grad;\n p = -g;\n \n for j = 0 : k\n gn = norm(g);\n if j == 0\n sigma = 1;\n else\n sigma = -sign(alpha_k(j)) * sigma;\n end\n Q1(:, j+1) = sigma * g / gn;\n \n\n if ~ (j == k)\n %Hp = Hv_f(w, new_X, new_Y, p, alpha);\n Hp = problem.hess_vec(w, p, sub_hess_indices);\n g = g + alpha_k(j+1) * Hp;\n p = -g + beta_k(j+1) * p;\n end\n end\n \n % compute final step in R^n\n s = Q1*h;\n end\n end\n elseif strcmp(subproblem_solver, 'exact')\n %H = hessian_f(w, new_X, new_Y, alpha);\n Hw = problem.hess(w, sub_hess_indices);\n [s, lambda_k] = exact_TR_suproblem_solver(grad, H, tr_radius, exact_tol, successful_flag, lambda_k);\n else\n \terror('solver unknown\\n');\n end\nend\n\nfunction [s, lambda_j] = exact_TR_suproblem_solver(grad, H, tr_radius, exact_tol, successful_flag, lambda_k)\n\n s = zeros(size(grad,1),size(grad,2));\n % Step 0: initialize safeguards\n H_ii_min = min(diag(H));\n absH = abs(H);\n H_max_norm = sqrt((size(H,1))^2) * max(absH(:));\n H_fro_norm = norm(H, 'fro');\n list_l = [];\n list_u = [];\n for i = 1 : length(H)\n l = H(i, i) + sum(abs(H(i, :))) - abs(H(i, i));\n u = -H(i, i) + sum(abs(H(i, :))) - abs(H(i, i));\n list_l = [list_l l];\n list_u = [list_u u];\n end\n gerschgorin_l = max(list_l);\n gerschgorin_u = max(list_u);\n\n lambda_lower = max([0, -H_ii_min, norm(grad) / tr_radius - min([H_fro_norm, H_max_norm, gerschgorin_l])]);\n lambda_upper = max([0, norm(grad) / tr_radius + min([H_fro_norm, H_max_norm, gerschgorin_u])]);\n\n if successful_flag == false && (lambda_lower <= lambda_k) && (lambda_k <= lambda_upper) % reinitialize at previous lambda in case of unscuccesful iterations\n lambda_j = lambda_k;\n elseif lambda_lower == 0 % allow for fast convergence in case of inner solution\n lambda_j = lambda_lower;\n else\n lambda_j = lambda_lower + (lambda_upper-lambda_lower)*rand(1,1);\n end\n\n i = 0;\n % Root Finding\n while true\n i = i + 1;\n lambda_in_N = false;\n lambda_plus_in_N = false;\n B = H + lambda_j * eye(size(H,1), size(H,2));\n try\n % 1 Factorize B\n L = chol(B, 'lower');\n % 2 Solve LL^Ts=-g\n Li = inv(L);\n s = - (Li'*Li)*grad;\n sn = norm(s);\n % 2.1 Termination: Lambda in F, if q(s(lamda)) stop. By Conn: Lemma 7.3.5:\n phi_lambda = 1.0 / sn - 1.0 / tr_radius;\n %if (abs(sn - tr_radius) <= exact_tol * tr_radius):\n if (abs(phi_lambda)<=exact_tol) %\n break;\n end\n \n % 3 Solve Lw=s\n w = Li*s;\n wn = norm(w);\n \n % Step 1: Lambda in L\n if lambda_j > 0 && (phi_lambda) < 0\n % print ('lambda: ',lambda_j, ' in L')\n lambda_plus = lambda_j + ((sn - tr_radius) / tr_radius) * ((sn^2) / (wn^2));\n lambda_j = lambda_plus;\n \n % Step 2: Lambda in G (sn 0 && lambda_j > 0 && any(grad ~= 0) % TBD: remove grad\n % print ('lambda: ',lambda_j, ' in G')\n lambda_upper = lambda_j;\n lambda_plus = lambda_j + ((sn - tr_radius) / tr_radius) * ((sn^2) / (wn^2));\n \n % Step 2a: If factorization succeeds: lambda_plus in L\n if lambda_plus > 0\n try\n % 1 Factorize B\n B_plus = H + lambda_plus * eye(size(H,1), size(H,2));\n L = chol(B_plus, 'lower');\n lambda_j = lambda_plus;\n % print ('lambda+', lambda_plus, 'in L')\n catch \n lambda_plus_in_N = true;\n end\n end\n \n % Step 2b/c: If not: Lambda_plus in N\n if lambda_plus <= 0 || lambda_plus_in_N == true\n % 1. Check for interior convergence (H pd, phi(lambda)>=0, lambda_l=0)\n try\n U = chol(H, 'upper');\n H_pd = true;\n catch \n H_pd = false;\n end\n \n if lambda_lower == 0 && H_pd == true && phi_lambda >= 0 %cannot happen in ARC!\n lambda_j = 0;\n % print ('inner solution found');\n break;\n % 2. Else, choose a lambda within the safeguard interval\n else\n % print ('lambda_plus', lambda_plus, 'in N')\n lambda_lower = max([lambda_lower, lambda_plus]); % reset lower safeguard\n lambda_j = max([sqrt(lambda_lower * lambda_upper),lambda_lower + 0.01 * (lambda_upper - lambda_lower)]);\n lambda_upper = single(lambda_upper); \n \n if lambda_lower == lambda_upper\n lambda_j = lambda_lower;\n % Hard case\n [ev, ew] = eig(H);\n d = ev(:, 1);\n dn = norm(d);\n assert((ew == -lambda_j), 'Ackward: in hard case but lambda_j != -lambda_1');\n [tao_lower, tao_upper] = mitternachtsformel(1, 2*(s'*d), (s'*s)-tr_radius^2);\n s = s + tao_lower * d;\n fprintf('hard case resolved inside');\n end\n end\n end\n \n elseif (phi_lambda) == 0\n break;\n else % TBD: move into if lambda+ column #this only happens for Hg=0 -> s=(0,..,0)->phi=inf -> lambda_plus=nan -> hard case (e.g. at saddle) \n lambda_in_N = true;\n end \n % Step 3: Lambda in N\n catch\n lambda_in_N = true;\n end\n \n if lambda_in_N == true\n % print ('lambda: ',lambda_j, ' in N')\n try\n U = chol(H, 'upper');\n H_pd = true;\n catch \n H_pd = false;\n end\n \n % 1. Check for interior convergence (H pd, phi(lambda)>=0, lambda_l=0)\n if lambda_lower == 0 && H_pd == true && phi_lambda >= 0\n lambda_j = 0;\n %print ('inner solution found')\n break;\n % 2. Else, choose a lambda within the safeguard interval\n else\n lambda_lower = max([lambda_lower, lambda_j]); % reset lower safeguard\n lambda_j = max([sqrt(lambda_lower * lambda_upper),lambda_lower + 0.01 * (lambda_upper - lambda_lower)]); % eq 7.3.14\n lambda_upper = single(lambda_upper);\n % Check for Hard Case:\n if lambda_lower == lambda_upper\n lambda_j = lambda_lower;\n [ev, ew] = eig(H);\n d = ev(:, 1);\n dn = norm(d);\n assert((ew == -lambda_j), 'Ackward: in hard case but lambda_j != -lambda_1');\n [tao_lower, tao_upper] = mitternachtsformel(1, 2*(s'*d), (s'*s)-tr_radius^2);\n s = s + tao_lower * d;\n\n fprintf('hard case resolved outside');\n end\n end\n end\n end\n \n % compute final step\n B = H + lambda_j * eye(size(H,1), size(H,2));\n % 1 Factorize B\n L = chol(B, 'lower');\n % 2 Solve LL^Ts=-g\n Li = inv(L);\n s = - Li'*Li*grad;\n %print (i,' exact solver iterations')\n\nend\n\n\n% Auxiliary Functions\nfunction [t_lower, t_upper] = mitternachtsformel(a, b, c)\n sqrt_discriminant = sqrt(b * b - 4 * a * c);\n t_lower = (-b - sqrt_discriminant) / (2 * a);\n t_upper = (-b + sqrt_discriminant) / (2 * a);\nend\n\nfunction [t_lower, t_upper] = solve_quadratic_equation(pc, pn, tr_radius)\n % solves ax^2+bx+c=0\n a = (pn - pc)'*(pn - pc);\n b = 2 * (pc'*(pn - pc));\n c = (pc'*pc) - tr_radius^2;\n sqrt_discriminant = sqrt(b * b - 4 * a * c);\n t_lower = (-b - sqrt_discriminant) / (2 * a);\n t_upper = (-b + sqrt_discriminant) / (2 * a);\nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/sgd_solver/tr_subsolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6403673648733333}} {"text": "function y = logmvn(X, Mu, Sigma, options)\n%LOGMVN Evaluate the logarithms of normal density functions.\n%The function evaluates the logarithm of Gaussian density function given \n%data at X(n,:) with center at Mu(n,:) and covariance matrix Sigma(:,:,n).\n%The code can handle different means and covariance matrices for each \n%sample. It is much faster than the native function mvnpdf.\n%\n% Input: \n% X - N by D data. N is the number of samples. D is the number of\n% dimensions.\n% Mu - N by D (multiple) or 1 by D (single) mean.\n% Sigma - D by D by N (multiple) or D by D (single) covariance matrice.\n% Options - structure containing indices for transforming the Sigma to a\n% sparse matrix. Usually no need to set.\n% Output:\n% y - N by 1 results that contain the logarithm of the Gaussians.\n%\n% Example:\n%\n% N = 1000;\n% D = 2;\n% Mu = [1 -1]; \n% Mu = repmat(Mu, 1000, 1) + randn(N,D);\n% SN = repmat(reshape(abs(randn(N,1)), [1,1,N]), D, D) .* repmat(eye(D), [1,1,N]);\n% Sigma = [.9 .4; .4 .3];\n% Sigma = repmat(Sigma, [1,1,N]) + SN;\n% X = mvnrnd(Mu,Sigma,1000); \n% \n% tic\n% y = logmvn(X, Mu, Sigma);\n% y = exp(y);\n% toc\n% \n% tic\n% y1 = mvnpdf(X, Mu, Sigma);\n% toc\n% \n% norm(y-y1)\n%\n% Author: Yuan Zhou (zhouyuanzxcv@gmail.com)\n\n% Copyright (C) 2015\nif nargin < 4\n options = [];\nend\n\nif size(Mu,1) == 1 && ndims(Sigma) == 2 % single\n y = loggausspdf(X, Mu, Sigma);\nelseif size(Mu,1) == size(X,1) && size(Sigma,3) == size(X,1) % multiple means\n y = logmvn_multiple(X, Mu, Sigma, options);\nend\n\nend\n\nfunction y = logmvn_multiple(X, Mu, Sigma, options)\n[N,B] = size(X);\n\n% Transform the sigma matrix to a sparse block diagonal matrix\nif ~isempty(options) && isfield(options,'sigma_update_in_logmvn')\n sparse_update_inplace(options.sigma_update_in_logmvn, Sigma(:));\n Sigma1 = options.sigma_update_in_logmvn;\nelse\n if ~isempty(options) && isfield(options,'Is') && isfield(options,'Js')\n Is = options.Is;\n Js = options.Js;\n else\n Is = (1:N*B);\n Is = repmat(reshape(Is, [B,1,N]), 1, B);\n Is = Is(:);\n \n Js = (1:N*B);\n Js = repmat(reshape(Js, [1,B,N]), B, 1);\n Js = Js(:);\n end\n\n Sigma1 = sparse(Is,Js,reshape(Sigma,N*B*B,1),N*B,N*B);\nend\n\n% Compute the Cholesky decomposition\n[R,err] = chol(Sigma1);\nif err ~= 0\n error('A Covariance matrix is not positive definite.');\nend\n\n% Final calculation\nY1 = X - Mu;\n\nx1 = reshape(Y1', 1, N*B) / R;\nx1 = sum(reshape(x1, B, N).^2, 1)';\nx2 = sum(reshape(log(diag(R)),B,N), 1)';\n\ny = -0.5 * x1 - x2 - B * log(2*pi) / 2;\nend\n\nfunction y = loggausspdf(X, mu, Sigma)\nX = X';\nmu = mu';\nd = size(X,1);\nX = bsxfun(@minus,X,mu);\n[U,p]= cholcov(Sigma);\nif p ~= 0\n error('ERROR: Sigma is not PD.');\nend\nQ = U'\\X;\nq = dot(Q,Q,1); % quadratic term (M distance)\nc = d*log(2*pi)+2*sum(log(diag(U))); % normalization constant\ny = -(c+q)/2;\n\ny = y';\nend", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/common/logmvn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.64033390734163}} {"text": "% fig_error_J.m\n% plot maximum normalized error vs J using QR method\n% for min-max NUFFT with uniform scaling factors\n% This is Fig. 3 in the 2003 IEEE T-SP paper.\n% Jeff Fessler, The University of Michigan\n\nif ~isvar('emax')\n%\tNlist = 1;\n\tNlist = 2^10;\n\tMlist = [1.5 2 2.5 3 4 5];\t% over-sampling factors\n%\tJlist = [2:11];\n\tJlist = [2:20];\t% neighborhood size\n\n\t[JJ, MM, NN] = ndgrid(Jlist, Mlist, Nlist);\n\n\temax = zeros(size(NN));\n\n\talpha = [1]; beta = [];\n\tfor ii=1:numel(NN)\n\t\tN = NN(ii);\n\t\tJ = JJ(ii);\n\t\tM = MM(ii);\n\t\tprintf('M=%d J=%d', M, J)\n\t\tK = M * N;\n\t\tgam = 2*pi/K;\n\t\tom = gam * [0:20]'/40;\n\t\temax(ii) = max(nufft1_err_mm(om, N, J, K, 'qr', alpha, beta));\n\tend\nend\n\n\n%\n% plot min-max errors\n%\nif 1\n\tsemilogy(Jlist, emax(:,1), '-o', ...\n\t\tJlist, emax(:,2), '-d', ...\n\t\tJlist, emax(:,3), '-^', ...\n\t\tJlist, emax(:,4), '-s', ...\n\t\tJlist, emax(:,5), '-p', ...\n\t\tJlist, emax(:,6), '-+')\n%\t\tJlist(Jlist <= 99), emax(Jlist <= 99, 2), '-d', ...\n%\t\tJlist(Jlist <= 98), emax(Jlist <= 98, 3), '-^', ...\n%\t\tJlist(Jlist <= 96), emax(Jlist <= 96, 4), '-s', ...\n%\t\tJlist(Jlist <= 95), emax(Jlist <= 95, 5), '-p')\n%\taxis([minmax(Jlist)'+[-0.2 0.2] 1e-5 1e-1])\n%\taxis tight\n%\taxisx([minmax(Jlist)'+[-0.2 0.2]])\n\taxis([minmax(Jlist)'+[-0.2 0.2] 1e-10 1e-0])\n\txtick([2:3:20])\n\tytick(10.^[-10:2:0])\n%\ttext(2.2, 2e-4, '(for unit-norm signal)')\n\txlabel J, ylabel 'E_{max}'\n\ttitle(sprintf('Maximum error for \\\\alpha = (%g)', alpha))\n\tleg = {};\n\tfor ii=1:length(Mlist)\n\t\tleg{ii} = sprintf('K/N=%g', Mlist(ii));\n\tend\n\tlegend(leg)\n\n%\tir_savefig c 'fig_error_J'\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/tsp2003figs/fig_error_J.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6403338881113423}} {"text": "%\n% Author: Marius Drulea\n% http://www.cv.utcluj.ro/optical-flow.html\n\n% References\n% M. Drulea and S. Nedevschi, \"Total variation regularization of \n% local-global optical flow,\" in Intelligent Transportation Systems (ITSC), \n% 2011 14th International IEEE Conference on, 2011, pp. 318-323.\n\n% Copyright (C) 2011 Technical University of Cluj-Napoca\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\nfunction [u, v, pu, pv] = solve_clg_tv_equation(u, v, u0, v0, pu, pv, ...\n I1, Ix, Iy, It, D, settings)\n%%\nlambda = settings.lambda;\n\ntheta = 0.5;\ntau = 0.5;\n% tau = 1.0/(4.0*theta + epsilon);\n\nder_mask = [0 -1 1];\nadjoint_der_mask = [-1 1 0];\n\nif settings.use_bilateral == 1 \n r0 = It - u0.*Ix - v0.*Iy;\n % apply the bilateral filter to the data terms\n [W_Ix_2, W_Ixy, W_Iy_2, W_Ix_r0, W_Iy_r0] = ...\n applyBilateralFilterToDataTerms(I1, Ix.*Ix, Ix.*Iy, Iy.*Iy, Ix.*r0, Iy.*r0, ...\n settings.wSize, settings.sigma_d, settings.sigma_r);\nelse \n gauss = fspecial('gaussian', [settings.wSize settings.wSize], settings.wSize/6);\n\n W_Ix_2 = imfilter(Ix.^2, gauss, 'replicate');\n W_Ixy = imfilter(Ix.*Iy, gauss, 'replicate');\n W_Iy_2 = imfilter(Iy.^2, gauss, 'replicate');\n\n r0 = It - u0.*Ix - v0.*Iy;\n W_Ix_r0 = imfilter(Ix.*r0, gauss, 'replicate');\n W_Iy_r0 = imfilter(Iy.*r0, gauss, 'replicate');\nend\n\na11 = 1 + 2*lambda*theta*W_Ix_2;\na12 = 2*lambda*theta*W_Ixy;\na21 = a12;\na22 = 1 + 2*lambda*theta*W_Iy_2;\nl_t_2_W_Ix_r0 = 2*lambda*theta*W_Ix_r0;\nl_t_2_W_Iy_r0 = 2*lambda*theta*W_Iy_r0;\n\ndelta = a11.*a22 - a21.*a12;\n%%\nfor k = 1:settings.its\n %% \n % 1. update the coupling variable \n \n b1 = u - l_t_2_W_Ix_r0; \n b2 = v - l_t_2_W_Iy_r0;\n \n % update u_ and v_ \n deltaU_ = b1.*a22 - b2.*a12;\n deltaV_ = b2.*a11 - b1.*a21;\n \n u_ = deltaU_./delta;\n v_ = deltaV_./delta;\n \n %% \n % compute the divergence of the dual variable\n % the adjoint of the nabla (derivative) operator = (- divergence) operator\n \n div_u = imfilter(pu(:, :, 1), adjoint_der_mask, 'replicate') + ...\n imfilter(pu(:, :, 2), adjoint_der_mask', 'replicate');\n div_v = imfilter(pv(:, :, 1), adjoint_der_mask, 'replicate') + ...\n imfilter(pv(:, :, 2), adjoint_der_mask', 'replicate');\n \n % update primal variable u\n u = u_ + theta*div_u;\n \n % update primal variable v\n v = v_ + theta*div_v;\n \n % compute nabla(u); the derivative operator \n ux = imfilter(u, der_mask, 'replicate');\n uy = imfilter(u, der_mask', 'replicate'); \n vx = imfilter(v, der_mask, 'replicate');\n vy = imfilter(v, der_mask', 'replicate');\n\n % update dual variable; gradient descent\n % p = p_k + tau*nabla(u);\n pu(:, :, 1) = pu(:, :, 1) + tau * ux;\n pu(:, :, 2) = pu(:, :, 2) + tau * uy;\n pv(:, :, 1) = pv(:, :, 1) + tau * vx;\n pv(:, :, 2) = pv(:, :, 2) + tau * vy;\n \n % project the dual variable to ensure the inequality |p| <= D\n % p = p./max(|p|, D) .* D;\n pu(:, :, 1) = pu(:, :, 1)./max(abs(pu(:, :, 1)), D) .* D;\n pu(:, :, 2) = pu(:, :, 2)./max(abs(pu(:, :, 2)), D) .* D;\n pv(:, :, 1) = pv(:, :, 1)./max(abs(pv(:, :, 1)), D) .* D;\n pv(:, :, 2) = pv(:, :, 2)./max(abs(pv(:, :, 2)), D) .* D;\nend\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/VSRnet/external_functions/CLG-TV-matlab/solve_clg_tv_equation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.640333886963866}} {"text": "function [month, day, year] = gdate (jdate)\n\n% convert Julian date to Gregorian (calendar) date\n\n% input\n\n% jdate = julian day\n\n% output\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% note: day may include fractional part\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\njd = jdate;\n\nz = fix(jd + .5);\nfday = jd + .5 - z;\n\nif (fday < 0)\n fday = fday + 1;\n z = z - 1;\nend\n\nif (z < 2299161)\n a = z;\nelse\n alpha = floor((z - 1867216.25) / 36524.25);\n a = z + 1 + alpha - floor(alpha / 4);\nend\n\nb = a + 1524;\nc = fix((b - 122.1) / 365.25);\nd = fix(365.25 * c);\ne = fix((b - d) / 30.6001);\nday = b - d - fix(30.6001 * e) + fday;\n\nif (e < 14)\n month = e - 1;\nelse\n month = e - 13;\nend\n\nif (month > 2)\n year = c - 4716;\nelse\n year = c - 4715;\nend\n\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/jpl_ephem/gdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.7217432122827969, "lm_q1q2_score": 0.6403338848113419}} {"text": "function i = binary_to_i4 ( s )\n\n%*****************************************************************************80\n%\n%% BINARY_TO_I4 converts a binary representation into an integer value.\n%\n% Example:\n%\n% S I\n%\n% '101' 5 \n% '-1000' -8 \n% '1' 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the binary representation.\n%\n% Output, integer I, the integer whose representation was input.\n%\n nchar = s_len_trim ( s );\n \n i = 0;\n ichr = 1;\n istate = 0;\n isgn = 1;\n \n while ( ichr <= nchar )\n\n c = s(ichr);\n%\n% Blank.\n%\n if ( c == ' ' )\n \n if ( istate == 2 )\n istate = 3;\n end\n%\n% Sign, + or -.\n%\n elseif ( c == '-' )\n\n if ( istate == 0 )\n istate = 1;\n isgn = - 1;\n else\n istate = - 1;\n end\n\n elseif ( c == '+' )\n\n if ( istate == 0 )\n istate = 1;\n else\n istate = - 1;\n end\n%\n% Digit, 0 or 1.\n%\n elseif ( c == '1' )\n\n i = 2 * i;\n i = i + 1;\n istate = 2;\n\n elseif ( c == '0' )\n \n i = 2 * i;\n istate = 2;\n%\n% Illegal or unknown sign.\n%\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BINARY_TO_I4 - Serious error!\\n' );\n fprintf ( 1, ' Illegal digit = \"%c\"\\n', c );\n fprintf ( 1, ' Conversion halted prematurely!\\n' );\n error ( 'BINARY_TO_I4 - Serious error!' );\n\n end\n\n if ( istate == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BINARY_TO_I4 - Serious error!\\n' );\n fprintf ( 1, ' Unable to decipher input!\\n' );\n error ( 'BINARY_TO_I4 - Serious error!' );\n end\n\n if ( 3 <= istate )\n break;\n end\n\n ichr = ichr + 1;\n\n end\n%\n% Apply the sign.\n%\n i = isgn * i;\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/chrpak/binary_to_i4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.6402676412848051}} {"text": "function [x, infos] = als_nmf(V, rank, in_options)\n% Alternative least squares (ALS) for non-negative matrix factorization (NMF).\n%\n% The problem of interest is defined as\n%\n% min || V - WH ||_F^2,\n% where \n% {V, W, H} > 0.\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n% V : (m x n) non-negative matrix to factorize\n% rank : rank\n% in_options \n% alg : als: Alternative least squares (ALS)\n%\n% : hals: Hierarchical alternative least squares (Hierarchical ALS)\n% Reference:\n% Andrzej Cichocki and PHAN Anh-Huy,\n% \"Fast local algorithms for large scale nonnegative matrix and tensor factorizations,\"\n% IEICE Transactions on Fundamentals of Electronics, Communications and Computer Sciences, \n% vol. 92, no. 3, pp. 708-721, 2009.\n%\n% : acc_hals: Accelerated hierarchical alternative least squares (Accelerated HALS)\n% Reference:\n% N. Gillis and F. Glineur, \n% \"Accelerated Multiplicative Updates and hierarchical ALS Algorithms for Nonnegative \n% Matrix Factorization,\", \n% Neural Computation 24 (4), pp. 1085-1105, 2012. \n% See http://sites.google.com/site/nicolasgillis/.\n% The corresponding code is originally created by the authors, \n% Then, it is modifided by H.Kasai.\n%\n%\n% Outputs:\n% x : non-negative matrix solution, i.e., x.W: (m x rank), x.H: (rank x n)\n% infos : log information\n% epoch : iteration nuber\n% cost : objective function value\n% optgap : optimality gap\n% time : elapsed time\n% grad_calc_count : number of sampled data elements (gradient calculations)\n%\n%\n% This file is part of NMFLibrary\n%\n% Created by H.Kasai on Mar. 24, 2017\n%\n% Change log: \n%\n% Oct. 27, 2017 (Hiroyuki Kasai): Fixed algorithm. \n%\n% Apr. 22, 2019 (Hiroyuki Kasai): Fixed bugs.\n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n% Jun. 24, 2022 (Hiroyuki Kasai): Added momentum acceleration mode and mofified.\n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n \n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = [];\n local_options.alg = 'hals';\n local_options.sub_mode = 'std';\n local_options.alpha = 2;\n local_options.delta = 0.1;\n local_options.inner_max_epoch = 500;\n local_options.inner_max_epoch_parameter = 0.5; \n local_options.beta0 = 0.5;\n local_options.eta = 1.5; \n local_options.gammabeta = 1.01;\n local_options.gammabetabar = 1.005; \n local_options.momentum_h = 0; \n local_options.momentum_w = 0; \n local_options.scaling = true;\n local_options.warm_restart = false; \n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options); \n\n % set paramters\n if ~strcmp(options.alg, 'als') && ~strcmp(options.alg, 'hals') ...\n && ~strcmp(options.alg, 'acc_hals')\n fprintf('Invalid algorithm: %s. Therfore, we use hals (i.e., Hierarchical ALS).\\n', options.alg);\n options.alg = 'hals';\n end\n\n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W;\n H = init_factors.H; \n \n % initialize\n method_name = sprintf('ALS (%s:%s)', options.alg, options.sub_mode);\n epoch = 0; \n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n\n % intialize for als \n if strcmp(options.alg, 'acc_hals')\n eit1 = cputime; \n VHt = V*H'; \n HHt = H*H'; \n \n scaling = sum(sum(VHt.*W))/sum(sum( HHt.*(W'*W) )); \n W = W * scaling;\n \n options_halsupdt = [];\n end \n \n if options.scaling\n [W, H] = normalize_WH(V, W, H, rank, 'type1');\n end\n \n [options, beta, betamax] = check_momemtum_setting(options); \n \n if options.warm_restart\n nV = norm(V, 'fro');\n rel_error = zeros(1, options.max_epoch);\n rel_error(1) = sqrt(nV^2 - 2*sum(sum(V * H' .* W)) + sum(sum( H * H' .* (W'*W)))) / nV; \n end\n W_prev = W; \n H_prev = H; \n \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n end \n \n % set start time\n start_time = tic();\n\n % main loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end\n \n\n %% update H\n VtW = V'*W;\n WtW = W'*W;\n WtV = W' * V; \n \n if strcmp(options.alg, 'als')\n \n %H = (W*pinv(W'*W))' * V;\n H = WtW \\ WtV; % H = inv(W'*W) * W' * V;\n H = H .* (H>0);\n\n elseif strcmp(options.alg, 'hals')\n \n for k=1:rank\n tmp = (VtW(:,k)' - (WtW(:,k)' * H) + (WtW(k,k) * H(k,:))) / WtW(k,k);\n tmp(tmp<=eps) = eps;\n H(k,:) = tmp;\n end \n \n elseif strcmp(options.alg, 'acc_hals')\n\n eit1 = cputime; \n options_halsupdt.max_epoch = change_inner_max_epoch(V, W, options);\n H = HALSupdt(H, WtW, WtV, eit1, options.alpha, options.delta, options_halsupdt); \n\n end\n \n % perform momentum for H\n if strcmp(options.sub_mode, 'momentum')\n [H, H_tmp1, H_tmp2] = do_momentum_h(H, H_prev, beta, epoch, options);\n end\n \n \n \n %% update W\n VHt = V * H';\n HHt = H * H';\n \n if strcmp(options.alg, 'als')\n \n %W = ((inv(H*H')*H)*V')';\n W = VHt / HHt; % W = V * H' * inv(H*H');\n W = (W>0) .* W;\n \n % normalize columns to unit \n W = W ./ (repmat(sum(W), m, 1)+eps); \n\n elseif strcmp(options.alg, 'hals')\n\n for k=1:rank\n tmp = (VHt(:,k) - (W * HHt(:,k)) + (W(:,k) * HHt(k,k))) / HHt(k,k);\n tmp(tmp<=eps) = eps;\n W(:,k) = tmp;\n end\n \n elseif strcmp(options.alg, 'acc_hals')\n \n% if epoch > 0 % Do not recompute A and B at first pass\n % Use actual computational time instead of estimates rhoU\n eit1 = cputime; \n eit1 = cputime-eit1; \n% end\n options_halsupdt.max_epoch = change_inner_max_epoch(V', H', options);\n W = HALSupdt(W', HHt',VHt', eit1, options.alpha, options.delta, options_halsupdt); \n W = W';\n\n end \n \n % perform momentum for W \n if strcmp(options.sub_mode, 'momentum')\n [W, H, W_tmp1] = do_momentum_w(W, W_prev, H, H_prev, H_tmp1, beta, epoch, options);\n end \n \n % perform warm_restart\n if options.warm_restart\n [W, H, W_prev, H_prev, rel_error, beta, betamax, options] = ...\n warm_restart(V, W, H, rank, W_prev, H_prev, W_tmp1, H_tmp1, H_tmp2, rel_error, beta, betamax, epoch, options);\n end \n \n % measure elapsed time\n elapsed_time = toc(start_time); \n \n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n;\n \n % update epoch\n epoch = epoch + 1; \n \n % store info\n infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time); \n \n % display info\n display_info(method_name, epoch, infos, options);\n \n end\n \n x.W = W;\n x.H = H;\n\nend", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/frobenius_norm/als_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6402515984284628}} {"text": "function [ mColumnVectorImage ] = ImageToColumnsSliding( mInputImage, vBlockSize )\n% ----------------------------------------------------------------------------------------------- %\n% [ mColumnImage ] = ImageToColumns( mInputImage, blockRadius )\n% Creates an column image from the sliding neighborhood in mInpuImage\n% Input:\n% - mInputImage - Input image.\n% Structure: Image Matrix (Single Channel)\n% Type: 'Single' / 'Double'.\n% Range: [0, 1].\n% - vBlockSize - Block Size.\n% Structure: 2D Vector.\n% Type: 'Single' / 'Double'.\n% Range: [0, 1].\n% Output:\n% - mColumnVectorImage - Column Vector Image.\n% Structure: Image Matrix (Single Channel)\n% Type: 'Single' / 'Double'.\n% Range: [0, 1].\n% Remarks:\n% 1. Prefixes:\n% - 'm' - Matrix.\n% - 'v' - Vector.\n% 2. Converts each sliding `vBlockSize(1)` by `vBlockSize(2) block of\n% `mInputImage` into a column of `mColumnVectorImage` with no zero\n% padding.\n% 3. Shouldn't be used for images larger than 400x400 and blocks of\n% 51x51.\n% TODO:\n% 1. I\n% Release Notes:\n% - 1.0.000 20/03/2015 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\n\n[numRows, numCol] = size(mInputImage);\nblockNumRows = vBlockSize(1);\nblockNumCols = vBlockSize(2);\n\n% Create Hankel-like indexing sub matrix.\nnc = numRows - blockNumRows + 1;\nnn = numCol - blockNumCols + 1;\n\nvColumnIdx = [(0:(blockNumRows - 1))]';\nvRowIdx = [1:nc];\n\nt = vColumnIdx(:, ones(nc, 1)) + vRowIdx(ones(blockNumRows, 1), :); % Hankel Subscripts\ntt = zeros(blockNumRows * blockNumCols, nc);\nrows = 1:blockNumRows;\nfor ii = 0:(blockNumCols - 1)\n tt(((ii * blockNumRows) + rows), :) = t + (numRows * ii);\nend\nmColumnVectorImageIdx = zeros((blockNumRows * blockNumCols), (nc * nn));\ncols = 1:nc;\nfor jj = 0:(nn - 1)\n mColumnVectorImageIdx(:, ((jj * nc) + cols)) = tt + (numRows * jj);\nend\n\nmColumnVectorImage = mInputImage(mColumnVectorImageIdx);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q2969/ImageToColumnsSliding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6402515976455541}} {"text": "%%*************************************************************************\n%% HSDbicgstab\n%%\n%% [xx,resnrm,flag] = HSDbicgstab(A,b,M1,tol,maxit)\n%%\n%% iterate on bb - (M1)*AA*x\n%%\n%% r = b-A*xtrue;\n%%\n%%*************************************************************************\n\nfunction [xx,resnrm,flag] = HSDbicgstab(A,b,M1,tol,maxit,printlevel)\n\nN = length(b);\nif (nargin < 6); printlevel = 1; end\nif (nargin < 5) || isempty(maxit); maxit = max(20,length(A.mat22)); end;\nif (nargin < 4) || isempty(tol); tol = 1e-8; end;\ntolb = min(1e-4,tol*norm(b));\nflag = 1;\n\nx = zeros(N,1);\nif isstruct(A); r = b-matvec(A,x); else r = b-mexMatvec(A,x); end;\nerr = norm(r); resnrm(1) = err; minresnrm = err; xx = x;\n%%if (err < tolb); return; end\n\nomega = 1.0;\nr_tld = r;\n%%\n%%\n%%\nsmtol = 1e-40;\nfor iter = 1:maxit,\n \n rho = (r_tld'*r);\n if (abs(rho) < smtol)\n flag = 2;\n if (printlevel); fprintf('*'); end;\n break;\n end\n if (iter > 1)\n beta = (rho/rho_1)* (alp/omega);\n p = r + beta*(p - omega*v);\n else\n p = r;\n end\n p_hat = precond(A,M1,p);\n if isstruct(A); v = matvec(A,p_hat); else v = mexMatvec(A,p_hat); end;\n alp = rho / (r_tld'*v);\n s = r - alp*v;\n %%\n s_hat = precond(A,M1,s);\n if isstruct(A); t = matvec(A,s_hat); else t = mexMatvec(A,s_hat); end;\n omega = (t'*s) / (t'*t);\n x = x + alp*p_hat + omega*s_hat;\n r = s - omega*t;\n rho_1 = rho;\n %%\n %% check convergence\n %%\n err = norm(r); resnrm(iter+1) = err; %#ok\n if (err < minresnrm);\n xx = x; minresnrm = err;\n end\n if (err < tolb)\n break;\n end\n if (err > 10*minresnrm)\n if (printlevel); fprintf('^'); end\n break;\n end\n if (abs(omega) < smtol)\n flag = 2;\n if (printlevel); fprintf('*'); end;\n break;\n end\nend\n%%\n%%*************************************************************************\n%%*************************************************************************\n%% matvec: matrix-vector multiply.\n%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]\n%%*************************************************************************\n\nfunction Ax = matvec(A,x)\n\nm = length(A.mat11); m2 = length(x)-m;\nif (m2 > 0)\n x1 = full(x(1:m));\nelse\n x1 = full(x);\nend\nAx = mexMatvec(A.mat11,x1);\nif (m2 > 0)\n x2 = full(x(m+1:m+m2));\n Ax = Ax + mexMatvec(A.mat12,x2);\n Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);\n Ax = [Ax; Ax2];\nend\n%%*************************************************************************\n%% precond:\n%%*************************************************************************\n\nfunction Mx = precond(A,L,x)\n\nm = L.matdim; m2 = length(x)-m;\nif (m2 > 0)\n x1 = full(x(1:m));\nelse\n x1 = full(x);\nend\nif (m2 > 0)\n x2 = x(m+1:m+m2);\n w = linsysolvefun(L,x1);\n z = mexMatvec(A.mat12,w,1) -x2;\n z = L.Mu \\ (L.Ml \\ (L.Mp*z));\n x1 = x1 - mexMatvec(A.mat12,z);\nend\n%%\nMx = linsysolvefun(L,x1);\n%%\nif (m2 > 0)\n Mx = [Mx; z];\nend\n%%*************************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDbicgstab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6402515877736743}} {"text": "%++++++++++++++++++++++++++++++++++++++++++++\n%PURPOSE: TO DETERMINE THE OPTIMUM VALUE OF \n%OVER-RELAXATION (OMEGA) FOR APPLICATION\n%IN SOR GS, PICKED OVER MINIMUM VALUE OF\n%SOR/GS ITERATION.\n%++++++++++++++++++++++++++++++++++++++++++++\nfunction [T]=optimum(om1,om2)\nN=200;\neps=1e-6;%error\nL=2;\ndx=L/N;\nn2=25; %n^2=hP/kA\ntb=400+273.15;\nta=34+273.15;\nkira=0;\n\nglobal omega eps N tb ta\nwarning off\n\n[gs,T]=GS;\n\nomega=om1;\nwhile omega4\n error('3 or 4 inputs required.')\nend\nT=length(y);\nif T<=(maxlags+1)\n error('Length of data must be larger than LAGS')\nend\nif size(y,1)~=T,\n y=y';\nend\nif size(y,2)~=1\n error('Y must be a column vector')\nend\nif ~isscalar(maxlags) && maxlags>0 && floor(maxlags)==maxlags\n error('LAGS must be a positive integer')\nend\nif ~isscalar(p)\n error('P must be a scalar integer in {0, 1, 2, 3}')\nend\nif ~ismember(p,[0 1 2 3])\n error('P must be a scalar integer in {0, 1, 2, 3}')\nend\nif nargin==3\n IC='AIC';\nelse\n if ~ischar(IC)\n error('IC must be a string, either ''AIC'' or ''BIC''');\n elseif ~ismember(IC,{'AIC','BIC'})\n error('IC must be a string, either ''AIC'' or ''BIC''');\n end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n% Setup common to all problems\n%y=y-y(1);\nydiff=diff(y);\n[ydiffcurr, ydifflags]=newlagmatrix(ydiff,maxlags); %#ok\nT=length(y);\nY=y(maxlags+2:T);\ntau=length(Y);\n%\nswitch p\n case 0\n % Case 1\n i=0;\n X=y(maxlags+1:T-1);\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n \n % Loop\n for i=1:maxlags\n X=[y(maxlags+1:T-1) ydifflags(:,1:i)];\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n end\n \n case {1,3}\n %Case 2\n i=0;\n X=[ones(size(Y)) y(maxlags+1:T-1)];\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n \n % Loop\n for i=1:maxlags\n X=[ones(size(Y)) y(maxlags+1:T-1) ydifflags(:,1:i)];\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n end\n \n \n case 2\n %Case 4\n i=0;\n X=[ones(size(Y)) y(maxlags+1:T-1) (1:tau)'];\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n \n % Loop\n for i=1:maxlags\n X=[ones(size(Y)) y(maxlags+1:T-1) (1:tau)' ydifflags(:,1:i)];\n rho = X\\Y;\n % Compute the errors\n e= Y-X*rho;\n s2(i+1)=e'*e/tau;\n K(i+1)=size(X,2);\n end\nend\n\n\nif strcmp(IC,'AIC')\n ICs=log(s2) + 2*K/tau;\nelse\n ICs=log(s2) + K*log(tau)/tau;\nend\n[~,lags]=min(ICs);\nlags=lags-1;\n[adfstat,pval,critval,resid]=augdf(y,p,lags);", "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/timeseries/augdfautolag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6402257252041874}} {"text": "function [logCr,logr]=gencorint(x,dim,tau,logr,p,w,svd,q)\n%Syntax: [logCr,logr]=gencorint(x,dim,tau,logr,p,w,svd,q)\n%________________________________________________________\n%\n% Calculates the generalized Correlation Integral (Cr) of a time\n% series x.\n%\n% logCr is the the value of log(Cr).\n% logr is log(range).\n% x is the time series.\n% dim is the embedding dimension.\n% tau is the time delay.\n% p is defines the norm.\n% w is the Theiler's correction.\n% svd is the number of singular values taken into account.\n% q is the generalization index.\n%\n%\n% References:\n%\n% Grassberger P, Procaccia I (1983): Characterization of strange\n% attractors. Physical Review Letters 50(5):346-349\n%\n% Theiler J (1986): Spurious dimension from correlation algorithms\n% applied tolimited time-series data. Physical Review A 34(3):2427-\n% 2432\n%\n% Albano A M, Muench J, Schwartz C, Mees A I, Rapp P E, (1988):\n% Singular-value decomposition and the Grassberger-Procaccia algorithm.\n% Physical Review A38:3017-3026\n% \n%\n% Alexandros Leontitsis\n% Department of Education\n% University of Ioannina\n% 45110 - Dourouti\n% Ioannina\n% Greece\n%\n% University e-mail: me00743@cc.uoi.gr\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n%\n% June 15, 2001.\n\nif nargin<1 | isempty(x)==1\n error('You should provide a time series.');\nelse\n % x must be a vector\n if min(size(x))>1\n error('Invalid time series.');\n end\n x=x(:);\n % n is the time series length\n n=length(x);\nend\n\nif nargin<2 | isempty(dim)==1\n dim=2;\nelse\n % dim must be either a scalar or a vector\n if min(size(dim))>1\n error('dim must be a scalar or a vector.');\n end\n % dim must be an integer\n dim=round(dim);\n % dim values must be above 0\n dim=dim(find(dim>0));\nend\n\nif nargin<3 | isempty(tau)==1\n tau=1;\nelse\n % tau must be either a scalar or a vector\n if min(size(tau))>1\n error('tau must be a scalar or a vector.');\n end\n % tau must be an integer\n tau=round(tau);\n % tau values must be above 0\n tau=tau(find(tau>0));\nend\n\nif nargin<4 | isempty(logr)==1\n r=(max(x)-min(x))/10*(1:20)'/20;\n logr=log10(r);\nelse\n % logr must be either a scalar or a vector\n if min(size(dim))>1\n error('logr must be a scalar or a vector.');\n end\n % if it is a scalar, it determines the maximum range\n if length(logr)==1\n div=logr;\n % div must be positive\n if div<=0\n error('logr must be a positive scalar or vector');\n end\n r=(max(x)-min(x))/div*(1:20)'/20;\n logr=log10(r);\n else\n logr=logr(:);\n r=10.^logr;\n end\nend\n\nif nargin<5 | isempty(p)==1\n p=inf;\nelse\n % p must be either a scalar or a vector\n if min(size(dim))>1\n error('p must be a scalar.');\n end\n % p values must be positive\n p=p(find(p>0));\nend\n\nif nargin<6 | isempty(w)==1\n w=1;\nelse\n % w must be either a scalar or a vector\n if min(size(w))>1\n error('w must be either a scalar or a vector.');\n end\n % w must be an integer\n w=round(w);\n % w must be positive\n w=w(find(w>0));\nend\n\nif nargin<7 | isempty(svd)==1\n svd=[];\nelse\n % svd must be a scalar or a vector\n if min(size(svd))>1\n error('svd must be either a scalar or a vector.');\n end\n % svd must be an integer\n svd=round(svd);\n % svd must be positive\n svd=svd(find(svd>0));\nend\n\nif nargin<8 | isempty(q)==1\n q=2;\nelse\n % q must be either a scalar or a vector\n if min(size(q))>2\n error('q must be either a scalar or a vector.');\n end\nend\n\n% Only one of dim, tau, p, w, or q should be vector\nl=[length(dim),length(tau),length(p),length(w),length(svd),length(q)];\nif length(find(l>1))>1\n error('Only one of dim, tau, p, w, svd, or q should be vector.');\nend\n\nm=max(l);\ndim=ones(1,m).*dim;\ntau=ones(1,m).*tau;\np=ones(1,m).*p;\nw=ones(1,m).*w;\nif isempty(svd)==0\n svd=ones(1,m).*svd;\nend\nq=ones(1,m).*q;\n\nfor i=1:m\n \n % Reconstruct the time-delay phase-space\n [Y,T]=phasespace(x,dim(i),tau(i));\n if isempty(svd)==0\n svd(i)=min(svd(i),dim(i));\n % SVD on X\n [u,s,v]=svd(Y,0);\n \n % Calculate the Principal Components\n pc=Y*v;\n \n % Reconstruct the first svd Principal Components\n Y=pc(:,1:svd(i))*v(:,1:svd(i))';\n end\n \n % Initialize the logCr\n Cr=zeros(size(r));\n \n if q(i)==2 % ...fast\n \n for i1=1:T-w(i)\n for i2=i1+w(i):T\n dist=norm(Y(i1,:)-Y(i2,:),p(i));\n s=find(r>dist);\n Cr(s)=Cr(s)+1;\n end\n end\n Cr=2*Cr/T/(T-1);\n logCr(:,i)=log10(Cr);\n \n else % slow...\n \n for i1=1:T\n c1=zeros(size(r));\n for i2=1:T\n if i1i2+(w(i)-1)\n dist=norm(Y(i1,:)-Y(i2,:),p(i));\n s=find(r>dist);\n c1(s)=c1(s)+1;\n end\n end\n c1=c1/(T-1);\n if q(i)~=1\n Cr=Cr+c1.^(q(i)-1);\n else\n Cr=Cr+c1;\n end\n end\n if q(i)~=1\n Cr=Cr/T;\n logCr(:,i)=log10(Cr.^(1/(q(i)-1)));\n else\n Cr=log10(Cr)/T;\n logCr(:,i)=Cr;\n end\n \n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1597-chaotic-systems-toolbox/gencorint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6402257108292988}} {"text": "function determ = fourier_sine_determinant ( n )\n\n%*****************************************************************************80\n%\n%% FOURIER_SINE_DETERMINANT returns the determinant of the FOURIER_SINE matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM, the determinant.\n%\n if ( mod ( n, 2 ) == 1 )\n determ = + 1.0;\n else\n determ = - 1.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/fourier_sine_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.6402090810244282}} {"text": "function F = ...\n obj_actuator_param_pulse_FFT_method(x,frequency_20,frequency_100)\n% Computes objective function for determination of basic parameters of\n% the proportional valve actuator that match the requirted frequency\n% response. The required and actual frequency responses are compared by\n% the frequency at which phase shift in -90 deg takes place. The frequency \n% response of a nonlinear system is obtained by processing the pulse \n% transient characteristic with the FFT algorythm. \n% Copyright 2010 MathWorks, Inc.\n\n% frequency_20 - frequency (Hz) at phase shift in -pi/2 at 20% input signal\n% frequency_100 - frequency (Hz) at phase shift in -pi/2 at 100% input signal\n\nmodel = 'actuator_freq_testrig_pulse_FFT_method';\nload_system(model);\n\nassignin('base','act_gain', x(1));\nassignin('base','time_const', x(2));\nassignin('base','act_saturation', x(3));\n\nsim(model);\n\ny_20 = yout(:,2); % Pulse transient characteristic at 20% input\ny_100 = yout(:,1); % Pulse transient characteristic at 100% input\nfs = 1000; % Sampling frequency\nn = length(y_20); % Window length = Transform length\ny_20_fft = fft(y_20,n); % Discrete Fourier Transform\ny_100_fft = fft(y_100,n); % Discrete Fourier Transform\nf0 = (0:n/2-1)*(fs/n); % Shifted frequency range, positive range\ny_20_0 = fftshift(y_20_fft); % Shifted DFT at 20% input\ny_100_0 = fftshift(y_100_fft); % Shifted DFT at 100% input\n% Phase characteristic at 20% input for positive frequencies after unwrap\nphase_20 = unwrap(angle(y_20_0(257:end))); \n% Phase characteristic at 100% input for positive frequencies after unwrap\nphase_100 = unwrap(angle(y_100_0(257:end)));\n\n% Computing frequency at 90 deg phase shift by interpolation of phase\n% characteristics\nfrq_20 = interp1(phase_20,f0,-pi/2);\nfrq_100 = interp1(phase_100,f0,-pi/2);\n\n% Objective function as a sum of squared differences between the specified\n% and computed frequencies at phase shift angle in -pi/2\nF = (frequency_20 - frq_20)^2 + (frequency_100 - frq_100)^2; \n\nend\n\n% EOF", "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/27260-hydraulic-valve-parameters-from-data-sheets-and-experimental-data/Valve_Params_SH/Ex8_Prop_Servo_Freq_Resp_Direct/obj_actuator_param_pulse_FFT_method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6401538572312556}} {"text": "classdef poisson_naive_bayes_CL\n\n% poisson_naive_bayes_CL is a classifier (CL) object that implements a \n% Poisson Naive Bayes classifier. For each class, the expected number of occurances \n% (denoted lambda) is calculated separately for each feature/neuron, by taking the mean\n% values from the training data for each class. To evaluate whether a given test point \n% belongs to class i, the log of the likelihood function is calculated using the lambda values as\n% parameters of Poisson distributions for each feature/neuron (i.e., a separate Poisson distribution \n% is calculated for each neuron), and the probability of observing a given number of spikes for\n% a particular neuron is calculated using the lambda value for that \n% neuron. The overall likelihood value is calculated by multiplying the \n% probabilities for each neuron together (i.e., Naive Bayes classifiers assume that each\n% neuron is independent), or equivalently, adding the log of the probabilities for\n% each neuron together. The class with the highest likelihood value is chosen as the \n% predicted label, and the decision values are the log likelihood values.\n%\n%\n% Like all CL objects, there are two main methods, which are:\n%\n% 1. cl = train(cl, XTr, YTr) \n% This method takes the training data (XTr, YTr) and learns a mean vector\n% (i.e., the lambda values) for each class.\n% \n% 2. [predicted_labels decision_values] = test(cl, XTe)\n% This method takes the test data an[d calculates the log of the likelihood\n% function for each class (which are the decision values), and returns the class\n% with the highest likelihood as the predicted_label. \n%\n% Notes: \n%\n% 1. This classifier assumes that all feature values are integers.\n%\n% 2. If the estimate rate parameter (lambda) for any feature is 0 (i.e., if the mean of a feature in the training data is 0), \n% then this 0 lambda estimate will be replaced by the value 1/(num_training_points_in_class_k +1); i.e., we will assume\n% that there is one more training point in which an event occurred. This prevents errors if an event occurred on a test point\n% but the estimated lambda was 0.\n%\n%\n% XTr and XTe are in the form [num_features x num_examples]\n% YTr is in the form [num_examples x 1]\n%\n\n\n%==========================================================================\n\n% This code is part of the Neural Decoding Toolbox.\n% Copyright (C) 2011 by Ethan Meyers (emeyers@mit.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 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\n\n\n\n properties \n lambdas = []; % the expected number of occurances for each neuron for each class\n labels = []; % the unique labels for the different classes\n end\n\n\n\n methods \n\n % constructor \n function cl = poisson_naive_bayes_CL\n end\n \n \n function cl = train(cl, XTr, YTr) \n\n % added sanity check\n if size(YTr, 2) ~= size(XTr, 2) && size(YTr, 1) ~= size(XTr, 2) \n error('Number of columns in YTr, and XTr must be the same (i.e., there must be one and exactly one label for each data point)') \n end\n\n % sanity check to make sure the training data only contains integers\n% if sum(sum(abs(round(XTr) - XTr))) > 10.^-2 % (not having it be exactly zero to account for round off error)\n% error(['The training data must only contain integers to use this classifier. Make sure the data was loaded as integers (e.g., using the appropriate flag in ' ...\n% 'basic_DS/generalization_DS datasources, and that only appropriate feature preprocessors were used (e.g., do not use the zscore_normalize_FP)'])\n% end\n \n \n \n cl.labels = unique(YTr);\n\n for iLabel = 1:length(cl.labels )\n \n lambdas(:, iLabel) = mean(XTr(:, (YTr == cl.labels(iLabel))), 2);\n \n % If the rate parameter (lambda) is zero, there can be problems if the test data has a value greater than zero\n % (i.e., will get zero probability, which creates problems when taking the log).\n % We will deal with this problem by assuming that there is one more data point with a 1 (when all training data has zero occurances)\n zero_lambda_replacement_value = 1/(length(find(YTr == cl.labels(iLabel))) + 1); % if found zeros for all trials, assume that there is one more trial where a 1 was found...\n lambdas((lambdas(:, iLabel) == 0), iLabel) = zero_lambda_replacement_value;\n \n end\n\n cl.lambdas = lambdas;\n \n end\n \n \n \n \n function [predicted_labels decision_values] = test(cl, XTe)\n \n \n % sanity check to make sure the test data only contains integers\n% if sum(sum(abs(round(XTe) - XTe))) > 10.^-2 % (not having it be exactly zero to account for round off error)\n% error(['The test data must only contain integers to use this classifier. Make sure the data was loaded as integers (e.g., using the appropriate flag in ' ...\n% 'basic_DS/generalization_DS datasources, and that only appropriate feature preprocessors were used (e.g., do not use the zscore_normalize_FP)'])\n% end\n \n \n \n % compute simultaneously all p-values for all features and test points (easy b/c everything is independent)\n curr_lambdas = repmat(cl.lambdas, [1, 1, size(XTe, 2)]);\n XTe_repmat_for_all_classes = permute(repmat(XTe, [1, 1, size(cl.lambdas, 2)]), [1 3 2]);\n %p_vals = exp(-curr_lambdas + XTe_repmat_for_all_classes .* log(curr_lambdas) - gammaln(XTe_repmat_for_all_classes + 1));\n %log_likelihoods = squeeze(sum(log(p_vals)));\n \n log_likelihoods = squeeze(sum(-curr_lambdas + XTe_repmat_for_all_classes .* log(curr_lambdas) - gammaln(XTe_repmat_for_all_classes + 1), 1)); % possibly even faster...\n % % %log_likelihoods = squeeze(sum(-curr_lambdas + XTe_repmat_for_all_classes .* log(curr_lambdas))); % since the factorial term does not depend on the class, code might be faster\n % if this term is removed. The decision values returned\n % will no longer be exactly the log likelihood values but rather the log likelihood\n % values minus a constant. Using this will make AUROC values worse, so don't do it!!!!\n \n % prior to version 1.0.4 the following line was used. I added a the sum over the first dimention (i.e., sum(XXX, 1)) so that the code will run even when only a single site is used \n %log_likelihoods = squeeze(sum(-curr_lambdas + XTe_repmat_for_all_classes .* log(curr_lambdas) - gammaln(XTe_repmat_for_all_classes + 1))); % possibly even faster...\n \n \n [vals inds] = randmax(log_likelihoods);\n predicted_labels = cl.labels(inds);\n decision_values = log_likelihoods';\n \n\n end\n \n \n end % end public methods\n \n \n\n \n\nend % end classdef\n\n\n\n\n\n\n\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/ndt_1_0_4/classifiers/@poisson_naive_bayes_CL/poisson_naive_bayes_CL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6401538538093081}} {"text": "function [Z, Z_L, Z_U, T, P, rho, c, g, mu, nu, k, n, n_sum] = atmo(alt,division,units)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Program: 1976 Standard Atmosphere Calculator[0-1000 km]\n% Author: Brent Lewis(RocketLion@gmail.com)\n% University of Colorado-Boulder\n% History: Original-1/10/2007\n% Revision-1/12/2007-Corrected for changes in Matlab versions\n% for backward compatability-Many thanks to Rich\n% Rieber(rrieber@gmail.com)\n% Input: alt: Final Geometric Altitude[km]\n% division: Reporting points for output arrays[km]\n% (.01 km & Divisible by .01 km)\n% units: 1-[Metric]\n% 2-{English}\n% Default: Values used if no input\n% alt: 1000 km\n% division: 1 km\n% units: Metric\n% Output: Each value has a specific region that it is valid in with this model\n% and is only printed out in that region\n% Z: Total Reporting Altitudes[0<=alt<=1000 km][km]{ft}\n% Z_L: Lower Atmosphere Reporting Altitudes[0<=alt<=86 km][km]{ft}\n% Z_U: Upper Atmosphere Reporting Altitudes[86<=alt<=1000 km][km]{ft}\n% T: Temperature array[0<=alt<=1000 km][K]{R}\n% P: Pressure array[0<=alt<=1000 km][Pa]{in_Hg}\n% rho: Density array[0<=alt<=1000 km][kg/m^3]{lb/ft^3}\n% c: Speed of sound array[0<=alt<=86 km][m/s]{ft/s}\n% g: Gravity array[0<=alt<=1000 km][m/s^2]{ft/s^2}\n% mu: Dynamic Viscosity array[0<=alt<=86 km][N*s/m^2]{lb/(ft*s)}\n% nu: Kinematic Viscosity array[0<=alt<=86 km][m^2/s]{ft^2/s}\n% k: Coefficient of Thermal Conductivity\n% array[0<=alt<=86 km][W/(m*K)]{BTU/(ft*s*R)}\n% n: Number Density of individual gases\n% (N2 O O2 Ar He H)[86km<=alt<=1000km][1/m^3]{1/ft^3}\n% n_sum: Number Density of total gases\n% [86km<=alt<=1000km][1/m^3]{1/ft^3}\n% Acknowledgements: 1976 U.S. Standard Atmosphere\n% Prof. Adam Norris-Numerical Analysis Class\n% Steven S. Pietrobon USSA1976 Program\n% Notes: Program uses a 5-point Simpson's Rule in 10\n% meter increments. Results DO vary by less 1%\n% compared to tabulated values and is probably\n% caused by different integration techniques\n% Examples: atmo() will compute the full atmosphere in 1 km\n% increments and output in Metric Units\n% atmo(10) will compute the atmosphere between 0\n% and 10 km in 1 km increments and output in\n% Metric Units\n% atmo(20,.1,2) will compute the atmosphere\n% between 0 and 20 km in 100 m increments and\n% output in English Units\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin == 0\n alt = 1000;\n division = 1;\n units = 1;\nelseif nargin == 1\n division = 1;\n units = 1;\nelseif nargin == 2\n units = 1;\nend\n\n% Error Reporting\nif nargin > 3\n error('Too many inputs')\nelseif mod(division,.01) ~= 0\n error('Divisions must be multiples of .01 km')\nelseif units ~= 1 && units ~= 2\n error('Units Choice Invalid[1-Metric,2-English]')\nelseif alt<0 || alt>1000\n error('Program only valid for 0 80 && Z_L(i) < 86\n T_L(i,1) = T_L(i)*interp1(Z_M,M_M_0,Z_L(i));\n end\nend\nfor i = 1 : length(Z_U)\n T_U(i,1) = atmo_temp(Z_U(i));\nend\n\n% Number Density\nif alt > 86\n n = atmo_compo(alt,division);\n n_sum = sum(n,2);\nelse\n n = [];\n n_sum = [];\nend\n\n% Pressure\nP_L = atmo_p(Z_L);\nP_U = atmo_p(Z_U,T_U,n_sum);\n\n% Density\nrho_L = M_0*P_L./(R*T_M_L);\nif ~isempty(P_U)\n rho_U = n*M_i/N_A;\nelse\n rho_U = [];\nend\n\n% Speed of Sound\nc = sqrt(gamma*R*T_M_L/M_0);\n% Dynamic Viscosity\nmu = beta*T_L.^1.5./(T_L+S);\n% Kinematic Viscosity\nnu = mu./rho_L;\n% Thermal Conductivity Coefficient\nk = 2.64638e-3*T_L.^1.5./(T_L+245*10.^(-12./T_L));\n\n% Combine Models\nT = [T_L(1:end-1*double(~isempty(T_U)));T_U];\nP = [P_L(1:end-1*double(~isempty(T_U)));P_U];\nrho = [rho_L(1:end-1*double(~isempty(T_U)));rho_U];\nZ = [Z_L(1:end-1*double(~isempty(T_U)));Z_U];\n\n% Gravity\ng = g_0*(r_E./(r_E+Z)).^2;\n\nif units == 2\n unit_c = [3.048e-1 3.048e-1 3.048e-1 5/9 0.0001450377 1.6018463e1...\n 3.048e-1 3.048e-1 1.488163944 9.290304e-2 6.226477504e-3...\n 3.531466672e2 3.531466672e2];\n Z = Z/unit_c(1);\n Z_L = Z_L/unit_c(2);\n Z_U = Z_U/unit_c(3);\n T = T/unit_c(4);\n P = P/unit_c(5);\n rho = rho/unit_c(6);\n c = c/unit_c(7); \n g = g/unit_c(8);\n mu = mu/unit_c(9);\n nu = nu/unit_c(10); \n k = n/unit_c(11);\n n_sum = n_sum/unit_c(12);\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/13635-complete-1976-standard-atmosphere/atmo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6401538503873607}} {"text": "function [ss_estimates,ss_estimates_constant,ss_estimates_exogenous,ss_estimates_contribution_exo]=ssestimates(ss_record,n,T,cband)\n\n\n\n% function [ss_estimates]=ssestimates(ss_record,n,T,cband)\n% calculates the point estimate (median), lower bound and upper bound of the steady-state from the posterior distribution\n% inputs: - cell 'ss_record': record of the gibbs sampler draws for the steady-state\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'T': number of sample time periods (defined p 7 of technical guide)\n% - scalar 'cband': confidence level for VAR coefficients\n% outputs: - cell 'ss_estimates': lower bound, point estimates, and upper bound for the steady-state \n\n\n\n% create first the cell that will contain the estimates\nss_estimates=cell(n,1);\nss_estimates_constant=cell(n,1);\nss_estimates_exogenous=cell(n,1);\nss_estimates_contribution_exo=cell(1,1);\n% for each variable and each sample period, compute the median, lower and upper bound from the Gibbs sampler records\n% consider variables in turn\nfor ii=1:n\n % consider sample periods in turn\n for jj=1:T\n % compute first the lower bound\n ss_estimates{ii,1}(1,jj)=quantile(ss_record{ii,1}(:,jj),(1-cband)/2);\n % then compute the median\n ss_estimates{ii,1}(2,jj)=quantile(ss_record{ii,1}(:,jj),0.5); \n % finally compute the upper bound\n ss_estimates{ii,1}(3,jj)=quantile(ss_record{ii,1}(:,jj),(1-(1-cband)/2));\n% % % if m>1\n% % % % same for only the constant\n% % % ss_estimates_constant{ii,1}(1,jj)=quantile(ss_record_constant{ii,1}(:,jj),(1-cband)/2);\n% % % % then compute the median\n% % % ss_estimates_constant{ii,1}(2,jj)=quantile(ss_record_constant{ii,1}(:,jj),0.5); \n% % % % finally compute the upper bound\n% % % ss_estimates_constant{ii,1}(3,jj)=quantile(ss_record_constant{ii,1}(:,jj),(1-(1-cband)/2));\n% % % % same for only the exogenous\n% % % ss_estimates_exogenous{ii,1}(1,jj)=quantile(ss_record_exogenous{ii,1}(:,jj),(1-cband)/2);\n% % % % then compute the median\n% % % ss_estimates_exogenous{ii,1}(2,jj)=quantile(ss_record_exogenous{ii,1}(:,jj),0.5); \n% % % % finally compute the upper bound\n% % % ss_estimates_exogenous{ii,1}(3,jj)=quantile(ss_record_exogenous{ii,1}(:,jj),(1-(1-cband)/2));\n% % % % compute contribution from only the exogenous part\n% % % ss_estimates_contribution_exo{ii,1}(1,jj)=(quantile(ss_record_constant{ii,1}(:,jj),0.5)-quantile(ss_record{ii,1}(:,jj),0.5));\n% % % else\n% % % ss_estimates_constant=[];\n% % % ss_estimates_exogenous=[];\n% % % end\n end\nend\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/ssestimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6401435703051648}} {"text": "function [gen, ave1, ave2] = fusion_strategy(features_a, features_b, source_a, source_b, unit)\n\n[m,n] = size(features_a);\n[m1,n1] = size(source_a);\nave_temp1 = zeros(m1,n1);\nave_temp2 = zeros(m1,n1);\nweight_ave_temp1 = zeros(m1,n1);\nweight_ave_temp2 = zeros(m1,n1);\n\nfor i=2:m-1\n for j=2:n-1\n A1 =sum(sum(features_a(i-1:i+1,j-1:j+1)))/9;\n A2 =sum(sum(features_b(i-1:i+1,j-1:j+1)))/9;\n \n % weight average\n weight_ave_temp1(((i-2)*unit+1):((i-1)*unit),((j-2)*unit+1):((j-1)*unit)) = A1/(A1+A2);\n weight_ave_temp2(((i-2)*unit+1):((i-1)*unit),((j-2)*unit+1):((j-1)*unit)) = A2/(A1+A2);\n ave_temp1(((i-2)*unit+1):((i-1)*unit),((j-2)*unit+1):((j-1)*unit)) = A1;\n ave_temp2(((i-2)*unit+1):((i-1)*unit),((j-2)*unit+1):((j-1)*unit)) = A2;\n% % choose max\n% if A1>A2\n% gen_temp(((i-2)*unit+1):((i-1)*unit),((j-2)*unit+1):((j-1)*unit)) = ones(unit,unit);\n% temp_mask(i,j) = 1;\n% end\n end\nend\n% figure;imshow(temp_mask);\nweight_ave_temp1 = weight_ave_temp1(1:m1,1:n1);\nweight_ave_temp2 = weight_ave_temp2(1:m1,1:n1);\n% figure;imshow(weight_ave_temp1);\n% figure;imshow(weight_ave_temp2);\n\ngen = source_a.*weight_ave_temp1 + source_b.*weight_ave_temp2;\n% figure;imshow(gen);\n\nave1 = ave_temp1;\nave2 = ave_temp2;\nend", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/VggML_Image_Fusion_Codes/fusion_strategy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6400328841613349}} {"text": "function [xi] = logSE3(chi)\nC = chi(1:3,1:3);\nr = chi(1:3,4);\n[vecs,eigs] = eig(C);\n[~,idx] = min(abs(diag(eigs)-1));\na = vecs(:,idx);\n\nphi = acos(1/2*(trace(C)-1));\nif phi == 0\n a = zeros(3,1);\n iJ = eye(3);\nelse\n C1 = cos(phi)*eye(3) + (1-cos(phi))*a*transpose(a) + sin(phi)*[[0,-a(3),a(2)];[a(3),0,-a(1)];[-a(2),a(1),0]];\n C2 = cos(-phi)*eye(3) + (1-cos(-phi))*a*transpose(a) + sin(-phi)*[[0,-a(3),a(2)];[a(3),0,-a(1)];[-a(2),a(1),0]];\n if norm(C2-C).\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/Graphics/idp3elli.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6400142252690894}} {"text": "function [x,info] = amgMaxwellinterface(A,b,node,edge,option)\n%% AMGMAXWELL algebraic multigrid solver for Maxwell equations.\n% \n% x = amgMaxwell(A,b,node,edge) attempts to solve the system of\n% linear equations Ax = b using multigrid type solver. The linear system is\n% obtained by either the first or second family of linear edge element\n% discretization of the Maxwell equation; See doc Maxwell.\n%\n% amgMaxwell is more algebraic than mgMaxwell but still requires geometric\n% information node and edge. Grapha Laplacian of vertices are used as\n% auxiliary Poisson operator and amg is used as Poisson solver.\n%\n% Input \n% - A: curl(alpha curl) + beta I\n% - b: right hand side\n% - node,edge: mesh information\n% - options: extra structures\n%\n% By default, the HX preconditioned PCG is used which works well for\n% symmetric positive definite matrices (e.g. arising from eddy current\n% simulation). For symmetric indefinite matrices (e.g. arising from time\n% harmonic Maxwell equation), set option.solver = 'minres' or 'bicg' or\n% 'gmres' to try other Krylov method with HX preconditioner.\n%\n% See also mg, mgMaxwell, mgMaxwellsaddle\n%\n% Reference: \n% R. Hiptmair and J. Xu, Nodal Auxiliary Space Preconditioning in\n% H(curl) and H(div) Spaces. SIAM J. Numer. Anal., 45(6):2483-2509, 2007.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nt = cputime;\n%% Initial check\nNdof = length(b); % number of dof\nN = size(node,1); % number of nodes\nNE = size(edge,1); % number of edge;\ndim = size(node,2); \n% Assign default values to unspecified parameters\nif ~exist('option','var')\n option = []; \nend \noption = mgoptions(option,length(b)); % parameters\nx0 = option.x0; \n% N0 = option.N0; \ntol = option.tol; \n%tol = 5*10^(-7);\n% mu = option.smoothingstep; preconditioner = option.preconditioner; coarsegridsolver = option.coarsegridsolver; \nprintlevel = option.printlevel; %setupflag = option.setupflag;\nmaxIt = 2000; %400; % increase the default step (200) for Maxwell equations\n% tol = 1e-7; % reset the tol\n% Check for zero right hand side\nif (norm(b) == 0) % if rhs vector is all zeros\n x = zeros(Ndof,1); % then solution is all zeros\n flag = 0; \n itStep = 0; \n err = 0; \n time = cputime - t;\n info = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',max(err(end,:))); \n return\nend\n\n%% Transfer operators from nodal element to edge element\nif isfield(option,'isBdEdge')\n isBdEdge = option.isBdEdge;\nelse\n deg = sum(spones(A(1:NE,1:NE)),2);\n isBdEdge = (deg == 1);\nend\nif Ndof == NE % lowest order edge element\n II = node2edgematrix(node,edge,isBdEdge);\nelseif Ndof >= 2*NE % first or second order edge element\n II = node2edgematrix1(node,edge,isBdEdge);\nend\nIIt = II';\n[grad,isBdNode] = gradmatrix(edge,isBdEdge);\ngradt = grad';\n\n%% Block smoother\n%if option.blklevel == 0 || ~isfield(option,'blklevel')\n \ninterfaceEdgeID = option.blkId+1:NE;\ninterfaceEdge = false(NE, 1);\ninterfaceEdge(option.blkId+1:NE) = true;\nregularEdge = false(NE, 1);\nregularEdge(1:option.blkId) = true;\n\nif isfield(option,'blklevel')\n \n ExtLevel = 0;\n while (ExtLevel0);\n regularEdge = ~interfaceEdge;\n interfaceEdgeID = find(interfaceEdge==1);\n ExtLevel = ExtLevel+1;\n \n end\n \nend\n\n\nAinterface = A(interfaceEdge,interfaceEdge);\nAregular = A(regularEdge,regularEdge);\nB = A(interfaceEdge, regularEdge);\nD = diag(Aregular);\n\ntic\nif isfield(option,'fact') == 1\n switch option.fact\n case 'lu'\n [L,U,P,Q] = lu(Ainterface);\n case 'chol'\n [R,flag,P] = chol(Ainterface);\n end\nelse\n [L,U,P,Q] = lu(Ainterface);\nend\ntoc\n\n%% Auxiliary Poisson matrix\n% - A: curl(alpha curl) + beta I\n% - AP: - div(alpha grad) + beta I\n% - BP: - div(beta grad)\n\nif isfield(option,'AP')\n AP = option.AP;\n edgeVec = node(edge(:,2),:) - node(edge(:,1),:);\n% edgeLength = sqrt(sum(edgeVec.^2,2));\n% if isfield(option,'beta') % resacle by the dielectric coefficients\n% if isreal(option.beta) && (length(option.beta) == NE)\n% beta = option.beta; \n% else % option.beta is a function \n% edgeMiddle = (node(edge(:,2),:) + node(edge(:,1),:))/2; \n% beta = option.beta(edgeMiddle); \n% end\n% end\n% M = accumarray(edge(:),repmat((edgeLength.^3).*beta,2,1),[N 1]);\n% AP = AP + spdiags(M,0,N,N);\nelse\n % build graph Laplacian to approximate AP\n edgeVec = node(edge(:,2),:) - node(edge(:,1),:);\n edgeLength = sqrt(sum(edgeVec.^2,2));\n if isfield(option,'alpha') % resacle by the magnetic coefficients\n if isreal(option.alpha) && (length(option.alpha) == NE)\n alpha = option.alpha; \n else % option.alpha is a function \n edgeMiddle = (node(edge(:,2),:) + node(edge(:,1),:))/2; \n alpha = option.alpha(edgeMiddle); \n end\n end\n % edge weight: h*alpha\n % AP = gradt*spdiags(edgeLength.*alpha,0,NE,NE)*grad;\n i1 = (1:NE)'; j1 = double(edge(:,1)); s1 = sqrt(edgeLength.*alpha);\n i2 = (1:NE)'; j2 = double(edge(:,2)); s2 = -s1;\n isFreeEdge = ~isBdEdge;\n G = sparse([i1(isFreeEdge);i2(isFreeEdge)],...\n [j1(isFreeEdge);j2(isFreeEdge)],...\n [s1(isFreeEdge);s2(isFreeEdge)],NE,N);\n %i1 = (1:NE)'; j1 = double(edge(:,1)); s1 = ones(size(alpha)).*sqrt(alpha);\n% i2 = (1:NE)'; j2 = double(edge(:,2)); s2 = -s1;\n% isFreeEdge = ~isBdEdge;\n% G = sparse([i1(:);i2(:)],...\n% [j1(:);j2(:)],...\n% [s1(:);s2(:)],NE,N);\n AP = G'*G;\n %E = G'*A*G;\n % lumped mass matrix: h^3*beta\n if isfield(option,'beta') % resacle by the dielectric coefficients\n if isreal(option.beta) && (length(option.beta) == NE)\n beta = option.beta; \n else % option.beta is a function \n edgeMiddle = (node(edge(:,2),:) + node(edge(:,1),:))/2; \n beta = option.beta(edgeMiddle); \n end\n end\n M = accumarray(edge(:),repmat((edgeLength.^3).*beta,2,1),[N 1]);\n AP = AP + spdiags(M,0,N,N);\nend\n% BP is Galerkin projection to the free node space\n% boundary nodes\nbdidx = zeros(N,1); \nbdidx(isBdNode) = 1;\nTbd = spdiags(bdidx,0,N,N);\nBP = gradt*A(1:NE,1:NE)*grad + Tbd;\n%BP = gradt*spdiags(edgeLength.*beta,0,NE,NE)*grad + Tbd;\n% if strcmp(option.outsolver,'minres')\n% BP = gradt*option.BPP(1:NE,1:NE)*grad + Tbd;\n% end\n\nsetupOption.solver = 'NO';\n[x,info,APi,Ri,RRi,ResAP,ProAP,clA] = amg(AP,ones(N,1),setupOption); %#ok\n[x,info,BPi,Si,SSi,ResBP,ProBP,clB] = amg(BP,ones(N,1),setupOption); %#ok\n\n%% Krylov iterative methods with HX preconditioner\nk = 1;\nerr = 1;\nswitch upper(option.outsolver)\n case 'CG'\n if printlevel>=1\n fprintf('Conjugate Gradient Method using HX preconditioner \\n');\n end\n x = x0;\n r = b - A*x;\n nb = norm(b);\n err = zeros(maxIt,2);\n err(1,:) = norm(r)/nb; \n while (max(err(k,:)) > tol) && (k <= maxIt)\n % compute Br by HX preconditioner\n Br = HXpreconditioner(r); \n % update tau, beta, and p\n rho = r'*Br; % r'*Br = e'*ABA*e approximates e'*A*e\n if k==1\n p = Br;\n else\n beta = rho/rho_old;\n p = Br + beta*p;\n end\n % update alpha, x, and r\n Ap = A*p;\n alpha = rho/(Ap'*p);\n r = r - alpha*Ap;\n x = x + alpha*p;\n rho_old = rho;\n % compute err for the stopping criterion\n k = k + 1;\n err(k,1) = sqrt(abs(rho/(x'*b))); % approximate relative error in energy norm\n err(k,2) = norm(r)/nb; % relative error of the residual in L2-norm\n if printlevel >= 2\n fprintf('#dof: %8.0u, HXCG iter: %2.0u, err = %12.8g\\n',...\n Ndof, k, max(err(k,:)));\n end\n end\n err = err(1:k,:);\n itStep = k-1;\n if k > maxIt || (max(err(end,:))>tol)\n flag = 1;\n else\n flag = 0;\n end\n case 'MINRES'\n fprintf('Minimum Residual Method with HX preconditioner \\n')\n [x,flag,err,itStep] = minres(A,b,tol,maxIt,@HXpreconditioner,[],x0); \n% x = minres(A,b,tol,maxIt,@HXpreconditioner,[],x0); \n case 'GMRES'\n fprintf('General Minimum Residual Method with HX preconditioner \\n')\n tic\n [x,flag,err,itStep] = gmres(A,b,10,tol,maxIt,@HXpreconditioner,[],x0);\n toc\n itStep = (itStep(1) -1)*10 + itStep(2);\nend\n\n%% Output\ntime = cputime - t;\nif printlevel >= 1\n fprintf('#dof: %8.0u, #nnz: %8.0u, iter: %2.0u, err = %8.4e, time = %4.2g s\\n',...\n Ndof, nnz(A), itStep, max(err(end,:)), time)\nend\nif (flag == 1) && (printlevel>0)\n fprintf('NOTE: the iterative method does not converge'); \nend\ninfo = struct('solverTime',time,'itStep',itStep,'error',err,'flag',flag,'stopErr',max(err(end,:))); \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions HXpreconditioner\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function Br = HXpreconditioner(r)\n %% 1. Smoothing in the finest grid of the original system\n if strcmp(option.smoother,'BD')\n if isfield(option,'fact') == 1\n switch option.fact\n case 'lu'\n eh = zeros(NE, 1);\n eh(regularEdge,:) = 0.75*r(regularEdge,:)./D;\n % eh(interfaceEdge,:) = Ainterface\\r(interfaceEdge,:);\n rtmp = P*r(interfaceEdge,:);\n rtmp = L\\rtmp;\n rtmp = U\\rtmp;\n rtmp = Q*rtmp;\n eh(interfaceEdge,:) = rtmp;\n case 'chol'\n eh = zeros(NE, 1);\n eh(regularEdge,:) = 0.75*r(regularEdge,:)./D;\n % eh(interfaceEdge,:) = Ainterface\\r(interfaceEdge,:);\n rtmp = P'*r(interfaceEdge,:);\n rtmp = R'\\rtmp;\n rtmp = R\\rtmp;\n rtmp = P*rtmp;\n eh(interfaceEdge,:) = rtmp;\n end\n else\n eh = zeros(NE, 1);\n eh(regularEdge,:) = 0.75*r(regularEdge,:)./D;\n % eh(interfaceEdge,:) = Ainterface\\r(interfaceEdge,:);\n rtmp = P*r(interfaceEdge,:);\n rtmp = L\\rtmp;\n rtmp = U\\rtmp;\n rtmp = Q*rtmp;\n eh(interfaceEdge,:) = rtmp;\n end\n elseif strcmp(option.smoother,'GS')\n % eh = triu(A)\\(D.*(tril(A)\\r)); # does not work if interface edge is\n % not treated differently\n rN = r(regularEdge); rI = r(interfaceEdge);\n rN = rN./D; rI = Ainterface\\rI;\n ehN = rN + B'*(Ainterface\\(B*rN))./D - B'*rI./D;\n ehI = -Ainterface\\(B*rN) + rI;\n eh = [ehN; ehI];\n else\n eh = 0.75*r./D; % Jacobi method. less computational time\n end\n %% 2. amg solver for auxiliary operators\n amgoption.solvermaxit = 3; % 3 for SPD matrix\n amgoption.printlevel = 0;\n rc = reshape(IIt*r(1:size(IIt,2)),N,dim); % transfer to the nodal linear element space\n %eaux = II*reshape(AP\\rc,dim*N,1);\n %eaux = II*reshape(amg(AP,rc,amgoption),dim*N,1);\n rAP = amgInterface(AP,rc,APi,Ri,RRi,ResAP,ProAP,clA,amgoption);\n eaux = II*reshape(rAP,dim*N,1);\n eh = eh + eaux;\n rb = gradt*r(1:NE);\n %eauxb = grad*(BP\\rb);\n %eauxb = grad*(amg(BP,rb,amgoption));\n rBP = amgInterface(BP,rb,BPi,Si,SSi,ResBP,ProBP,clB,amgoption);\n eauxb = grad*rBP;\n Br = eh + eauxb;\n end\n\n function z = amgInterface(M,r0,Ai,Bi,BBi,Res,Pro,cl,amgoption)\n \n maxItz = amgoption.solvermaxit;\n Nb = size(r0,2);\n z = repmat(zeros(size(r0,1),1),1,Nb);\n kz = 1;\n rz = r0 - M*z;\n nbz = max(sqrt(sum(r0.^2,1)));\n errz = zeros(maxItz,2);\n errz(1,:) = max(sqrt(sum(rz.^2,1)))/nbz;\n\n amgprintlevel = amgoption.printlevel; \n level = max(min(ceil(log2(N)/2-4),8),2);\n prefunc = @wcycle;\n if amgprintlevel >= 1\n fprintf('Conjugate Gradient Method\\n')\n end\n if isfield(amgoption,'smoothingstep') % smoothing steps\n mu = amgoption.smoothingstep;\n else\n mu = 2;\n end\n \n \n while (max(errz(kz,:)) > tol) && (kz <= maxItz) \n % compute Br by MG\n Brz = prefunc(r0);\n % update tau, beta, and p\n rhoz = dot(Brz,r0); % e'*ABA*e approximates e'*A*e\n if kz == 1\n pz = Brz;\n else\n betaz = rhoz./rho_oldz;\n pz = Brz + betaz.*pz;\n end\n % update alpha, x, and r\n Apz = M*pz;\n alpha = rhoz./dot(Apz,pz);\n r0 = r0 - alpha.*Apz;\n z = z + alpha.*pz;\n rho_oldz = rhoz;\n kz = kz + 1;\n % compute err for the stopping criterion\n % err(k,1) = alpha*sqrt(p'*Ap/(x'*A*x)); % increamental error in energy norm\n errz(kz,1) = max(sqrt(abs(rhoz./dot(z,r0)))); % approximate relative error in energy norm\n errz(kz,2) = max(sqrt(sum(r0.^2,1)))/nbz; % relative error of the residual in L2-norm\n if amgprintlevel >= 2\n fprintf('#dof: %8.0u, MGCG iter: %2.0u, err = %8.4e\\n',...\n N, kz-1, max(errz(kz,:)));\n end\n end\n errz = errz(1:kz,:);\n itStepz = kz-1;\n \n function e = wcycle(r,J) % solve equations Ae = r in each level\n if nargin<=1\n J = level;\n end\n if J == cl\n e = Ai{cl}\\r; % exact solver in the coaresest grid\n return\n end\n % fine grid pre-smoothing\n e = Bi{J}\\r; % pre-smoothing\n for s = 1:mu % extra mu steps smoothing\n e = e + Bi{J}\\(r-Ai{J}*e);\n end\n rc = Res{J}*(r - Ai{J}*e);\n % coarse grid correction twice\n ec = wcycle(rc,J-1);\n ec = ec + wcycle(rc - Ai{J-1}*ec,J-1);\n % fine grid post-smoothing\n e = e + Pro{J-1}*ec;\n e = e + BBi{J}\\(r-Ai{J}*e);\n for s = 1:mu\n e = e + BBi{J}\\(r-Ai{J}*e); % post-smoothing\n end\n end\n \n end\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/amgMaxwellinterface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6399972673421538}} {"text": "function [meanAmp,meanPh,seZ,meanStd] = vectorMean(view,scanNum,ROIcoords)\n%\n% [meanAmp,meanPh,seZ,meanStd] = vectorMean(view,scanNum,ROIcoords)\n%\n% Calculates mean amplitude and phase for pixels that are in\n% ROIcoords. \n% The standard error (std(z)/sqrt(length(z))) can also\n% returned. This is the average distance of the complex values\n% z = amp*exp(-i(ph)) from the mean of z.\n%\n% Can >also< return the mean noise std in the ROI:\n% Computed from the coherence and the amplitude.\n% \n% scanNum: scan number (integer)\n% ROIcoords: 3xN array of (y,x,z) coords (e.g., corresponding to\n% the selected ROI).\n%\n% djh 4/23/98\n% bw 2/17/99 Added seZ computation.\n%\n% Get co and ph (vectors) for the desired scan, within the\n% current ROI.\n%\nsubAmp = getCurDataROI(view,'amp',scanNum,ROIcoords);\nsubPh = getCurDataROI(view,'ph',scanNum,ROIcoords);\nsubCo = getCurDataROI(view,'co',scanNum,ROIcoords);\n\n% Remove NaNs from subCo and subAmp that may be there if ROI\n% includes volume voxels where there is no data.\nNaNs = find(isnan(subPh));\nif ~isempty(NaNs)\n disp('ROI includes voxels that have no data. These voxels are being ignored.');\n notNaNs = find(~isnan(subPh));\n subPh = subPh(notNaNs);\n subAmp = subAmp(notNaNs);\n subCo= subCo(notNaNs);\n \nend\n\n% Compute the mean co right here...\nmeanCo=mean(subCo);\n\n% convert to complex numbers\nz = subAmp .* exp(sqrt(-1)*subPh);\nif isempty(z)\n disp('Warning: no activity seen for current ROI');\n seZ = 0;\n meanAmp = 0;\n meanPh = 0;\nelse\n\tmeanZ = mean(z);\n \n if nargout > 2\n seZ = std(z)/sqrt(length(z));\n end\n meanAmp = abs(meanZ);\n\tmeanPh = angle(meanZ);\nend\n% Compute the meanStd right here...\nmeanStd=meanAmp.*sqrt((1/mean(subCo).^2)-1);\n\n\nreturn;\n\n% Debug\n\ncoords = INPLANE{1}.ROIs(INPLANE{1}.selectedROI).coords;\nscan = 1;\n[meanAmp,meanPh] = vectorMean(INPLANE{1},scan,coords)\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/BlockAnalysis/vectorMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6399972558167406}} {"text": "function lik = lik_lgp(varargin)\n%LIK_LGP Create a logistic Gaussian process likelihood structure \n%\n% Description\n% LIK = LIK_LGP creates a logistic Gaussian process likelihood structure\n%\n% The likelihood is defined as follows:\n% __ n\n% p(y|f) = || i=1 exp(f_i) / Sum_{j=1}^n exp(f_j),\n%\n% where f contains latent values.\n%\n% Reference\n%\n% Jaakko Riihimäki and Aki Vehtari (2014). Laplace approximation\n% for logistic Gaussian process density estimation and\n% regression. Bayesian analysis, in press.\n%\n% See also\n% LGPDENS, GP_SET, LIK_*\n%\n% Copyright (c) 2011 Jaakko Riihimäki and Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_LGP';\n ip.addOptional('lik', [], @isstruct);\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'LGP';\n lik.nondiagW = true;\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'LGP')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n\n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_lgp_pak;\n lik.fh.unpak = @lik_lgp_unpak;\n lik.fh.ll = @lik_lgp_ll;\n lik.fh.llg = @lik_lgp_llg; \n lik.fh.llg2 = @lik_lgp_llg2;\n lik.fh.llg3 = @lik_lgp_llg3;\n lik.fh.tiltedMoments = @lik_lgp_tiltedMoments;\n lik.fh.predy = @lik_lgp_predy;\n lik.fh.invlink = @lik_lgp_invlink;\n lik.fh.recappend = @lik_lgp_recappend;\n end\n\nend\n\nfunction [w,s,h] = lik_lgp_pak(lik)\n%LIK_LGP_PAK Combine likelihood parameters into one vector.\n%\n% Description \n% W = LIK_LGP_PAK(LIK) takes a likelihood structure LIK\n% and returns an empty verctor W. If LGP likelihood had\n% parameters this would combine them into a single row vector\n% W (see e.g. lik_negbin). This is a mandatory subfunction \n% used for example in energy and gradient computations.\n% \n% See also\n% LIK_LGP_UNPAK, GP_PAK\n\n w = []; s = {}; h=[];\nend\n\n\nfunction [lik, w] = lik_lgp_unpak(lik, w)\n%LIK_LGP_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_LGP_UNPAK(W, LIK) Doesn't do anything.\n%\n% If LGP likelihood had parameters this would extract them\n% parameters from the vector W to the LIK structure. This \n% is a mandatory subfunction used for example in energy \n% and gradient computations.\n% \n%\n% See also\n% LIK_LGP_PAK, GP_UNPAK\n\n lik=lik;\n w=w;\n \nend\n\n\nfunction logLik = lik_lgp_ll(lik, y, f, z)\n%LIK_LGP_LL Log likelihood\n%\n% Description\n% E = LIK_LGP_LL(LIK, Y, F, Z) takes a likelihood data\n% structure LIK, incedence counts Y, expected counts Z, and\n% latent values F. Returns the log likelihood, log p(y|f,z).\n% This subfunction is needed when using Laplace approximation \n% or MCMC for inference with non-Gaussian likelihoods. This \n% subfunction is also used in information criteria (DIC, WAIC) \n% computations.\n%\n% See also\n% LIK_LGP_LLG, LIK_LGP_LLG3, LIK_LGP_LLG2, GPLA_E\n\n n=sum(y);\n qj=exp(f);\n logLik = sum(f.*y)-n*log(sum(qj));\nend\n\n\nfunction deriv = lik_lgp_llg(lik, y, f, param, z)\n%LIK_LGP_LLG Gradient of the log likelihood\n%\n% Description \n% G = LIK_LGP_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z\n% and latent values F. Returns the gradient of the log\n% likelihood with respect to PARAM. At the moment PARAM can be\n% 'param' or 'latent'. This subfunction is needed when using Laplace \n% approximation or MCMC for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_LGP_LL, LIK_LGP_LLG2, LIK_LGP_LLG3, GPLA_E\n \n switch param\n case 'latent'\n n=sum(y);\n qj=exp(f);\n pj=qj./sum(qj);\n deriv=y-n*pj;\n end\nend\n\n\nfunction g2 = lik_lgp_llg2(lik, y, f, param, z)\n%function g2 = lik_lgp_llg2(lik, y, f, param, z)\n%LIK_LGP_LLG2 Second gradients of the log likelihood\n%\n% Description \n% G2 = LIK_LGP_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z,\n% and latent values F. Returns the Hessian of the log\n% likelihood with respect to PARAM. At the moment PARAM can be\n% only 'latent'. G2 is a vector with diagonal elements of the\n% Hessian matrix (off diagonals are zero). This subfunction \n% is needed when using Laplace approximation or EP for \n% inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_LGP_LL, LIK_LGP_LLG, LIK_LGP_LLG3, GPLA_E\n\n switch param\n case 'latent'\n qj=exp(f);\n \n % g2 is not the second gradient of the log likelihood but only a\n % vector to form the exact gradient term in gpla_nd_e, gpla_nd_g and\n % gpla_nd_pred functions\n g2=qj./sum(qj);\n end\nend \n\nfunction g3 = lik_lgp_llg3(lik, y, f, param, z)\n%LIK_LGP_LLG3 Third gradients of the log likelihood\n%\n% Description\n% G3 = LIK_LGP_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, incedence counts Y, expected counts Z\n% and latent values F and returns the third gradients of the\n% log likelihood with respect to PARAM. At the moment PARAM\n% can be only 'latent'. G3 is a vector with third gradients.\n% This subfunction is needed when using Laplace approximation \n% for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_LGP_LL, LIK_LGP_LLG, LIK_LGP_LLG2, GPLA_E, GPLA_G\n \n switch param\n case 'latent'\n qj=exp(f);\n \n % g3 is not the third gradient of the log likelihood but only a\n % vector to form the exact gradient term in gpla_nd_e, gpla_nd_g and\n % gpla_nd_pred functions\n g3=qj./sum(qj);\n \n %n=sum(y);\n %nf=size(f,1);\n %g3d=zeros(nf,nf);\n %for i1=1:nf\n % g3dtmp=-g3*g3(i1);\n % g3dtmp(i1)=g3dtmp(i1)+g3(i1);\n % g3d(:,i1)=g3dtmp;\n % %g3i1= n*(-diag(g3d(:,i1)) + bsxfun(@times,g3,g3d(:,i1)') + bsxfun(@times,g3d(:,i1),g3'));\n %end\n end\nend\n\nfunction [logM_0, m_1, sigm2hati1] = lik_lgp_tiltedMoments(lik, y, i1, sigm2_i, myy_i, z)\n%LIK_LGP_TILTEDMOMENTS Returns the marginal moments for EP algorithm\n%\n% Description\n% [M_0, M_1, M2] = LIK_LGP_TILTEDMOMENTS(LIK, Y, I, S2,\n% MYY, Z) takes a likelihood structure LIK, incedence counts\n% Y, expected counts Z, index I and cavity variance S2 and\n% mean MYY. Returns the zeroth moment M_0, mean M_1 and\n% variance M_2 of the posterior marginal (see Rasmussen and\n% Williams (2006): Gaussian processes for Machine Learning,\n% page 55). This subfunction is needed when using EP for \n% inference with non-Gaussian likelihoods.\n%\n% See also\n% GPEP_E\n\n error('Not implemented')\n \nend\n\n\nfunction [lpy, Ey, Vary] = lik_lgp_predy(lik, Ef, Varf, yt, zt)\n%LIK_LGP_PREDY Returns the predictive mean, variance and density of y\n%\n% Description \n% LPY = LIK_LGP_PREDY(LIK, EF, VARF YT, ZT)\n% Returns also the predictive density of YT, that is \n% p(yt | y,zt) = \\int p(yt | f, zt) p(f|y) df.\n% This requires also the incedence counts YT, expected counts ZT.\n% This subfunction is needed when computing posterior predictive \n% distributions for future observations.\n%\n% [LPY, EY, VARY] = LIK_LGP_PREDY(LIK, EF, VARF) takes a\n% likelihood structure LIK, posterior mean EF and posterior\n% Variance VARF of the latent variable and returns the\n% posterior predictive mean EY and variance VARY of the\n% observations related to the latent variables. This \n% subfunction is needed when computing posterior predictive \n% distributions for future observations.\n% \n\n%\n% See also \n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n\n error('Not implemented')\n \nend\n\nfunction [df,minf,maxf] = init_lgp_norm(yy,myy_i,sigm2_i,myy)\n%INIT_LGP_NORM\n%\n% Description\n% Return function handle to a function evaluating LGP *\n% Gaussian which is used for evaluating (likelihood * cavity)\n% or (likelihood * posterior) Return also useful limits for\n% integration. This is private function for lik_lgp. This \n% subfunction is needed by sufunctions tiltedMoments, siteDeriv \n% and predy.\n% \n% See also\n% LIK_LGP_TILTEDMOMENTS, LIK_LGP_PREDY\n \n% Not applicable\n\nend\n\nfunction mu = lik_lgp_invlink(lik, f, z)\n%LIK_LGP_INVLINK Returns values of inverse link function\n% \n% Description \n% P = LIK_LGP_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values MU of inverse link function.\n% This subfunction is needed when using function gp_predprctmu.\n%\n% See also\n% LIK_LGP_LL, LIK_LGP_PREDY\n \n mu = exp(f);\n mu = mu./sum(mu);\n \nend\n\nfunction reclik = lik_lgp_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = LIK_LGP_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood record structure RECLIK, record index RI and\n% likelihood structure LIK with the current MCMC samples of\n% the parameters. Returns RECLIK which contains all the old\n% samples and the current samples from LIK. This subfunction \n% is needed when using MCMC sampling (gp_mc).\n% \n% See also\n% GP_MC\n\n if nargin == 2\n reclik.type = 'LGP';\n\n % Set the function handles\n reclik.fh.pak = @lik_lgp_pak;\n reclik.fh.unpak = @lik_lgp_unpak;\n reclik.fh.ll = @lik_lgp_ll;\n reclik.fh.llg = @lik_lgp_llg; \n reclik.fh.llg2 = @lik_lgp_llg2;\n reclik.fh.llg3 = @lik_lgp_llg3;\n reclik.fh.tiltedMoments = @lik_lgp_tiltedMoments;\n reclik.fh.predy = @lik_lgp_predy;\n reclik.fh.invlink = @lik_lgp_invlink;\n reclik.fh.recappend = @lik_lgp_recappend;\n return\n end\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/lik_lgp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6399972483232232}} {"text": "function [hold_state, cax, next] = axes(majors,ticks)\n% TERNARY.AXES create ternary axis\n% [hold_state, cax, next] = TERNARY.AXES(MAJORS) creates a ternary axis system using the system\n% defaults and with MAJORS major tickmarks with percentage labels at tick\n% marks. Returns the hold state of the plot.\n%\n% [hold_state, cax, next] = TERNARY.AXES(MAJORS,'fractions') returns the\n% axes with fraction of unit at tick marks.\n\n% Author: Carl Sandrock 20050211\n% Modifications: FVA: \n\n% To Do\n\n% Modifications\n\n% Modifiers\n% (CS) Carl Sandrock\n\npercentage = 1;\nif nargin > 1\n switch ticks\n case 'fraction'\n percentage = 0;\n otherwise\n percentage = 1;\n end\nend\n\n%TODO: Get a better way of offsetting the labels\nxoffset = 0.01;\nyoffset = 0.02;\n\n% get hold state\ncax = newplot;\nnext = lower(get(cax,'NextPlot'));\nhold_state = ishold;\n\n% get x-axis text color so grid is in same color\ntc = get(cax,'xcolor');\nls = get(cax,'gridlinestyle');\n\n% Hold on to current Text defaults, reset them to the\n% Axes' font attributes so tick marks use them.\nfAngle = get(cax, 'DefaultTextFontAngle');\nfName = get(cax, 'DefaultTextFontName');\nfSize = get(cax, 'DefaultTextFontSize');\nfWeight = get(cax, 'DefaultTextFontWeight');\nfUnits = get(cax, 'DefaultTextUnits');\n\nset(cax, 'DefaultTextFontAngle', get(cax, 'FontAngle'), ...\n 'DefaultTextFontName', get(cax, 'FontName'), ...\n 'DefaultTextFontSize', get(cax, 'FontSize'), ...\n 'DefaultTextFontWeight', get(cax, 'FontWeight'), ...\n 'DefaultTextUnits','data')\n\n% only do grids if hold is off\nif ~hold_state\n\t%plot axis lines\n\thold on;\n\tplot ([0 1 0.5 0],[0 0 sin(1/3*pi) 0], 'color', tc, 'linewidth',1,...\n 'handlevisibility','off');\n\tset(gca, 'visible', 'off');\n\n % plot background if necessary\n if ~ischar(get(cax,'color')),\n patch('xdata', [0 1 0.5 0], 'ydata', [0 0 sin(1/3*pi) 0], ...\n 'edgecolor',tc,'facecolor',get(gca,'color'),...\n 'handlevisibility','off');\n end\n \n\t% Generate labels\n\tmajorticks = linspace(0, 1, majors + 1);\n\tmajorticks = majorticks(1:end-1);\n if percentage \n labels = num2str(majorticks'*100);\n else\n labels = num2str(majorticks','%1.1g');%Doesn't work! I don't want it to put a leading zero, that's all!\n end\n\t\n zerocomp = zeros(size(majorticks)); % represents zero composition\n \n\t% Plot right labels (no c - only b a)\n\t[lxc, lyc] = ternary.coords(1-majorticks, majorticks, zerocomp);\n\ttext(lxc, lyc, [repmat(' ', length(labels), 1) labels]);\n\t\n\t% Plot bottom labels (no b - only a c)\n\t[lxb, lyb] = ternary.coords(majorticks, zerocomp, 1-majorticks); % fB = 1-fA\n\ttext(lxb, lyb, labels, 'VerticalAlignment', 'Top');\n\t\n\t% Plot left labels (no a, only c b)\n\t[lxa, lya] = ternary.coords(zerocomp, 1-majorticks, majorticks);\n\t%text(lxa-xoffset, lya, labels, 'HorizontalAlignment','right');\n\ttext(lxa-xoffset, lya, labels, 'HorizontalAlignment','right');\n\t\n\tnlabels = length(labels)-1;\n\tfor i = 1:nlabels\n plot([lxa(i+1) lxb(nlabels - i + 2)], [lya(i+1) lyb(nlabels - i + 2)], ls, 'color', tc, 'linewidth',1,...\n 'handlevisibility','off');\n plot([lxb(i+1) lxc(nlabels - i + 2)], [lyb(i+1) lyc(nlabels - i + 2)], ls, 'color', tc, 'linewidth',1,...\n 'handlevisibility','off');\n plot([lxc(i+1) lxa(nlabels - i + 2)], [lyc(i+1) lya(nlabels - i + 2)], ls, 'color', tc, 'linewidth',1,...\n 'handlevisibility','off');\n end\nend%if ~hold_state\n\n% Reset defaults\nset(cax, 'DefaultTextFontAngle', fAngle , ...\n 'DefaultTextFontName', fName , ...\n 'DefaultTextFontSize', fSize, ...\n 'DefaultTextFontWeight', fWeight, ...\n 'DefaultTextUnits', fUnits );\nreturn%[hold_state, cax, next]\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/30914-entropy-triangle/entropy_triangle/+ternary/axes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.639884862121728}} {"text": "function varargout = pr(varargin)\n%VL_PR Precision-recall curve.\n% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the\n% precision-recall (PR) curve. LABELS are the ground truth labels,\n% greather than zero for a positive sample and smaller than zero for\n% a negative one. SCORES are the scores of the samples obtained from\n% a classifier, where lager scores should correspond to positive\n% samples.\n%\n% Samples are ranked by decreasing scores, starting from rank 1.\n% PRECISION(K) and RECALL(K) are the precison and recall when\n% samples of rank smaller or equal to K-1 are predicted to be\n% positive and the remaining to be negative. So for example\n% PRECISION(3) is the percentage of positive samples among the two\n% samples with largest score. PRECISION(1) is the precision when no\n% samples are predicted to be positive and is conventionally set to\n% the value 1.\n%\n% Set to zero the lables of samples that should be ignored in the\n% evaluation. Set to -INF the scores of samples which are not\n% retrieved. If there are samples with -INF score, then the PR curve\n% may have maximum recall smaller than 1, unless the INCLUDEINF\n% option is used (see below). The options NUMNEGATIVES and\n% NUMPOSITIVES can be used to add additional surrogate samples with\n% -INF score (see below).\n%\n% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional\n% structure INFO with the following fields:\n%\n% info.auc::\n% The area under the precision-recall curve. If the INTERPOLATE\n% option is set to FALSE, then trapezoidal interpolation is used\n% to integrate the PR curve. If the INTERPOLATE option is set to\n% TRUE, then the curve is piecewise constant and no other\n% approximation is introduced in the calculation of the area. In\n% the latter case, INFO.AUC is the same as INFO.AP.\n%\n% info.ap::\n% Average precision as defined by TREC. This is the average of the\n% precision observed each time a new positive sample is\n% recalled. In this calculation, any sample with -INF score\n% (unless INCLUDEINF is used) and any additional positive induced\n% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE\n% option is set to true, the AP is computed from the interpolated\n% precision and the result is the same as INFO.AUC. Note that AP\n% as defined by TREC normally does not use interpolation [1].\n%\n% info.ap_interp_11::\n% 11-points interpolated average precision as defined by TREC.\n% This is the average of the maximum precision for recall levels\n% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in\n% the PASCAL VOC challenge up to the 2008 edition.\n%\n% info.auc_pa08::\n% Deprecated. It is the same of INFO.AP_INTERP_11.\n%\n% VL_PR(...) with no output arguments plots the PR curve in the\n% current axis.\n%\n% VL_PR() accepts the following options:\n%\n% Interpolate:: false\n% If set to true, use interpolated precision. The interpolated\n% precision is defined as the maximum precision for a given recall\n% level and onwards. Here it is implemented as the culumative\n% maximum from low to high scores of the precision.\n%\n% NumPositives:: []\n% NumNegatives:: []\n% If set to a number, pretend that LABELS contains this may\n% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be\n% smaller than the actual number of positive/negative entrires in\n% LABELS. The additional positive/negative labels are appended to\n% the end of the sequence, as if they had -INF scores (not\n% retrieved). This is useful to evaluate large retrieval systems\n% for which one stores ony a handful of top results for efficiency\n% reasons.\n%\n% IncludeInf:: false\n% If set to true, data with -INF score SCORES is included in the\n% evaluation and the maximum recall is 1 even if -INF scores are\n% present. This option does not include any additional positive or\n% negative data introduced by specifying NUMPOSITIVES and\n% NUMNEGATIVES.\n%\n% Stable:: false\n% If set to true, RECALL and PRECISION are returned in the same order\n% of LABELS and SCORES rather than being sorted by decreasing\n% score (increasing recall). Samples with -INF scores are assigned\n% RECALL and PRECISION equal to NaN.\n%\n% NormalizePrior:: []\n% If set to a scalar, reweights positive and negative labels so\n% that the fraction of positive ones is equal to the specified\n% value. This computes the normalised PR curves of [2]\n%\n% About the PR curve::\n% This section uses the same symbols used in the documentation of\n% the VL_ROC() function. In addition to those quantities, define:\n%\n% PRECISION(S) = TP(S) / (TP(S) + FP(S))\n% RECALL(S) = TPR(S) = TP(S) / P\n%\n% The precision is the fraction of positivie predictions which are\n% correct, and the recall is the fraction of positive labels that\n% have been correctly classified (recalled). Notice that the recall\n% is also equal to the true positive rate for the ROC curve (see\n% VL_ROC()).\n%\n% REFERENCES:\n% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to\n% Information Retrieval. Cambridge University Press, 2008.\n% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in\n% object detectors. In Proc. ECCV, 2012.\n%\n% See also VL_ROC(), VL_HELP().\n[varargout{1:nargout}] = vl_pr(varargin{:});\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/noprefix/pr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6398110336598105}} {"text": "function tet_mesh_volumes ( prefix )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for TET_MESH_VOLUMES.\n%\n% Discussion:\n%\n% TET_MESH_VOLUMES determines the element volumes of a tet mesh.\n%\n% Usage:\n%\n% tet_mesh_volumes ( 'prefix' )\n%\n% where\n%\n% * 'prefix'_nodes.txt contains nodal coordinates;\n% * 'prefix'_elements.txt contains the element definitions;\n% * 'prefix'_volumes.txt will contain the element volumes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n timestamp ( )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TET_MESH_VOLUMES:\\n' );\n fprintf ( 1, ' MATLAB version:\\n' );\n fprintf ( 1, ' Compute volume of each tetrahedron in a tet mesh.\\n' );\n%\n% Argument 1 is the common file prefix.\n%\n if ( 1 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TET_MESH_VOLUMES:\\n' );\n prefix = input ( ' Please enter the filename prefix:' );\n\n end\n%\n% Create the filenames.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n element_filename = strcat ( prefix, '_elements.txt' );\n volume_filename = strcat ( prefix, '_volumes.txt' );\n%\n% Read the node data.\n%\n [ dim_num, node_num ] = r8mat_header_read ( node_filename );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read the header of \"%s\".\\n', node_filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, ' Number of points NODE_NUM = %d\\n', node_num );\n\n if ( dim_num ~= 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TET_MESH_VOLUMES - Fatal error!\\n' );\n fprintf ( 1, ' Dataset must have spatial dimension 3.\\n' );\n error ( 'TET_MESH_VOLUMES - Fatal error!' );\n end\n\n node_xyz = r8mat_data_read ( node_filename, dim_num, node_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read the data in \"%s\".\\n', node_filename );\n\n r8mat_transpose_print_some ( dim_num, node_num, node_xyz, 1, 1, 5, 5, ...\n ' 5 by 5 portion of data read from file:' );\n%\n% Read the element data.\n%\n [ element_order, element_num ] = i4mat_header_read ( element_filename );\n\n if ( element_order ~= 4 && element_order ~= 10 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TET_MESH_VOLUMES - Fatal error!\\n' );\n fprintf ( 1, ' Data is not for a 4 or 10 node tet mesh.\\n' );\n error ( 'TET_MESH_VOLUMES - Fatal error!' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read the header of \"%s\".\\n', element_filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Element order = %d\\n', element_order );\n fprintf ( 1, ' Number of elements = %d\\n', element_num );\n\n element_node = i4mat_data_read ( element_filename, element_order, element_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read the data in \"%s\".\\n', element_filename );\n\n i4mat_transpose_print_some ( element_order, element_num, ...\n element_node, 1, 1, element_order, 10, ' Portion of TETRA_NODE:' );\n%\n% Detect and correct 0-based indexing.\n%\n element_node = mesh_base_one ( node_num, element_order, element_num, ...\n element_node );\n%\n% Compute and the volumes.\n%\n volume = zeros ( element_num );\n\n for element = 1 : element_num\n tetra(1:3,1:4) = node_xyz(1:3,element_node(1:4,element));\n volume(element) = tetrahedron_volume ( tetra );\n end\n\n volume_max = max ( volume(1:element_num) );\n volume_min = min ( volume(1:element_num) );\n volume_ave = sum ( volume(1:element_num) ) / element_num;\n volume_tot = sum ( volume(1:element_num) );\n volume_var = r8vec_variance ( element_num, volume );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Minimum: %f\\n', volume_min );\n fprintf ( 1, ' Average: %f\\n', volume_ave );\n fprintf ( 1, ' Maximum: %f\\n', volume_max );\n fprintf ( 1, ' Total: %f\\n', volume_tot );\n fprintf ( 1, ' Variance: %f\\n', volume_var );\n\n r8mat_write ( volume_filename, 1, element_num, volume );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Full list of volumes written to \"%s\".\\n',...\n volume_filename );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TET_MESH_VOLUMES:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction table = i4mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% I4MAT_DATA_READ reads data from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns in the data.\n%\n% Output, integer TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %d' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the input file.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' End of input while reading data.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = i4mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% I4MAT_HEADER_READ reads the header from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction i4mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% I4MAT_TRANSPOSE_PRINT_SOME prints some of an I4MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 10;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n fprintf ( 1, '\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%7d ', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction element_node = mesh_base_one ( node_num, element_order, ...\n element_num, element_node )\n\n%*****************************************************************************80\n%\n%% MESH_BASE_ONE ensures that the element definition is one-based.\n%\n% Discussion:\n%\n% The ELEMENT_NODE array contains nodes indices that form elements.\n% The convention for node indexing might start at 0 or at 1.\n% Since a MATLAB program will naturally assume a 1-based indexing, it is\n% necessary to check a given element definition and, if it is actually\n% 0-based, to convert it.\n%\n% This function attempts to detect 0-based node indexing and correct it.\n%\n% Thanks to Feifei Xu for pointing out that I was subtracting 1 when I\n% should have been adding 1! 29 November 2012.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer ELEMENT_ORDER, the order of the elements.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input/output, integer ELEMENT_NODE(ELEMENT_ORDE,ELEMENT_NUM), the element\n% definitions.\n%\n node_min = min ( min ( element_node(1:element_order,1:element_num) ) );\n node_max = max ( max ( element_node(1:element_order,1:element_num) ) );\n\n if ( node_min == 0 && node_max == node_num - 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MESH_BASE_ONE:\\n' );\n fprintf ( 1, ' The element indexing appears to be 0-based!\\n' );\n fprintf ( 1, ' This will be converted to 1-based.\\n' );\n element_node(1:element_order,1:element_num) = ...\n element_node(1:element_order,1:element_num) + 1;\n elseif ( node_min == 1 && node_max == node_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MESH_BASE_ONE:\\n' );\n fprintf ( 1, ' The element indexing appears to be 1-based!\\n' );\n fprintf ( 1, ' No conversion is necessary.\\n' );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MESH_BASE_ONE - Warning!\\n' );\n fprintf ( 1, ' The element indexing is not of a recognized type.\\n' );\n end\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = zeros ( m, n );\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction det = r8mat_det_4d ( a )\n\n%*****************************************************************************80\n%\n%% R8MAT_DET_4D computes the determinant of a 4 by 4 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 January 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(4,4), the matrix whose determinant is desired.\n%\n% Output, real DET, the determinant of the matrix.\n%\n det = ...\n a(1,1) * ( ...\n a(2,2) * ( a(3,3) * a(4,4) - a(3,4) * a(4,3) ) ...\n - a(2,3) * ( a(3,2) * a(4,4) - a(3,4) * a(4,2) ) ...\n + a(2,4) * ( a(3,2) * a(4,3) - a(3,3) * a(4,2) ) ) ...\n - a(1,2) * ( ...\n a(2,1) * ( a(3,3) * a(4,4) - a(3,4) * a(4,3) ) ...\n - a(2,3) * ( a(3,1) * a(4,4) - a(3,4) * a(4,1) ) ...\n + a(2,4) * ( a(3,1) * a(4,3) - a(3,3) * a(4,1) ) ) ...\n + a(1,3) * ( ...\n a(2,1) * ( a(3,2) * a(4,4) - a(3,4) * a(4,2) ) ...\n - a(2,2) * ( a(3,1) * a(4,4) - a(3,4) * a(4,1) ) ...\n + a(2,4) * ( a(3,1) * a(4,2) - a(3,2) * a(4,1) ) ) ...\n - a(1,4) * ( ...\n a(2,1) * ( a(3,2) * a(4,3) - a(3,3) * a(4,2) ) ...\n - a(2,2) * ( a(3,1) * a(4,3) - a(3,3) * a(4,1) ) ...\n + a(2,3) * ( a(3,1) * a(4,2) - a(3,2) * a(4,1) ) );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 5;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%12f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For greater precision, try:\n%\n% fprintf ( output_unit, ' %24,16f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %14f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction mean = r8vec_mean ( n, x )\n\n%*****************************************************************************80\n%\n%% R8VEC_MEAN returns the mean of an R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real X(N), the vector whose mean is desired.\n%\n% Output, real MEAN, the mean, or average,\n% of the vector entries.\n%\n mean = sum ( x(1:n) ) / n;\n\n return\nend\nfunction variance = r8vec_variance ( n, x )\n\n%*****************************************************************************80\n%\n%% R8VEC_VARIANCE returns the variance of an R8VEC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real X(N), the vector whose variance is desired.\n%\n% Output, real VARIANCE, the variance of the vector entries.\n%\n mean = r8vec_mean ( n, x );\n\n variance = sum ( ( x(1:n) - mean ).^2 );\n\n if ( 1 < n )\n variance = variance / ( n - 1 );\n else\n variance = 0.0;\n end \n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*****************************************************************************80\n%\n% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LENGTH, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\nfunction word_num = s_word_count ( s )\n\n%*****************************************************************************80\n%\n%% S_WORD_COUNT counts the number of \"words\" in a string.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be examined.\n%\n% Output, integer WORD_NUM, the number of \"words\" in the string.\n% Words are presumed to be separated by one or more blanks.\n%\n FALSE = 0;\n TRUE = 1;\n\n word_num = 0;\n s_length = length ( s );\n\n if ( s_length <= 0 )\n return;\n end\n\n blank = TRUE;\n\n for i = 1 : s_length\n\n if ( s(i) == ' ' )\n blank = TRUE;\n elseif ( blank == TRUE )\n word_num = word_num + 1;\n blank = FALSE;\n end\n\n end\n\n return\nend\nfunction volume = tetrahedron_volume ( tetra )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_VOLUME computes the volume of a tetrahedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real TETRA(3,4), the vertices of the tetrahedron.\n%\n% Output, real VOLUME, the volume of the tetrahedron.\n%\n dim_num = 3;\n\n a(1:dim_num,1:4) = tetra(1:dim_num,1:4);\n a(4,1:4) = 1.0;\n\n volume = abs ( r8mat_det_4d ( a ) ) / 6.0;\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tet_mesh_volumes/tet_mesh_volumes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6398110271362706}} {"text": "function accuracy = rksr_dsk_classifier(TrainSet, TestSet, options)\n% Riemannian kernelized sparse representation classification (R-KSRC) with discriminative Stein kernel algorithm\n%\n% Inputs:\n% TrainSet train sets of size dxn, where d is dimension and n is number of sets \n% TestSet test sets of size dxn, where d is dimension and n is number of sets\n% options options\n% Output:\n% accuracy classification accurary\n%\n% References:\n% M. Harandi, R. Hartley, B. Lovell and C. Sanderson, \n% \"Sparse coding on symmetric positive definite manifolds using bregman divergences,\" \n% IEEE Transactions on Neural Networks and Learning Systems, vol.27, no.6, pp.1294-1306, 2016.\n%\n% M. Harandi, C. Sanderson, R. Hartley and B. Lovell, \n% \"Sparse coding and dictionary learning for symmetric positive definite matrices: a kernel approach,\" \n% European Conference on Computer Vision (ECCV), 2012.\n%\n% J. Zhang, L. Wang. L. Zhou, and W. Li,\n% \"Learning discriminative Stein kernel for SPD matrices and its applications,\" \n% IEEE Transactions on Neural Networks and Learning Systems, vol.27, no.5, pp.1020-1033, 2015.\n%\n% Originally created by Mehrtash Harandi (mehrtash.harandi at gmail dot com).\n% Originally created by J. Zhang (jz163@uowmail.edu.au).\n% Modified by H. Kasai on July 10, 2017.\n\n \n \n % retrieve dimension of the SPD matrices\n dim = size(TrainSet.X_cov, 1);\n test_num = length(TestSet.y);\n class_num = length(unique(TestSet.y));\n \n % calculate eigen decomposition\n train_decomp = Decomposite_eig_new(TrainSet);\n test_decomp = Decomposite_eig_new(TestSet);\n \n % learn alpha of kernel\n if ~options.original_alpha\n initial_alpha = 1*ones(1,dim); % the initial alpha corresponding to the original Stein kernel\n LB = 0.01*initial_alpha; \n\n fmincon_opt = optimset('Algorithm', 'interior-point'); % run interior-point algorithm\n \n if options.verbose\n fmincon_opt.Display = 'iter'; \n else\n fmincon_opt.Display = 'off';\n end\n fmincon_opt.MaxIter = 100;\n fmincon_opt.TolFun = 1e-5;\n %tic\n optimal_alpha = fmincon(@(alpha) objfun_ff_new(alpha,TrainSet.y,train_decomp, options.lambda,initial_alpha,options.obj_method,options.theta),initial_alpha,[],[],[],[],LB,[],[],fmincon_opt);\n %toc\n else\n optimal_alpha = ones(1,dim);\n end\n \n \n % compute the Stein divergence with the obtained adjustment parameter optimal_alpha\n S_test = EigComp2SD_power_new(train_decomp, test_decomp, optimal_alpha); \n S_train = EigComp2SD_power_new(train_decomp, train_decomp, optimal_alpha);\n train_kernel = exp(-1 * options.theta * S_train); \n test_kernel = exp(-1 * options.theta * S_test); \n\n % normalize dictionary\n [KD, ~] = data_normalization(train_kernel, [], 'std'); \n [KX, ~] = data_normalization(test_kernel, [], 'std'); \n\n [KD_U, KD_D, ~] = svd(KD); \n A = diag(sqrt(diag(KD_D))) * KD_U';\n D_Inv = KD_U * diag(1./sqrt(diag(KD_D)));\n KX = D_Inv' * KX;\n \n % perform lasso\n param.lambda = options.lambda;\n param.lambda2 = 0; \n param.mode = 2;\n scX = full(mexLasso(KX,A,param));\n \n % prepare class array\n classes = unique(TrainSet.y); \n % prepare predicted label array\n identity = zeros(1, test_num);\n \n for i = 1 : test_num\n % prepare residual array\n residuals = zeros(1, class_num);\n \n % calculate residual for each class\n for j = 1 : class_num\n idx = find(TrainSet.y == classes(j));\n %residuals(j) = norm(KX(:, i) - A(:,idx)*scX(idx, i))/sum(scX(idx, i) .* scX(idx, i));\n residuals(j) = norm(KX(:, i) - A(:,idx)*scX(idx, i));\n \n if strcmp(options.mode, 'src')\n residuals(j) = norm(KX(:, i) - A(:,idx)*scX(idx, i)); \n elseif strcmp(options.mode, 'ip_linear')\n scX_i = scX(idx, i);\n %residuals(j) = sum(abs(scX_i));\n residuals(j) = sum(scX_i);\n elseif strcmp(options.mode, 'ip_max')\n scX_i = scX(idx, i);\n residuals(j) = max(abs(scX_i));\n end\n end\n\n % calculate the predicted label\n [~, label] = min(residuals); \n if strcmp(options.mode, 'src')\n [~, label] = min(residuals); \n elseif strcmp(options.mode, 'ip_linear') || strcmp(options.mode, 'ip_max')\n [~, label] = max(residuals); \n end\n identity(i) = label;\n \n if options.verbose\n correct = (label == TestSet.y(1, i));\n fprintf('# RSR-DSK-%s (with %s metric): test:%03d, predict class: %03d --> ground truth :%03d (%d)\\n', options.obj_method, options.mode, i, label, TestSet.y(1, i), correct);\n end \n end\n\n % calculate accuracy\n correct_num = sum(identity == TestSet.y);\n accuracy = correct_num/test_num;\nend\n\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/algorithm/rksr_dsk_classifier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6397604299904344}} {"text": "function nodevol=nodevolume(node,elem, evol)\n%\n% nodevol=nodevolume(node,elem)\n%\n% calculate the volumes of the cells in the barycentric dual-mesh\n% (this is different from the Voronoi cells, which blong to the \n% circumcentric dual mesh)\n%\n% author: Qianqian Fang, \n% date: 2009/12/31\n%\n% input:\n% node: node coordinates\n% elem: element table of a mesh\n%\n% output:\n% nodevol: volume values for all nodes\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\ndim=4;\nif(size(elem,2)==3) dim=3; end\n\nif(nargin<3)\n evol=elemvolume(node,elem(:,1:dim));\nend\n\nelemnum=size(elem,1);\nnodenum=size(node,1);\nnodevol=zeros(nodenum,1);\nfor i=1:elemnum\n nodevol(elem(i,1:dim))=nodevol(elem(i,1:dim))+evol(i);\nend\nnodevol=nodevol/dim;\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/nodevolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6396457327420223}} {"text": "function D = compute_histogram_distance(H, options)\n\n% compute_histogram_distance - compute distance between histograms\n%\n% D = compute_histogram_distance(H, options);\n%\n% H(:,i) is the ith histogram.\n%\tD(i,g) is the distance between histogram i and j.\n%\n%\toptions.histmetric is the metric used to compute the distance d(g,h) between two histograms.\n%\tWe denote by G and H the cumulative distribution, i.e. G=cumsum(g)\n%\t\t'l2' -> d(g,h)^2 = sum_i (g(i)-h(i))^2\n%\t\t'l1' -> d(g,h) = sum_i abs(g(i)-h(i))\n%\t\t'cl2' -> d(g,h)^2 = sum_i (G(i)-H(i))^2\n%\t\t'cl1' -> d(g,h) = sum_i abs(G(i)-H(i))\n%\t\t'chi2' -> d(g,h) = sum_i (G(i)-H(i))^2 / (G(i)+H(i))\n%\t\t'bhatta' -> d(g,h) = 1 - sum_i sqrt(G(i)*H(i))\n% options.sigma is a pre-smoothing factor, counted in pixels.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\nif isfield(options, 'sigma')\n\tsigma = options.sigma;\nelse\n\tsigma = 1.2;\nend\nif isfield(options, 'histmetric')\n\thistmetric = options.histmetric;\nelse\n\thistmetric = 'histmetric';\nend\n\n%% smooth the histograms\nn = size(H,1);\nm = size(H,2);\nh = compute_gaussian_filter( 21,sigma/(2*n),n);\nfor i=1:m\n H(:,i) = perform_convolution(H(:,i),h);\nend\n\n% make them sum to 1\nH = max(H,0);\nH = H ./ repmat( sum(H,1), [n 1] );\n\n%% compute distance\nswitch lower(histmetric)\n case {'cl2' 'cl1'}\n D = distance_matrix(cumsum(H), histmetric(2:end) );\n otherwise\n D = distance_matrix(H, histmetric );\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distance_matrix(X,metric)\n\nn = size(X,1); % dimension\np = size(X,2);\n\nA = repmat( reshape(X', [p 1 n] ), [1 p]);\nB = permute(A, [2 1 3]);\n\nswitch metric\n case 'l1'\n D = sum( abs(A-B), 3 );\n case 'l2'\n D = sqrt( sum( (A-B).^2, 3 ) );\n case 'chi2'\n a = A+B; a(a1 ) | ( size(p2.e,2)>1 )\n error('divison only for univariate polynomials')\n end\n \n % both p1 and p2 univariate polynomials\n if ~isequal(p1.v,p2.v) & ~isempty(p1.v) & ~isempty(p2.v)\n error('division only for univariate polynomials depending on the same variable')\n end\n \n isint = isa(p1.c,'intval') | isa(p2.c,'intval');\n \n if p2.e==0 % p2 is constant\n q = p1;\n q.c = p1.c/p2.c;\n if nargout==2\n if isint\n r = polynom(intval(0),p1.v);\n else\n r = polynom(0,p1.v);\n end\n end \n if rndold\n setround(rndold)\n end\n return\n end\n \n if p1.e', 'Fontsize', 24 );\n ylabel ( '<--- X(T) --->', 'Fontsize', 24 );\n\n hold off\n\n filename = 'uniform_run.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Multiple solutions plotted in file \"%s\".\\n', filename );\n%\n% Since our deltas were computed randomly, they aren't in order.\n% We need to sort them, and their corresponding function values,\n% before plotting.\n%\n [ d_plot, i ] = sort ( d_plot );\n q_plot = q_plot(i);\n%\n% Plot the observed values of delta versus F, the time at\n% which the solution reached 0.99.\n%\n figure ( 2 )\n plot ( d_plot, q_plot, 'r.-', 'Linewidth', 3, 'Markersize', 25 );\n grid on\n xlabel ( '<-- Parameter Delta -->', 'Fontsize', 24 )\n ylabel ( '<-- Ignition time Q(Delta) -->', 'Fontsize', 24 )\n title ( 'Ignition time as a function of parameter Delta', 'Fontsize', 24 )\n\n filename = 'uniform_qoi.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Quantity of Interest plotted in file \"%s\".\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UNIFORM_RUN\\n' );\n fprintf ( 1, ' Normal end of execution\\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/flame_ode/uniform_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6395109714407605}} {"text": "function x = daub12_transform_inverse ( n, y )\n\n%*****************************************************************************80\n%\n%% DAUB12_TRANSFORM_INVERSE inverts the DAUB12 transform of a vector.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the vector.\n% N must be a power of 2 and at least 4.\n%\n% Input, real Y(N), the transformed vector.\n%\n% Output, real X(N), the original vector.\n%\n c = [ ...\n 0.1115407433501095; ...\n 0.4946238903984533; ...\n 0.7511339080210959; ...\n 0.3152503517091982; ...\n -0.2262646939654400; ...\n -0.1297668675672625; ...\n 0.0975016055873225; ...\n 0.0275228655303053; ...\n -0.0315820393174862; ...\n 0.0005538422011614; ...\n 0.0047772575109455; ...\n -0.0010773010853085 ];\n p = 11;\n x(1:n,1) = y(1:n);\n m = 4;\n q = floor ( ( p - 1 ) / 2 );\n\n while ( m <= n )\n \n z(1:m,1) = 0.0;\n\n j = 1;\n\n mh = floor ( m / 2 );\n\n for i = - q + 1 : mh - q\n \n for k = 0 : 2 : p - 1\n i0 = i4_wrap ( i + k / 2, 1, mh );\n i1 = i4_wrap ( i + mh + k / 2, mh + 1, m );\n z(j,1) = z(j,1) + c(p-k) * x(i0) + c(k+2) * x(i1);\n z(j+1,1) = z(j+1,1) + c(p-k+1) * x(i0) - c(k+1) * x(i1);\n end\n\n j = j + 2;\n\n end\n\n x(1:m,1) = z(1:m);\n\n m = m * 2;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wavelet/daub12_transform_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6395109672476645}} {"text": "function [dc,dk] = bspderiv(d,c,k) \n% \n% Function Name: \n% \n% bspdeval - Evaluate the control points and knot sequence of the derivative \n% of a univariate B-Spline. \n% \n% Calling Sequence: \n% \n% [dc,dk] = bspderiv(d,c,k) \n% \n% Parameters: \n% \n% d\t: Degree of the B-Spline. \n% \n% c\t: Control Points, matrix of size (dim,nc). \n% \n% k\t: Knot sequence, row vector of size nk. \n% \n% dc\t: Control points of the derivative \n% \n% dk\t: Knot sequence of the derivative \n% \n% Description: \n% \n% Evaluate the derivative of univariate B-Spline, which is itself a B-Spline. \n% This function provides an interface to a toolbox 'C' routine. \n[mc,nc] = size(c); \nnk = numel(k); \n % \n % int bspderiv(int d, double *c, int mc, int nc, double *k, int nk, double *dc, \n % double *dk) \n % { \n % int ierr = 0; \n % int i, j, tmp; \n % \n % // control points \n % double **ctrl = vec2mat(c,mc,nc); \n % \n % // control points of the derivative \ndc = zeros(mc,nc-1); % double **dctrl = vec2mat(dc,mc,nc-1); \n % \nfor i=0:nc-2 % for (i = 0; i < nc-1; i++) { \n tmp = d / (k(i+d+2) - k(i+2)); % tmp = d / (k[i+d+1] - k[i+1]); \n for j=0:mc-1 % for (j = 0; j < mc; j++) { \n dc(j+1,i+1) = tmp*(c(j+1,i+2) - c(j+1,i+1)); % dctrl[i][j] = tmp * (ctrl[i+1][j] - ctrl[i][j]); \n end % } \nend % } \n % \ndk = zeros(1,nk-2); % j = 0; \nfor i=1:nk-2 % for (i = 1; i < nk-1; i++) \n dk(i) = k(i+1); % dk[j++] = k[i]; \nend % \n % freevec2mat(dctrl); \n % freevec2mat(ctrl); \n % \n % return ierr; \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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/bspderiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.639509237526178}} {"text": "function [model] = svmTrain(X, Y, C, kernelFunction, ...\n tol, max_passes)\n%SVMTRAIN Trains an SVM classifier using a simplified version of the SMO\n%algorithm.\n% [model] = SVMTRAIN(X, Y, C, kernelFunction, tol, max_passes) trains an\n% SVM classifier and returns trained model. X is the matrix of training\n% examples. Each row is a training example, and the jth column holds the\n% jth feature. Y is a column matrix containing 1 for positive examples\n% and 0 for negative examples. C is the standard SVM regularization\n% parameter. tol is a tolerance value used for determining equality of\n% floating point numbers. max_passes controls the number of iterations\n% over the dataset (without changes to alpha) before the algorithm quits.\n%\n% Note: This is a simplified version of the SMO algorithm for training\n% SVMs. In practice, if you want to train an SVM classifier, we\n% recommend using an optimized package such as:\n%\n% LIBSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/)\n% SVMLight (http://svmlight.joachims.org/)\n%\n%\n\nif ~exist('tol', 'var') || isempty(tol)\n tol = 1e-3;\nend\n\nif ~exist('max_passes', 'var') || isempty(max_passes)\n max_passes = 5;\nend\n\n% Data parameters\nm = size(X, 1);\nn = size(X, 2);\n\n% Map 0 to -1\nY(Y==0) = -1;\n\n% Variables\nalphas = zeros(m, 1);\nb = 0;\nE = zeros(m, 1);\npasses = 0;\neta = 0;\nL = 0;\nH = 0;\n\n% Pre-compute the Kernel Matrix since our dataset is small\n% (in practice, optimized SVM packages that handle large datasets\n% gracefully will _not_ do this)\n%\n% We have implemented optimized vectorized version of the Kernels here so\n% that the svm training will run faster.\nif strcmp(func2str(kernelFunction), 'linearKernel')\n % Vectorized computation for the Linear Kernel\n % This is equivalent to computing the kernel on every pair of examples\n K = X*X';\nelseif strfind(func2str(kernelFunction), 'gaussianKernel')\n % Vectorized RBF Kernel\n % This is equivalent to computing the kernel on every pair of examples\n X2 = sum(X.^2, 2);\n K = bsxfun(@plus, X2, bsxfun(@plus, X2', - 2 * (X * X')));\n K = kernelFunction(1, 0) .^ K;\nelse\n % Pre-compute the Kernel Matrix\n % The following can be slow due to the lack of vectorization\n K = zeros(m);\n for i = 1:m\n for j = i:m\n K(i,j) = kernelFunction(X(i,:)', X(j,:)');\n K(j,i) = K(i,j); %the matrix is symmetric\n end\n end\nend\n\n% Train\nfprintf('\\nTraining ...');\ndots = 12;\nwhile passes < max_passes,\n\n num_changed_alphas = 0;\n for i = 1:m,\n\n % Calculate Ei = f(x(i)) - y(i) using (2).\n % E(i) = b + sum (X(i, :) * (repmat(alphas.*Y,1,n).*X)') - Y(i);\n E(i) = b + sum (alphas.*Y.*K(:,i)) - Y(i);\n\n if ((Y(i)*E(i) < -tol && alphas(i) < C) || (Y(i)*E(i) > tol && alphas(i) > 0)),\n\n % In practice, there are many heuristics one can use to select\n % the i and j. In this simplified code, we select them randomly.\n j = ceil(m * rand());\n while j == i, % Make sure i \\neq j\n j = ceil(m * rand());\n end\n\n % Calculate Ej = f(x(j)) - y(j) using (2).\n E(j) = b + sum (alphas.*Y.*K(:,j)) - Y(j);\n\n % Save old alphas\n alpha_i_old = alphas(i);\n alpha_j_old = alphas(j);\n\n % Compute L and H by (10) or (11).\n if (Y(i) == Y(j)),\n L = max(0, alphas(j) + alphas(i) - C);\n H = min(C, alphas(j) + alphas(i));\n else\n L = max(0, alphas(j) - alphas(i));\n H = min(C, C + alphas(j) - alphas(i));\n end\n\n if (L == H),\n % continue to next i.\n continue;\n end\n\n % Compute eta by (14).\n eta = 2 * K(i,j) - K(i,i) - K(j,j);\n if (eta >= 0),\n % continue to next i.\n continue;\n end\n\n % Compute and clip new value for alpha j using (12) and (15).\n alphas(j) = alphas(j) - (Y(j) * (E(i) - E(j))) / eta;\n\n % Clip\n alphas(j) = min (H, alphas(j));\n alphas(j) = max (L, alphas(j));\n\n % Check if change in alpha is significant\n if (abs(alphas(j) - alpha_j_old) < tol),\n % continue to next i.\n % replace anyway\n alphas(j) = alpha_j_old;\n continue;\n end\n\n % Determine value for alpha i using (16).\n alphas(i) = alphas(i) + Y(i)*Y(j)*(alpha_j_old - alphas(j));\n\n % Compute b1 and b2 using (17) and (18) respectively.\n b1 = b - E(i) ...\n - Y(i) * (alphas(i) - alpha_i_old) * K(i,j)' ...\n - Y(j) * (alphas(j) - alpha_j_old) * K(i,j)';\n b2 = b - E(j) ...\n - Y(i) * (alphas(i) - alpha_i_old) * K(i,j)' ...\n - Y(j) * (alphas(j) - alpha_j_old) * K(j,j)';\n\n % Compute b by (19).\n if (0 < alphas(i) && alphas(i) < C),\n b = b1;\n elseif (0 < alphas(j) && alphas(j) < C),\n b = b2;\n else\n b = (b1+b2)/2;\n end\n\n num_changed_alphas = num_changed_alphas + 1;\n\n end\n\n end\n\n if (num_changed_alphas == 0),\n passes = passes + 1;\n else\n passes = 0;\n end\n\n fprintf('.');\n dots = dots + 1;\n if dots > 78\n dots = 0;\n fprintf('\\n');\n end\n if exist('OCTAVE_VERSION')\n fflush(stdout);\n end\nend\nfprintf(' Done! \\n\\n');\n\n% Save the model\nidx = alphas > 0;\nmodel.X= X(idx,:);\nmodel.y= Y(idx);\nmodel.kernelFunction = kernelFunction;\nmodel.b= b;\nmodel.alphas= alphas(idx);\nmodel.w = ((alphas.*Y)'*X)';\n\nend\n", "meta": {"author": "zsiciarz", "repo": "ml-coursera", "sha": "54208ee72b88f1dc3c9235e644a47f618b80441c", "save_path": "github-repos/MATLAB/zsiciarz-ml-coursera", "path": "github-repos/MATLAB/zsiciarz-ml-coursera/ml-coursera-54208ee72b88f1dc3c9235e644a47f618b80441c/octave/mlclass-ex6/svmTrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728003, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6395092282418423}} {"text": "%% runSignalReconstructionDemo.m\n%\n% This script will create phaseless measurements from a 1d test signal, and \n% then recover the image using phase retrieval methods. We now describe \n% the details of the simple recovery problem that this script implements.\n% \n% Recovery Problem\n% This script creates a complex-valued random Gaussian signal. Measurements\n% of the signal are then obtained by applying a linear operator to the\n% signal, and computing the magnitude (i.e., removing the phase) of \n% the results.\n%\n% Measurement Operator\n% Measurement are obtained using a linear operator, called 'A', that \n% contains random Gaussian entries.\n%\n% The Recovery Algorithm\n% The image is recovered by calling the method 'solvePhaseRetrieval', and\n% handing the measurement operator and linear measurements in as arguments.\n% A struct containing options is also handed to 'solvePhaseRetrieval'.\n% The entries in this struct specify which recovery algorithm is used.\n%\n% For more details, see the Phasepack user guide.\n%\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\nfunction runSignalReconstructionDemo()\n\n%% Specify the signal length, and number of measurements\nn = 100; % The signal length\nm = 8*n; % The number of measurements\n\n%% Build the target signal\nx_true = randn(n,1)+1i*randn(n,1);\n\n%% Create the measurement operator\n% Note: we use a dense matrix in this example, but PhasePack also supports\n% function handles. See the more complex 'runImageReconstructionDemo.m'\n% script for an example using the fast Fourier transform.\nA = randn(m,n)+1i*randn(m,n);\n\n%% Compute phaseless measurements\nb = abs(A*x_true); \n\n%% Set options for PhasePack - this is where we choose the recovery algorithm\nopts = struct; % Create an empty struct to store options\nopts.algorithm = 'Fienup'; % Use the Fienup method to solve the retrieval problem. Try changing this to 'twf' for truncated Wirtinger flow.\nopts.initMethod = 'optimal'; % Use the optimal spectral initializer method to generate an initial starting point for the solver \nopts.tol = 1e-3; % The tolerance - make this smaller for more accurate solutions, or larger for faster runtimes\nopts.verbose = 2; % Print out lots of information as the solver runs (set this to 1 or 0 for less output)\n\n%% Run the Phase retrieval Algorithm\nfprintf('Running %s algorithm\\n',opts.algorithm);\n% Call the solver using the measurement operator 'A', the\n% measurements 'b', the length of the signal to be recovered, and the\n% options. Note, the measurement operator can be either a function handle\n% or a matrix. Here, we use a matrix. In this case, we have omitted the \n% second argument. If 'A' had been a function handle, we would have \n% handed the transpose of 'A' in as the second argument.\n[x, outs] = solvePhaseRetrieval(A, [], b, n, opts);\n% Note: 'outs' is a struct containing convergene information.\n\n%% Remove phase ambiguity\n% Phase retrieval can only recover images up to a phase ambiguity. \n% Let's apply a phase rotation to align the recovered signal with the \n% original so they look the same when we plot them.\nrotation = sign(x'*x_true(:));\nx = x*rotation;\n\n% Print some useful info to the console\nfprintf('Signal recovery required %d iterations (%f secs)\\n',outs.iterationCount, outs.solveTimes(end));\n\n\n%% Plot results\nfigure;\n% Plot the true vs recovered signal. Ideally, this scatter plot should be\n% clustered around the 45-degree line.\nsubplot(1,2,1);\nscatter(real(x_true),real(x));\nxlabel('Original signal value');\nylabel('Recovered signal value');\ntitle('Original vs recovered signal');\n\n% Plot a convergence curve\nsubplot(1,3,3);\nconvergedCurve = semilogy(outs.solveTimes, outs.residuals);\nset(convergedCurve, 'linewidth',1.75);\ngrid on;\nxlabel('Time (sec)');\nylabel('Error');\ntitle('Convergence Curve');\nset(gcf,'units','points','position',[0,0,1200,300]);\n\n\nend", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/runSignalReconstructionDemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6394989540459788}} {"text": "classdef KalmanFilter < handle\n %KALMANFILTER Kalman filter class\n %\n % The class implements a standard\n % [Kalman filter](https://en.wikipedia.org/wiki/Kalman_filter), [Welch95].\n % However, you can modify `transitionMatrix`, `controlMatrix`, and\n % `measurementMatrix` to get an extended Kalman filter functionality.\n %\n % ## Example\n %\n % % initialization\n % kf = cv.KalmanFilter(4,2);\n % kf.statePre = [10;20;0;0]; % initial state prediction\n % kf.transitionMatrix = [1,0,1,0; 0,1,0,1; 0,0,1,0; 0,0,0,1];\n % kf.measurementMatrix([1,4]) = 1;\n % kf.processNoiseCov = eye(4) * 1e-4;\n % kf.measurementNoiseCov = eye(2) * 1e-1;\n % kf.errorCovPost = eye(4) * 0.1;\n %\n % % dynamics\n % p_pred = kf.predict(); % update internal state\n % measure = [11;21]; % measurement\n % p_est = kf.correct(measure); % correct\n %\n % ## References\n % [Welch95]:\n % > Greg Welch and Gary Bishop. An introduction to the kalman filter, 1995.\n % > [PDF](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf)\n %\n % See also: cv.KalmanFilter.init, cv.KalmanFilter.predict,\n % cv.KalmanFilter.correct, vision.KalmanFilter\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % predicted state `(x'(k)): x(k)=A*x(k-1)+B*u(k)`\n statePre\n % corrected state `(x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))`\n statePost\n % state transition matrix `(A)`\n transitionMatrix\n % control matrix `(B)` (not used if there is no control)\n controlMatrix\n % measurement matrix `(H)`\n measurementMatrix\n % process noise covariance matrix `(Q)`\n processNoiseCov\n % measurement noise covariance matrix `(R)`\n measurementNoiseCov\n % priori error estimate covariance matrix\n % `(P'(k)): P'(k)=A*P(k-1)*At + Q`\n errorCovPre\n % Kalman gain matrix `(K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R`)\n gain\n % posteriori error estimate covariance matrix\n % `(P(k)): P(k)=(I-K(k)*H)*P'(k)`\n errorCovPost\n end\n\n methods\n function this = KalmanFilter(varargin)\n %KALMANFILTER KalmanFilter constructor\n %\n % kf = cv.KalmanFilter()\n % kf = cv.KalmanFilter(dynamParams, measureParams)\n % kf = cv.KalmanFilter(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __dynamParams__ Dimensionality of the state.\n % * __measureParams__ Dimensionality of the measurement.\n %\n % ## Options\n % * __ControlParams__ Dimensionality of the control vector.\n % default 0\n % * __Type__ Type of the created matrices that should be `single`\n % or `double`. default `single`\n %\n % The constructor invokes the cv.KalmanFilter.init method to\n % initialize the object with the passed parameters.\n %\n % See also: cv.KalmanFilter, cv.KalmanFilter.init\n %\n this.id = KalmanFilter_(0, 'new');\n if nargin>0, this.init(varargin{:}); end\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % kf.delete()\n %\n % See also: cv.KalmanFilter\n %\n if isempty(this.id), return; end\n KalmanFilter_(this.id, 'delete');\n end\n\n function init(this, dynamParams, measureParams, varargin)\n %INIT Re-initializes Kalman filter. The previous content is destroyed\n %\n % kf.init(dynamParams, measureParams)\n % kf.init(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __dynamParams__ Dimensionality of the state.\n % * __measureParams__ Dimensionality of the measurement.\n %\n % ## Options\n % * __ControlParams__ Dimensionality of the control vector.\n % default 0\n % * __Type__ Type of the created matrices that should be `single`\n % or `double` (default).\n %\n % See also: cv.KalmanFilter.KalmanFilter\n %\n KalmanFilter_(this.id, 'init', dynamParams, measureParams, varargin{:});\n end\n\n function s = predict(this, varargin)\n %PREDICT Computes a predicted state\n %\n % s = kf.predict('OptionName', optionValue, ...)\n %\n % ## Output\n % * __s__ Output predicted state.\n %\n % ## Options\n % * __Control__ The optional input control. Not set by default\n %\n % See also: cv.KalmanFilter.correct\n %\n s = KalmanFilter_(this.id, 'predict', varargin{:});\n end\n\n function s = correct(this, measurement)\n %CORRECT Updates the predicted state from the measurement\n %\n % s = kf.correct(measurement)\n %\n % ## Input\n % * __measurement__ The measured system parameters.\n %\n % ## Output\n % * __s__ Output corrected state.\n %\n % See also: cv.KalmanFilter.predict\n %\n s = KalmanFilter_(this.id, 'correct', measurement);\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.statePre(this)\n value = KalmanFilter_(this.id, 'get', 'statePre');\n end\n function set.statePre(this, value)\n KalmanFilter_(this.id, 'set', 'statePre', value);\n end\n\n function value = get.statePost(this)\n value = KalmanFilter_(this.id, 'get', 'statePost');\n end\n function set.statePost(this, value)\n KalmanFilter_(this.id, 'set', 'statePost', value);\n end\n\n function value = get.transitionMatrix(this)\n value = KalmanFilter_(this.id, 'get', 'transitionMatrix');\n end\n function set.transitionMatrix(this, value)\n KalmanFilter_(this.id, 'set', 'transitionMatrix', value);\n end\n\n function value = get.controlMatrix(this)\n value = KalmanFilter_(this.id, 'get', 'controlMatrix');\n end\n function set.controlMatrix(this, value)\n KalmanFilter_(this.id, 'set', 'controlMatrix', value);\n end\n\n function value = get.measurementMatrix(this)\n value = KalmanFilter_(this.id, 'get', 'measurementMatrix');\n end\n function set.measurementMatrix(this, value)\n KalmanFilter_(this.id, 'set', 'measurementMatrix', value);\n end\n\n function value = get.processNoiseCov(this)\n value = KalmanFilter_(this.id, 'get', 'processNoiseCov');\n end\n function set.processNoiseCov(this, value)\n KalmanFilter_(this.id, 'set', 'processNoiseCov', value);\n end\n\n function value = get.measurementNoiseCov(this)\n value = KalmanFilter_(this.id, 'get', 'measurementNoiseCov');\n end\n function set.measurementNoiseCov(this, value)\n KalmanFilter_(this.id, 'set', 'measurementNoiseCov', value);\n end\n\n function value = get.errorCovPre(this)\n value = KalmanFilter_(this.id, 'get', 'errorCovPre');\n end\n function set.errorCovPre(this, value)\n KalmanFilter_(this.id, 'set', 'errorCovPre', value);\n end\n\n function value = get.gain(this)\n value = KalmanFilter_(this.id, 'get', 'gain');\n end\n function set.gain(this, value)\n KalmanFilter_(this.id, 'set', 'gain', value);\n end\n\n function value = get.errorCovPost(this)\n value = KalmanFilter_(this.id, 'get', 'errorCovPost');\n end\n function set.errorCovPost(this, value)\n KalmanFilter_(this.id, 'set', 'errorCovPost', value);\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/KalmanFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6393674837971197}} {"text": "function I = sum3(f)\n%SUM3 Triple integral of a BALLFUN over its domain.\n% I = SUM3(F) returns the double definite integral of a BALLFUN.\n%\n% See also SUM, SUM2.\n\n% Copyright 2019 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 I = [];\n return\nend\n\n% Second argument: integral over the sphere of radius -1\n[m,n,p] = size(f);\nm = m+2; p = p+2;\nF = coeffs3(f,m,n,p);\n\n% Extract the 0-th Fourier mode\nF = reshape(F(:,floor(n/2)+1,:), m, p);\n\n% Increase the discretization by 2 in the r and theta direction\nF = [zeros(m,1),F,zeros(m,1);zeros(2,p+2)];\nm = m+2;\np = p+2;\n\n% Multiply f par r^2sin(theta) (= Jacobian)\nMsin = trigspec.multmat(p, [0.5i;0;-0.5i] );\nMr2 = ultraS.multmat(m, [0.5; 0; 0.5], 0 );\nF = Mr2*F*(Msin.');\n\n% Coefficients of integration between 0 and 1 of the chebyshev polynomials\nIntChebyshev = zeros(1,m);\nfor i = 0:m-1\n if mod(i,4)==0\n IntChebyshev(i+1) = -1/(i^2-1);\n elseif mod(i,4)==1\n IntChebyshev(i+1) = 1/(i+1);\n elseif mod(i,4)==2\n IntChebyshev(i+1) = -1/(i^2-1);\n else\n IntChebyshev(i+1) = -1/(i-1);\n end\nend\n\n% Coefficients of integration between 0 and pi of the theta Fourier\n% function\nListp = (1:p).' - floor(p/2)-1;\nIntTheta = -1i*((-1).^Listp-1)./Listp;\nIntTheta(floor(p/2)+1) = pi;\n\n% Integrate over lambda\nIntTheta = 2*pi*IntTheta;\n\n% Integrate over the sphere of radius -1\nif nargin>1\n IntChebyshev = (-1).^(0:m-1).*IntChebyshev;\nend\n\n% Return the integral of f over the ballfun\nI = IntChebyshev*F*IntTheta;\n\n% Return real value if the function is real\nif f.isReal\n I = real(I); \nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/sum3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6392370268432342}} {"text": "% Using 2D or 3D affine matrix to rotate, translate, scale, reflect and\n% shear a 2D image or 3D volume. 2D image is represented by a 2D matrix,\n% 3D volume is represented by a 3D matrix, and data type can be real \n% integer or floating-point.\n%\n% You may notice that MATLAB has a function called 'imtransform.m' for\n% 2D spatial transformation. However, keep in mind that 'imtransform.m'\n% assumes y for the 1st dimension, and x for the 2nd dimension. They are\n% equivalent otherwise.\n%\n% In addition, if you adjust the 'new_elem_size' parameter, this 'affine.m'\n% is equivalent to 'interp2.m' for 2D image, and equivalent to 'interp3.m'\n% for 3D volume.\n%\n% Usage: [new_img new_M] = ...\n%\taffine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);\n%\n% old_img -\toriginal 2D image or 3D volume. We assume x for the 1st\n%\t\tdimension, y for the 2nd dimension, and z for the 3rd\n%\t\tdimension.\n%\n% old_M -\ta 3x3 2D affine matrix for 2D image, or a 4x4 3D affine\n%\t\tmatrix for 3D volume. We assume x for the 1st dimension,\n%\t\ty for the 2nd dimension, and z for the 3rd dimension.\n%\n% new_elem_size (optional) - size of voxel along x y z direction for \n%\t\ta transformed 3D volume, or size of pixel along x y for\n%\t\ta transformed 2D image. We assume x for the 1st dimension\n%\t\ty for the 2nd dimension, and z for the 3rd dimension.\n%\t\t'new_elem_size' is 1 if it is default or empty.\n%\n%\t\tYou can increase its value to decrease the resampling rate,\n%\t\tand make the 2D image or 3D volume more coarse. It works\n%\t\tjust like 'interp3'.\n%\n% verbose (optional) - 1, 0\n%\t\t1: show transforming progress in percentage\n%\t\t2: progress will not be displayed\n%\t\t'verbose' is 1 if it is default or empty.\n%\n% bg (optional) -\tbackground voxel intensity in any extra corner that\n%\t\tis caused by the interpolation. 0 in most cases. If it is\n%\t\tdefault or empty, 'bg' will be the average of two corner\n%\t\tvoxel intensities in original data.\n%\n% method (optional) -\t1, 2, or 3\n%\t\t1: for Trilinear interpolation\n%\t\t2: for Nearest Neighbor interpolation\n%\t\t3: for Fischer's Bresenham interpolation\n%\t\t'method' is 1 if it is default or empty.\n%\n% new_img -\ttransformed 2D image or 3D volume\n%\n% new_M -\ttransformed affine matrix\n%\n% Example 1 (3D rotation):\n%\tload mri.mat; old_img = double(squeeze(D));\n%\told_M = [0.88 0.5 3 -90; -0.5 0.88 3 -126; 0 0 2 -72; 0 0 0 1];\n%\tnew_img = affine(old_img, old_M, 2);\n%\t[x y z] = meshgrid(1:128,1:128,1:27);\n%\tsz = size(new_img);\n%\t[x1 y1 z1] = meshgrid(1:sz(2),1:sz(1),1:sz(3));\n%\tfigure; slice(x, y, z, old_img, 64, 64, 13.5);\n%\tshading flat; colormap(map); view(-66, 66);\n%\tfigure; slice(x1, y1, z1, new_img, sz(1)/2, sz(2)/2, sz(3)/2);\n%\tshading flat; colormap(map); view(-66, 66);\n%\n% Example 2 (2D interpolation):\n%\tload mri.mat; old_img=D(:,:,1,13)';\n%\told_M = [1 0 0; 0 1 0; 0 0 1];\n%\tnew_img = affine(old_img, old_M, [.2 .4]);\n%\tfigure; image(old_img); colormap(map);\n%\tfigure; image(new_img); colormap(map);\n%\n% This program is inspired by:\n% SPM5 Software from Wellcome Trust Centre for Neuroimaging\n%\thttp://www.fil.ion.ucl.ac.uk/spm/software\n% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid\n%\tTransformations to Volume Data, WSCG2004 Conference.\n%\thttp://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf\n% \n% - Jimmy Shen (jimmy@rotman-baycrest.on.ca)\n%\nfunction [new_img, new_M] = affine(old_img, old_M, new_elem_size, verbose, bg, method)\n\n if ~exist('old_img','var') | ~exist('old_M','var')\n error('Usage: [new_img new_M] = affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);');\n end\n\n if ndims(old_img) == 3\n if ~isequal(size(old_M),[4 4])\n error('old_M should be a 4x4 affine matrix for 3D volume.');\n end\n elseif ndims(old_img) == 2\n if ~isequal(size(old_M),[3 3])\n error('old_M should be a 3x3 affine matrix for 2D image.');\n end\n else\n error('old_img should be either 2D image or 3D volume.');\n end\n\n if ~exist('new_elem_size','var') | isempty(new_elem_size)\n new_elem_size = [1 1 1];\n elseif length(new_elem_size) < 2\n new_elem_size = new_elem_size(1)*ones(1,3);\n elseif length(new_elem_size) < 3\n new_elem_size = [new_elem_size(:); 1]';\n end\n\n if ~exist('method','var') | isempty(method)\n method = 1;\n elseif ~exist('bresenham_line3d.m','file') & method == 3\n error([char(10) char(10) 'Please download 3D Bresenham''s line generation program from:' char(10) char(10) 'http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21057' char(10) char(10) 'to test Fischer''s Bresenham interpolation method.' char(10) char(10)]);\n end\n\n % Make compatible to MATLAB earlier than version 7 (R14), which\n % can only perform arithmetic on double data type\n %\n old_img = double(old_img);\n old_dim = size(old_img);\n\n if ~exist('bg','var') | isempty(bg)\n bg = mean([old_img(1) old_img(end)]);\n end\n\n if ~exist('verbose','var') | isempty(verbose)\n verbose = 1;\n end\n\n if ndims(old_img) == 2\n old_dim(3) = 1;\n old_M = old_M(:, [1 2 3 3]);\n old_M = old_M([1 2 3 3], :);\n old_M(3,:) = [0 0 1 0];\n old_M(:,3) = [0 0 1 0]';\n end\n\n % Vertices of img in voxel\n %\n XYZvox = [\t1\t\t1\t\t1\n\t\t1\t\t1\t\told_dim(3)\n\t\t1\t\told_dim(2)\t1\n\t\t1\t\told_dim(2)\told_dim(3)\n\t\told_dim(1)\t1\t\t1\n\t\told_dim(1)\t1\t\told_dim(3)\n\t\told_dim(1)\told_dim(2)\t1\n\t\told_dim(1)\told_dim(2)\told_dim(3) ]';\n\n old_R = old_M(1:3,1:3);\n old_T = old_M(1:3,4);\n\n % Vertices of img in millimeter\n %\n XYZmm = old_R*(XYZvox-1) + repmat(old_T, [1, 8]);\n\n % Make scale of new_M according to new_elem_size\n %\n new_M = diag([new_elem_size 1]);\n\n % Make translation so minimum vertex is moved to [1,1,1]\n %\n new_M(1:3,4) = round( min(XYZmm,[],2) );\n\n % New dimensions will be the maximum vertices in XYZ direction (dim_vox)\n % i.e. compute dim_vox via dim_mm = R*(dim_vox-1)+T\n % where, dim_mm = round(max(XYZmm,[],2));\n %\n new_dim = ceil(new_M(1:3,1:3) \\ ( round(max(XYZmm,[],2))-new_M(1:3,4) )+1)';\n\n % Initialize new_img with new_dim\n %\n new_img = zeros(new_dim(1:3));\n\n % Mask out any changes from Z axis of transformed volume, since we\n % will traverse it voxel by voxel below. We will only apply unit\n % increment of mask_Z(3,4) to simulate the cursor movement\n %\n % i.e. we will use mask_Z * new_XYZvox to replace new_XYZvox\n %\n mask_Z = diag(ones(1,4));\n mask_Z(3,3) = 0;\n\n % It will be easier to do the interpolation if we invert the process\n % by not traversing the original volume. Instead, we traverse the\n % transformed volume, and backproject each voxel in the transformed \n % volume back into the original volume. If the backprojected voxel\n % in original volume is within its boundary, the intensity of that\n % voxel can be used by the cursor location in the transformed volume.\n %\n % First, we traverse along Z axis of transformed volume voxel by voxel\n %\n for z = 1:new_dim(3)\n\n if verbose & ~mod(z,10)\n fprintf('%.2f percent is done.\\n', 100*z/new_dim(3));\n end\n\n % We need to find out the mapping from voxel in the transformed\n % volume (new_XYZvox) to voxel in the original volume (old_XYZvox)\n %\n % The following equation works, because they all equal to XYZmm:\n % new_R*(new_XYZvox-1) + new_T == old_R*(old_XYZvox-1) + old_T\n %\n % We can use modified new_M1 & old_M1 to substitute new_M & old_M\n % new_M1 * new_XYZvox == old_M1 * old_XYZvox\n %\n % where: M1 = M; M1(:,4) = M(:,4) - sum(M(:,1:3),2);\n % and: M(:,4) == [T; 1] == sum(M1,2)\n %\n % Therefore: old_XYZvox = old_M1 \\ new_M1 * new_XYZvox;\n %\n % Since we are traverse Z axis, and new_XYZvox is replaced\n % by mask_Z * new_XYZvox, the above formula can be rewritten\n % as: old_XYZvox = old_M1 \\ new_M1 * mask_Z * new_XYZvox;\n %\n % i.e. we find the mapping from new_XYZvox to old_XYZvox:\n % M = old_M1 \\ new_M1 * mask_Z;\n %\n % First, compute modified old_M1 & new_M1\n %\n old_M1 = old_M; old_M1(:,4) = old_M(:,4) - sum(old_M(:,1:3),2);\n new_M1 = new_M; new_M1(:,4) = new_M(:,4) - sum(new_M(:,1:3),2);\n\n % Then, apply unit increment of mask_Z(3,4) to simulate the\n % cursor movement\n %\n mask_Z(3,4) = z;\n\n % Here is the mapping from new_XYZvox to old_XYZvox\n %\n M = old_M1 \\ new_M1 * mask_Z;\n\n switch method\n case 1\n new_img(:,:,z) = trilinear(old_img, new_dim, old_dim, M, bg);\n case 2\n new_img(:,:,z) = nearest_neighbor(old_img, new_dim, old_dim, M, bg);\n case 3\n new_img(:,:,z) = bresenham(old_img, new_dim, old_dim, M, bg);\n end\n\n end;\t\t\t% for z\n\n if ndims(old_img) == 2\n new_M(3,:) = [];\n new_M(:,3) = [];\n end\n\n return;\t\t\t\t\t% affine\n\n\n%--------------------------------------------------------------------\nfunction img_slice = trilinear(img, dim1, dim2, M, bg)\n\n img_slice = zeros(dim1(1:2));\n TINY = 5e-2;\t\t\t\t\t% tolerance\n\n % Dimension of transformed 3D volume\n %\n xdim1 = dim1(1);\n ydim1 = dim1(2);\n\n % Dimension of original 3D volume\n %\n xdim2 = dim2(1);\n ydim2 = dim2(2);\n zdim2 = dim2(3);\n\n % initialize new_Y accumulation\n %\n Y2X = 0;\n Y2Y = 0;\n Y2Z = 0;\n\n for y = 1:ydim1\n\n % increment of new_Y accumulation\n %\n Y2X = Y2X + M(1,2);\t\t% new_Y to old_X\n Y2Y = Y2Y + M(2,2);\t\t% new_Y to old_Y\n Y2Z = Y2Z + M(3,2);\t\t% new_Y to old_Z\n\n % backproject new_Y accumulation and translation to old_XYZ\n %\n old_X = Y2X + M(1,4);\n old_Y = Y2Y + M(2,4);\n old_Z = Y2Z + M(3,4);\n\n for x = 1:xdim1\n\n % accumulate the increment of new_X, and apply it\n % to the backprojected old_XYZ\n %\n old_X = M(1,1) + old_X ;\n old_Y = M(2,1) + old_Y ;\n old_Z = M(3,1) + old_Z ;\n\n % within boundary of original image\n %\n if (\told_X > 1-TINY & old_X < xdim2+TINY & ...\n\t\told_Y > 1-TINY & old_Y < ydim2+TINY & ...\n\t\told_Z > 1-TINY & old_Z < zdim2+TINY\t)\n\n % Calculate distance of old_XYZ to its neighbors for\n % weighted intensity average\n %\n dx = old_X - floor(old_X);\n dy = old_Y - floor(old_Y);\n dz = old_Z - floor(old_Z);\n\n x000 = floor(old_X);\n x100 = x000 + 1;\n\n if floor(old_X) < 1\n x000 = 1;\n x100 = x000;\n elseif floor(old_X) > xdim2-1\n x000 = xdim2;\n x100 = x000;\n end\n\n x010 = x000;\n x001 = x000;\n x011 = x000;\n\n x110 = x100;\n x101 = x100;\n x111 = x100;\n\n y000 = floor(old_Y);\n y010 = y000 + 1;\n\n if floor(old_Y) < 1\n y000 = 1;\n y100 = y000;\n elseif floor(old_Y) > ydim2-1\n y000 = ydim2;\n y010 = y000;\n end\n\n y100 = y000;\n y001 = y000;\n y101 = y000;\n\n y110 = y010;\n y011 = y010;\n y111 = y010;\n\n z000 = floor(old_Z);\n z001 = z000 + 1;\n\n if floor(old_Z) < 1\n z000 = 1;\n z001 = z000;\n elseif floor(old_Z) > zdim2-1\n z000 = zdim2;\n z001 = z000;\n end\n\n z100 = z000;\n z010 = z000;\n z110 = z000;\n\n z101 = z001;\n z011 = z001;\n z111 = z001;\n\n x010 = x000;\n x001 = x000;\n x011 = x000;\n\n x110 = x100;\n x101 = x100;\n x111 = x100;\n\n v000 = double(img(x000, y000, z000));\n v010 = double(img(x010, y010, z010));\n v001 = double(img(x001, y001, z001));\n v011 = double(img(x011, y011, z011));\n\n v100 = double(img(x100, y100, z100));\n v110 = double(img(x110, y110, z110));\n v101 = double(img(x101, y101, z101));\n v111 = double(img(x111, y111, z111));\n\n img_slice(x,y) = v000*(1-dx)*(1-dy)*(1-dz) + ...\n v010*(1-dx)*dy*(1-dz) + ...\n v001*(1-dx)*(1-dy)*dz + ...\n v011*(1-dx)*dy*dz + ...\n v100*dx*(1-dy)*(1-dz) + ...\n v110*dx*dy*(1-dz) + ...\n v101*dx*(1-dy)*dz + ...\n v111*dx*dy*dz;\n\n else\n img_slice(x,y) = bg;\n\n end\t% if boundary\n\n end\t% for x\n end\t\t% for y\n\n return;\t\t\t\t\t% trilinear\n\n\n%--------------------------------------------------------------------\nfunction img_slice = nearest_neighbor(img, dim1, dim2, M, bg)\n\n img_slice = zeros(dim1(1:2));\n\n % Dimension of transformed 3D volume\n %\n xdim1 = dim1(1);\n ydim1 = dim1(2);\n\n % Dimension of original 3D volume\n %\n xdim2 = dim2(1);\n ydim2 = dim2(2);\n zdim2 = dim2(3);\n\n % initialize new_Y accumulation\n %\n Y2X = 0;\n Y2Y = 0;\n Y2Z = 0;\n\n for y = 1:ydim1\n\n % increment of new_Y accumulation\n %\n Y2X = Y2X + M(1,2);\t\t% new_Y to old_X\n Y2Y = Y2Y + M(2,2);\t\t% new_Y to old_Y\n Y2Z = Y2Z + M(3,2);\t\t% new_Y to old_Z\n\n % backproject new_Y accumulation and translation to old_XYZ\n %\n old_X = Y2X + M(1,4);\n old_Y = Y2Y + M(2,4);\n old_Z = Y2Z + M(3,4);\n\n for x = 1:xdim1\n\n % accumulate the increment of new_X and apply it\n % to the backprojected old_XYZ\n %\n old_X = M(1,1) + old_X ;\n old_Y = M(2,1) + old_Y ;\n old_Z = M(3,1) + old_Z ;\n\n xi = round(old_X);\n yi = round(old_Y);\n zi = round(old_Z);\n\n % within boundary of original image\n %\n if (\txi >= 1 & xi <= xdim2 & ...\n\t\tyi >= 1 & yi <= ydim2 & ...\n\t\tzi >= 1 & zi <= zdim2\t)\n\n img_slice(x,y) = img(xi,yi,zi);\n\n else\n img_slice(x,y) = bg;\n\n end\t% if boundary\n\n end\t% for x\n end\t\t% for y\n\n return;\t\t\t\t\t% nearest_neighbor\n\n\n%--------------------------------------------------------------------\nfunction img_slice = bresenham(img, dim1, dim2, M, bg)\n\n img_slice = zeros(dim1(1:2));\n\n % Dimension of transformed 3D volume\n %\n xdim1 = dim1(1);\n ydim1 = dim1(2);\n\n % Dimension of original 3D volume\n %\n xdim2 = dim2(1);\n ydim2 = dim2(2);\n zdim2 = dim2(3);\n\n for y = 1:ydim1\n\n start_old_XYZ = round(M*[0 y 0 1]');\n end_old_XYZ = round(M*[xdim1 y 0 1]');\n\n [X Y Z] = bresenham_line3d(start_old_XYZ, end_old_XYZ);\n\n % line error correction\n %\n% del = end_old_XYZ - start_old_XYZ;\n % del_dom = max(del);\n % idx_dom = find(del==del_dom);\n % idx_dom = idx_dom(1);\n % idx_other = [1 2 3];\n % idx_other(idx_dom) = [];\n %del_x1 = del(idx_other(1));\n% del_x2 = del(idx_other(2));\n % line_slope = sqrt((del_x1/del_dom)^2 + (del_x2/del_dom)^2 + 1);\n % line_error = line_slope - 1;\n% line error correction removed because it is too slow\n\n for x = 1:xdim1\n\n % rescale ratio\n %\n i = round(x * length(X) / xdim1);\n\n if i < 1\n i = 1;\n elseif i > length(X)\n i = length(X);\n end\n\n xi = X(i);\n yi = Y(i);\n zi = Z(i);\n\n % within boundary of the old XYZ space\n %\n if (\txi >= 1 & xi <= xdim2 & ...\n\t\tyi >= 1 & yi <= ydim2 & ...\n\t\tzi >= 1 & zi <= zdim2\t)\n\n img_slice(x,y) = img(xi,yi,zi);\n\n% if line_error > 1\n % x = x + 1;\n\n% if x <= xdim1\n % img_slice(x,y) = img(xi,yi,zi);\n % line_error = line_slope - 1;\n % end\n % end\t\t% if line_error\n% line error correction removed because it is too slow\n\n else\n img_slice(x,y) = bg;\n\n end\t% if boundary\n\n end\t% for x\n end\t\t% for y\n\n return;\t\t\t\t\t% bresenham\n\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/niftiToolbox/affine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6392156878875145}} {"text": "function [P_MPP,U_MPP,I_MPP,U_OC_New,I_SC_New,U_PV,I_PV,P_PV] = PV_Module_Simulator_Function(G,T_amb)\n%------ Solar Module simulation according to DIN EN 50530:2010 ------------\n% This function can be used to simulate an solar cell to a PV-field by\n% entering the number of modules (cells) in parallel and the number of\n% module in serise. \n% The equations used in this function are taken from the DIN EN 50530:2010\n% norm.\n% This function need two inputs:\n% 1- G: The new solar irradiation at which the new working points\n% (U_MPP,P_MPP,...) will be calculated.\n% 2- T_amb: The new ambiant temperature at which the new working points\n% (U_MPP,P_MPP,...) will be calculated.\n% This function outputs are:\n% 1- P_MPP,U_MPP,I_MPP: are the power, voltage, current at the maximum\n% power point at the new conditions respectivily\n% 2- U_OC_New,I_SC_New: are the open circuit voltage and the short circuit\n% current respectivily calculated for the new weather(input) conditions.\n% 3- U_PV,I_PV,P_PV: are the new characteristic curves values for the\n% studied input condition.\n% This function will also ask the user for addtional informations which\n% need to be given in order to be able to simulate the characteristics of\n% the selected PV-mdouel.\n% Those information cal be obtained from the datasheet of the selected PV\n% modules. if not given use the default values already given.\n%Author: Aubai Alkhatib, date: 25.09.2013\n\nprompt1 = {'Please Enter The STC Temperatur in C','Please Enter The STC Open Voltage in V','Please Enter The STC Short circut Current in A','Please Enter The Voltage temperatur coefficient Beta in %/C','Please Enter The Curent temperatur coefficient Alpha in %/C ','Please Enter The STC Irradiantion in W/m2','Please Eneter The Voltage of the MPP in V','Please Eneter The Current of the MPP in A','Please Eneter The Technology correction factor CG in W/m2','Please Eneter The Technology correction factor CU in pu','Please Eneter The Technology correction factor CR in m2/W','Please Eneter The number of PV-Modules in Parallel P','Please Eneter The number of PV-Modules in Seris R','Please Enter The Open circut Voltage of the LS'};\nname = 'Initial Input data';\nnumlines = 1;\n%defaultanswer1 = {'25','36.7','8.18','-0.32','0.04','1000','29.9','7.53','2.514','8.593','1.088','22','384','1200','Oldenburg,Germany','20130701','X:\\Loc_4631\\2013\\07'};\ndefaultanswer1 = {'25','36.7','8.18','-0.32','0.04','1000','29.9','7.53','2.514','8.593','1.088','22','450','1600'};\n%defaultanswer1 = {'4','1700','105','20','400','50','1'};\nanswer1 = inputdlg(prompt1,name,numlines,defaultanswer1);\nT_STC = str2num(answer1{1})+273;\nUoc_STC = str2num(answer1{2});\nIsc_STC = str2num(answer1{3});\nV_T_C = str2num(answer1{4})/100;\nI_T_C = str2num(answer1{5})/100;\nE0 = str2num(answer1{6});\nUmpp_STC = str2num(answer1{7});\nImpp_STC = str2num(answer1{8});\nCG = str2num(answer1{9})/1000;\nCU = str2num(answer1{10})/100;\nCR = str2num(answer1{11})/10000;\nR = str2num(answer1{12});\nP = str2num(answer1{13});\nTs = str2num(answer1{14});%#ok<*ST2NM>\nG_STC = E0;\nUoc_STC = Uoc_STC * R;\nIsc_STC = Isc_STC * P;\nUmpp_STC = Umpp_STC * R;\nImpp_STC = Impp_STC * P;\nif 0 == 1\n T_0 = -3;\n k = 0.03;%km^2/w\n Tau = 5;% in min\n T_PV = T_amb + T_0 + ((k*1000000)/(1+(Tau*60)))*G;\nelse\n T_NOCT = 45;\n T_PV = T_amb + ((T_NOCT-20) * (G/800));\nend\nAlpha = I_T_C;\nIsc_New = (Isc_STC*(G/G_STC)) * (1 + (Alpha * (T_PV - T_STC)));\nBeta = V_T_C;\nUoc_New = Uoc_STC*(1+Beta*(T_PV-T_STC))*(log((G/CG)+1)*CU-CR*G);\nFF_U = Umpp_STC/Uoc_STC;\nFF_I = Impp_STC/Isc_STC;\nI_0 = (Isc_STC*(1-FF_I)^(1/(1-FF_U)))*(G/G_STC);\nCAQ = (FF_U-1)/(log(1-FF_I));\nU_PV = 0:1:Ts;\nI_PV = Isc_New - I_0*(exp(U_PV/(Uoc_New*CAQ))-1);\nP_PV = U_PV.*I_PV;\nP_MPP = max(P_PV);\nU_MPP = U_PV(P_PV == P_MPP);\nI_MPP = I_PV(U_MPP);\nindx = find(I_PV < 0);\nU_OC_New = U_PV(indx(1));\nI_SC_New = I_PV(1);\nfigure(1);\nsubplot(2,1,1);\nplot(U_PV,I_PV);xlabel('DC-Voltage in V');ylabel('DC-Current in A');title('PV-Module Charactaristic curves');grid on;ylim([0,I_MPP+((20/100)*I_MPP)]);xlim([0,U_OC_New+10]);\nsubplot (2,1,2);\nplot(U_PV,P_PV);xlabel('DC-Voltage in V');ylabel('DC-Power in W');grid on;ylim([0,P_MPP+((5/100)*P_MPP)]);xlim([0,U_OC_New+10]);\nend\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/43625-pv-module-calculater/m.file/PV_Module_Simulator_Function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6391984960975873}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n% \n% \n% \n\n% problem 7 - convolution of x[n] and h[n]\n\nn=0:10;\nu=ones(size(n));\nn1=0:3;\nu4_1=zeros(size(n1));\nn2=4:10;\nu4_2=ones(size(n2));\nu4=[u4_1 u4_2];\nx=u-u4;\nh=0.7.^n;\ny=conv(x,h);\nstem(0:20,y);\nxlim([-1 21]);\nlegend('y[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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/4/c412g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6391890181356884}} {"text": "function f = projectOntoBMCII(f)\n%PROJECTONTOBMCII Projection onto BMC-II symmetry.\n% F = projectOntoBMCII(F) is the orthogonal projection of f onto BMC-II \n% symmetry, i.e., a function that is\n% 1. even in r for every even wave number in theta.\n% 2. odd in r for every odd wave number in theta.\n% Additionally, for all but the k=0 mode in theta, the resulting \n% projection enforces the diskfun is zero at the origin.\n%\n% The projection is orthogonal, i.e., the correction matrix to fix up the\n% structure has the smallest possible Frobenius norm.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Even part\nfeven = f;\nfeven.cols = feven.cols(:, feven.idxPlus);\nfeven.rows = feven.rows(:, feven.idxPlus);\nfeven = projectOntoEvenBMCII(feven);\n\n% Odd part\nfodd = f;\nfodd.cols = fodd.cols(:, fodd.idxMinus);\nfodd.rows = fodd.rows(:, fodd.idxMinus);\nfodd = projectOntoOddBMCII(fodd);\n\n% Put pieces back together.\nf.cols(:, f.idxPlus) = feven.cols;\nf.rows(:, f.idxPlus) = feven.rows;\n\nf.cols(:, f.idxMinus) = fodd.cols;\nf.rows(:, f.idxMinus) = fodd.rows;\n\nend\n\nfunction f = projectOntoEvenBMCII(f)\n% Project a diskfun to have even BMC-II symmetry, i.e., a diskfun that\n% is pi-periodic in theta and even in r. The projection is orthogonal,\n% i.e., the correction matrix to fix up the structure has the smallest\n% possible Frobenius norm.\n\n% Nothing to project\nif isempty(f)\n return;\nend\n\n% Operate on the column coefficients first.\nX = f.cols.funs{1}.onefun.coeffs;\n\n% Get size: \n[m, n] = size(X); \n\n % First we enforce that the every function in r is even: \n X(2:2:end, :) = 0; \n \n% The rest of the code now needs to operate on the remaining even,\n% non-zero modes in theta.\nevenModes = 2:n;\n \n\nif ( ~isempty(evenModes) )\n % to enforce that f(r) = 0 for each column function, \n % we want C with smallest 2-norm such that A*(X(1:2:end, 2:end)+C) = 0, \n % where A =[1 -1 1 -1..] . \n % The solution is \n % C = A'*((A*A')\\(A*X)). \n %odd modes in r are zero, they won't contribute.\n even = 1:2:m;\n Xe = X(even, evenModes); \n factor = 1/length(even)*(sum(Xe(1:2:end, :),1)-sum(Xe(2:2:end, :),1));\n C = ((-1*ones(length(even), 1)).^((2:length(even)+1)'))*factor; \n %now add C to X\n X(even, evenModes) = Xe+C; \n \nend\n\nctechs = chebtech2({'',X}); \nf.cols.funs{1}.onefun = ctechs;\n\n% Now operate on the rows. The coefficients for the rows of an even BMC-II\n% function should only contain even wave numbers. The projection is to\n% simply zero out the odd wave numbers.\nX = f.rows.funs{1}.onefun.coeffs;\nn = size(X, 1);\nzeroMode = floor(n/2) + 1;\noddModes = [fliplr(zeroMode-1:-2:1) zeroMode+1:2:n];\nX(oddModes, :) = 0;\nrtechs = real(trigtech({'', X}));\nf.rows.funs{1}.onefun = rtechs;\n\n% Weird feval behavior in chebfun requires this\nf.cols.pointValues = feval(ctechs, [-1; 1]);\nf.rows.pointValues = feval(rtechs, [-1; 1]); \n\nend\n\nfunction f = projectOntoOddBMCII(f)\n% Project a diskfun to have odd BMC-II symmetry, i.e., a diskfun that is\n% pi-anti-periodic in theta and even in r. The projection is orthogonal, \n% i.e., the correction matrix to fix up the structure has the smallest \n% possible Frobenius norm.\n\n% Nothing to project\nif isempty(f)\n return;\nend\n\n% to enforce odd, simply zero out even coeffs: \n\n% Operate on the column coefficients first to project them onto odd\n% functions.\nX = f.cols.funs{1}.onefun.coeffs;\nX(1:2:end, :) = 0; \n\nctechs = chebtech2({'',X}); \nf.cols.funs{1}.onefun = ctechs;\n\n% Now operate on the rows. The coefficients for the rows of an odd BMC-II\n% function should only contain odd wave numbers. The projection is to\n% simply zero out the even wave numbers.\nX = f.rows.funs{1}.onefun.coeffs;\nn = size(X, 1); \nzeroMode = floor(n/2) + 1;\nevenModes = [fliplr(zeroMode-2:-2:1) zeroMode:2:n];\nX(evenModes, :) = 0;\n\nrtechs = real(trigtech({'', X}));\nf.rows.funs{1}.onefun = rtechs;\n\n% Weird feval behavior in chebfun requires this\nf.cols.pointValues = feval(ctechs, [-1; 1]);\nf.rows.pointValues = feval(rtechs, [-1; 1]); \n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@diskfun/projectOntoBMCII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736771, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6391424926945196}} {"text": "function G = divgrad(M,options)\n\n% divgrad - compute either gradient or divergence.\n%\n% G = divgrad(M);\n%\n% if M is a 2D array, compute gradient, \n% if M is a 3D array, compute divergence.\n% Use centered finite differences.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nif size(M,3)==2\n G = mydiv(M,options);\nelse\n G = mygrad(M,options);\nend\n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction d = mydiv(g,options)\n\nbound = getoptions(options, 'bound', 'sym');\n\nn = size(g,1);\nd = zeros(n);\n\nif strcmp(bound,'sym')\n d(2:end-1,:) = d(2:end-1,:) + ( g(3:end,:,1)-g(1:end-2,:,1) )/2;\n d(1,:) = d(1,:) + g(2,:,1)-g(1,:,1);\n d(end,:) = d(end,:) + g(end,:,1)-g(end-1,:,1);\n\n d(:,2:end-1) = d(:,2:end-1) + ( g(:,3:end,2)-g(:,1:end-2,2) )/2;\n d(:,1) = d(:,1) + g(:,2,2)-g(:,1,2);\n d(:,end) = d(:,end) + g(:,end,2)-g(:,end-1,2);\nelse\n sel1 = [2:n 1];\n sel2 = [n 1:n-1];\n d = g(sel1,:,1)-g(sel2,:,1) + g(:,sel1,2)-g(:,sel2,2);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction g = mygrad(M,options)\n\nbound = getoptions(options, 'bound', 'sym');\n\nn = size(M,1);\ng = zeros(n,n,2);\n\nif strcmp(bound,'sym')\n % on x\n g(2:end-1,:,1) = ( M(3:end,:)-M(1:end-2,:) )/2;\n g(1,:,1) = M(2,:)-M(1,:);\n g(end,:,1) = M(end,:)-M(end-1,:);\n % on y\n g(:,2:end-1,2) = ( M(:,3:end)-M(:,1:end-2,:) )/2;\n g(:,1,1) = M(2,:)-M(1,:);\n g(:,end,1) = M(:,end)-M(:,end-1);\nelse\n sel1 = [2:n 1];\n sel2 = [n 1:n-1];\n g = cat( 3, M(sel1,:)-M(sel2,:), M(:,sel1)-M(:,sel2) )/2;\nend", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/toolbox_fast_marching/divgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6391424877467202}} {"text": "function J = jacobian( F )\n%JACOBIAN Jacobian determinant of a CHEBFUN2V.\n% J = JACOBIAN(F) computes the determinant of the Jacobian matrix associated\n% to the vector-valued CHEBFUN2V F. The CHEBFUN2V must have two components.\n%\n% Note we return the determinant of the Jacobian matrix and not the Jacobian\n% matrix itself.\n%\n% See also CHEBFUN2/GRADIENT. \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 J = []; \n return \nend\n\nif ( F.nComponents == 3 )\n error('CHEBFUN:CHEBFUN2V:jacobian:notSquare', ...\n 'Jacobian matrix is not square.')\nend\n\n% Determinant formula: \nFx = diff( F, 1, 2 ); \nFy = diff( F, 1, 1 ); \n\n% Jacobian: \nFxc = Fx.components; \nFyc = Fy.components;\nJ = Fxc{1} .* Fyc{2} - Fyc{1} .* Fxc{2}; \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/@chebfun2v/jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6391424825637452}} {"text": "function n=im3Dnorm(img,normind,varargin)\n% IMAGE3DNORM computes the desired image norm\n% IMAGE3DNORM(IMG,NORMIND) computes the norm if image IMG using the norm\n% defined in NORMING\n%\n% IMG A 3D image\n% NORMIND 'LN': N norm\n% 'TV': TV norm\n% \n% \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri\n%--------------------------------------------------------------------------\nif ~ischar(normind)\n error('CBCT:image3Dnorm:InvalidInput','Norm option has to be a string');\nend\nif length(normind)~=2\n error('CBCT:image3Dnorm:InvalidInput','Unknown norm option');\nend\n\nif strcmp(normind(1),'L')\n Nnorm=str2double(normind(2:end));\n n=norm(img(:),Nnorm);\n return;\nend\n\nif strcmp(normind,'TV')\n typeGrad=varargin{1};\n if strcmpi(typeGrad,'central')\n [gx,gy,gz]=gradient(img);\n end\n if strcmpi(typeGrad,'forward')\n gx=diff(img,1,1);\n gy=diff(img,1,2);\n gz=diff(img,1,3);\n gx=cat(1,gx,zeros(size(gx(end,:,:))));\n gy=cat(2,gy,zeros(size(gy(:,end,:))));\n gz=cat(3,gz,zeros(size(gz(:,:,end))));\n\n end\n if strcmpi(typeGrad,'backward')\n gx=diff(img,1,1);\n gy=diff(img,1,2);\n gz=diff(img,1,3);\n gx=cat(1,zeros(size(gx(1,:,:))),gx);\n gy=cat(2,zeros(size(gy(:,1,:))),gy);\n gz=cat(3,zeros(size(gz(:,:,1))),gz);\n end\n if ~exist('gx','var')\n error('CBCT:image3Dnorm:InvalidInput','Unknown gradient option for the TV norm');\n end\n g=sqrt(gx.^2+gy.^2+gz.^2); clear gx gy gz;\n n=sum(g(:));\n return;\nend\n\nerror('CBCT:image3Dnorm:InvalidInput','Unknown norm option');\nend", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Utilities/im3Dnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6391224600036114}} {"text": "function odf = calcKernelODF(ori,varargin)\n% calculate ODF from individuel orientations via kernel density estimation\n%\n% *calcKernelODF* is one of the core function of the MTEX toolbox.\n% It estimates an ODF from a set of individual crystal orientations by\n% .\n%\n% The function *calcKernelODF* has several options to control the halfwidth\n% of the kernel functions, the resolution, etc. Most important the\n% estimated ODF is affected by the *halfwidth* of the kernel function.\n%\n% If the halfwidth is large the estimated ODF is smooth whereas a small\n% halfwidth results in a sharp ODF. It depends on your prior information\n% about the ODF to choose this parameter right. Look at this\n% for an exhausive discussion.\n%\n% Syntax\n% odf = calcKernelODF(ori)\n% odf = calcKernelODF(grains.meanOrientation,'weigths',grains.area)\n% odf = calcKernelODF(ebsd.orientations,'halfwidth',5*degree)\n%\n% Input\n% ori - @orientation\n%\n% Output\n% odf - @SO3Fun\n%\n% Options\n% halfwidth - halfwidth of the kernel function\n% resolution - resolution of the grid where the ODF is approximated\n% kernel - kernel function (default -- de la Valee Poussin kernel)\n% weights - list of weights for the orientations\n%\n% Flags\n% exact - no approximation to a corser grid\n%\n% See also\n% ebsd_demo EBSD2odf EBSDSimulation_demo EBSD/load EBSD/calcKernel kernel/kernel\n\n\n\n% maybe there is nothing to do\nif isempty(ori), odf = ODF; return, end\n\n% extract weights\nif check_option(varargin,'weights')\n weights = get_option(varargin,'weights');\n varargin = delete_option(varargin,'weights',1);\nelse\n weights = ones(1,length(ori));\nend\n\n% remove nan orientations and weights\nweights = weights(~isnan(ori));\nori = subSet(ori,~isnan(ori));\n\n% normalize weights\nweights = weights ./ sum(weights(:));\n\n% extract kernel function\npsi = SO3DeLaValleePoussinKernel('halfwidth',10*degree,varargin{:});\npsi = get_option(varargin,'kernel',psi);\nhw = psi.halfwidth;\n\n% if we have to many orientation approximate them on a grid\nif length(ori) > 1000 && ~check_option(varargin,'exact')\n \n [ori,weights] = gridify(ori,'weights',weights,...\n 'resolution',max(0.75*degree,hw / 2), varargin{:});\n \nend\n\n% set up exact ODF\nodf = unimodalODF(ori,psi,ori.CS,ori.SS,'weights',weights);\n \nend\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@orientation/calcKernelODF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6391224500097432}} {"text": "function [E,J]=SynthMeasWatsonSHCylSingleRadGPD_PGSE(x, grad_dirs, G, delta, smalldel, fibredir, roots)\n% Substrate: Impermeable cylinders with one radius in a homogeneous background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Pulse sequence: Pulsed gradient spin echo\n% Signal approximation: Gaussian phase distribution.\n%\n% [E,J]=SynthMeasWatsonSHCylSingleRadGPD_PGSE(x, grad_dirs, G, delta, smalldel, fibredir, roots)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters. The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the hindered diffusivity outside the cylinders in perpendicular directions.\n% x(4) is the radius of the cylinders.\n% x(5) is the concentration parameter of the Watson's distribution\n%\n% grad_dirs is the gradient direction for each measurement. It has size [N\n% 3] where N is the number of measurements.\n%\n% G, delta and smalldel are the gradient strength, pulse separation and\n% pulse length of each measurement in the protocol. Each has\n% size [N 1].\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution. It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% roots contains solutions to the Bessel function equation from function\n% BesselJ_RootsCyl.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\n\n% Duplication with SynthMeasDistributedRadVG remains, because of the\n% derivative computation.\n\nf=x(1);\ndPar=x(2);\ndPerp=x(3);\nR=x(4);\nkappa=x(5);\n\n% build the input x vector for hindered compartment\nx_h = [dPar dPerp kappa];\n\n% build the input x vector for restricted diffusion in Neuman cylinder model\n% set diffusion coeff in restricted compartment same as parallel one in\n% hindered.\nx_r = [dPar R kappa];\n\n% Synthesize measurements from model\nif (nargout>1)\n\t[E_h, J_h] = SynthMeasWatsonHinderedDiffusion_PGSE(x_h, grad_dirs, G, delta, smalldel, fibredir);\n\t[E_r, J_r] = SynthMeasWatsonSHCylNeuman_PGSE(x_r, grad_dirs, G, delta, smalldel, fibredir, roots);\nelse\n\tE_h = SynthMeasWatsonHinderedDiffusion_PGSE(x_h, grad_dirs, G, delta, smalldel, fibredir);\n\tE_r = SynthMeasWatsonSHCylNeuman_PGSE(x_r, grad_dirs, G, delta, smalldel, fibredir, roots);\nend\n\nE=(1-f)*E_h+f*E_r;\n\n% Compute the Jacobian matrix\nif(nargout>1)\n \n % dE_tot/df = E_r - E_h\n dEtdf = E_r - E_h;\n \n % dE_tot/ddPar\n dEtddPar = (1-f)*J_h(:,1) + f*J_r(:,1);\n \n % dE_tot/ddPerp\n dEtddPerp = (1-f)*J_h(:,2);\n \n % dE_tot/dR\n dEtdr = f*J_r(:,2);\n \n % dE_tot/dk\n dEtdk = (1-f)*J_h(:,3) + f*J_r(:,3);\n \n % Construct the jacobian matrix. \n J = zeros(length(E), 5);\n J(:,1) = dEtdf;\n J(:,2) = dEtddPar;\n J(:,3) = dEtddPerp;\n J(:,4) = dEtdr;\n J(:,5) = dEtdk;\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHCylSingleRadGPD_PGSE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6391224496054632}} {"text": "function [f,g] = spsurfun(y, z)\n% SPSURFUN Evaluate the sparse grid interpolant at single point\n% IP = SPSURFUN(Y,Z) Computes the interpolated value IP at\n% the single point [Y1, ..., YD] for the sparse grid \n% interpolant Z.\n%\n% [IP,IPGRAD] = SPSURFUN(Y,Z) Computes the interpolated \n% value IP and the gradient vector IPGRAD.\n%\n% Example:\n% f = inline('x.^2 + y.^2 - 2.*z');\n% g1 = inline('2*x + 0*y + 0*z');\n% g2 = inline('2*y + 0*x + 0*z');\n% g3 = inline('-2 + 0*x + 0*y + 0*z');\n% z = spvals(f,3,[],spset('GridType','Chebyshev'));\n% [ip,ipgrad] = spsurfun([0.5, 0.2, 0.2], z)\n% f_exact = f(0.5, 0.2, 0.2)\n% g_exact = [g1(0.5, 0.2, 0.2); ...\n% g2(0.5, 0.2, 0.2); ...\n% g3(0.5, 0.2, 0.2)]\n%\n% See also SPINTERP, SPVALS. \n%\n% Note:\n% SPSURFUN is provided for conveniece to be used as an\n% alternative to SPINTERP, where the point Y to be\n% evaluated is given as a row or column vector. This\n% functional form is often adopted by multivariate \n% optimization algorithms (such as fminsearch) in\n% Matlab.\n% Note that this form allows the evaluation of the sparse\n% grid interpolant at a single point only. Therefore, It \n% is recommended to use SPINTERP instead if multiple \n% evaluations of the interpolant can be performed\n% simultaneously.\n \t\n% Author : Andreas Klimke\n% Version: 1.0\n% Date : September 8, 2006\n\n% Change log:\n% V1.0 : September 8, 2006\n% Initial version\n\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\nif nargout <= 1\n f = spinterp(z, y);\nelseif nargout == 2\n [f,g] = spinterp(z, y);\n g = g{1,1};\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spinterp/spsurfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6391017671213415}} {"text": "function linpack_s_test23 ( )\n\n%*****************************************************************************80\n%\n%% TEST23 tests SQRDC and SQRSL.\n%\n% Discussion:\n%\n% SQRDC and SQRSL compute the QR factorization, and use it\n% to solve linear systems.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 3;\n p = 3;\n lda = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST23\\n' );\n fprintf ( 1, ' For a general matrix,\\n' );\n fprintf ( 1, ' SQRDC computes the QR decomposition of a\\n' );\n fprintf ( 1, ' matrix, but does not return Q and R explicitly.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Show how Q and R can be recovered using SQRSL.\\n' );\n%\n% Set the matrix A.\n%\n a = [ ...\n 1.0, 1.0, 0.0; ...\n 1.0, 0.0, 1.0; ...\n 0.0, 1.0, 1.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The original matrix A:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : p\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Decompose the matrix.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Decompose the matrix.\\n' );\n\n job = 0;\n ipvt(1:p) = 0;\n\n [ a, qraux, ipvt ] = sqrdc ( a, lda, n, p, ipvt, job );\n%\n% Print out what SQRDC has stored in A...\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The packed matrix A which describes Q and R:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : p\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% ...and in QRAUX.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The QRAUX vector, containing some additional\\n' );\n fprintf ( 1, ' information defining Q:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %14f', qraux(i) );\n end\n fprintf ( 1, '\\n' );\n%\n% Print out the resulting R factor.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The R factor:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : p\n\n if ( j < i ) \n r(i,j) = 0.0;\n else\n r(i,j) = a(i,j);\n end\n\n end\n\n for j = 1 : p\n fprintf ( 1, ' %14f', r(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n%\n% Call SQRSL to extract the information about the Q matrix.\n% We do this, essentially, by asking SQRSL to tell us the\n% value of Q*Y, where Y is a column of the identity matrix.\n%\n job = 10000;\n\n for i = 1 : n\n%\n% Set the vector Y.\n%\n y(1:n) = 0.0;\n\n y(i) = 1.0;\n%\n% Ask SQRSL to tell us what Q*Y is.\n%\n [ qy, qty, b, rsd, xb, info ] = sqrsl ( a, lda, n, p, qraux, y, job );\n\n if ( info ~= 0 )\n fprintf ( 1, ' Error! SQRSL returns INFO = %d\\n', info );\n return\n end\n%\n% Copy QY into the appropriate column of Q.\n%\n q(1:n,i) = qy(1:n);\n\n end\n%\n% Now print out the Q matrix we have extracted.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The Q factor:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %14f', q(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Compute Q*R to verify that it equals A.\n%\n b(1:n,1:p) = q(1:n,1:n) * r(1:n,1:p);\n%\n% Print the result.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The product Q * R:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : p\n fprintf ( 1, ' %14f', b(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_s/linpack_s_test23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6390874877091124}} {"text": "function out=prox_max(x,alpha)\n%PROX_MAX computes the proximal operator of the function alpha*max(x(:))\n%\n% Usage: \n% out = PROX_MAX(x,alpha)\n% ===========================================\n% INPUT:\n% x - point to be projected (vector/matrix)\n% alpha - positive scalar\n% ===========================================\n% Output:\n% out - proximal operator at x\n\n% This file is part of the FOM package - a collection of first order methods for solving convex optimization problems\n% Copyright (C) 2017 Amir and Nili Beck\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\nif (nargin < 2)\n error ('usage: prox_max(x,alpha)') ;\nend\n\nif (alpha < 0)\n error('usage: prox_max(x,alpha) - alpha should be positive')\nend\n\nout = x - alpha * proj_simplex (x/alpha,1,'eq') ;\n\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/tool/FOM_prox functions/prox_max.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6390603341021822}} {"text": "function [U] = hyperNfindr(M, q)\n% HYPERNFINDR Performs the N-FINDR (endmember extraction) algorithm\n% Performs the N-FINDR algorithm to find q endmembers. If only M is\n% given as input, this function calls hyperHfcVd to estimate the number\n% of endmembers (q) and then hyperPct to reduce dimensionality to (q-1).\n%\n% Usage\n% [U] = hyperNfindr(M)\n% [U] = hyperNfindr(M, q)\n% Inputs\n% M - 2d matrix of HSI data (p x N)\n% q - Number of endmembers to find\n% -- if not given, q is obtained from hyperHfcVd(M, 10^-3)\n% Outputs\n% U - Recovered endmembers (p x q)\n% \n% References\n% M. Winter, \"N-findr: an algorithm for fast autonomous \n% spectral endmember determination in hyperspectral data,\" SPIE’s \n% International Symposium on Optical Science, Engineering, and \n% Instrumentation, pages 266–275. International Society for Optics \n% and Photonics, 1999.\n\n% Error trapping\nif ndims(M) ~= 2\n warning('WarnTests:dim', ...\n 'Input image must be p x N.\\n',...\n 'Converting with hyperConvert2d.\\n')\n M = hyperConvert2d(M);\nend\n\nM_orig = M;\n[p, N] = size(M);\n\nif nargin == 1\n fprintf('Implementing hyperHfcVd to determine the number of endmembers.\\n')\n q = hyperHfcVd(M_orig, [10^-3]);\n fprintf('Reducing dimensionality to (q-1) using hyperPct.\\n')\n M = hyperPct(M, q-1);\nelseif q < p+1\n warning('WarnTests:dim', ...\n strcat('N-FINDR requires (q-1) spectral bands.\\n',...\n 'Performing PCA to reduce dimensionality.\\n'))\n M = hyperPct(M, q-1);\nelseif q > p+1\n warning('WarnTests:dim', ...\n strcat('N-FINDR requires (q-1) spectral bands.\\n',...\n 'Performing PCA to reduce dimensionality.\\n'))\n error('ErrTests:dim', ...\n strcat('N-FINDR cannot find more than (p+1) endmembers (q),\\n', ...\n 'where p is the number of available spectral bands.\\n'))\nend\n\n% Initialize\nU_idx = randperm(N,q); % Random endmember selection\nE = M(:,U_idx); % Endmember matrix\nV = abs(det([ones(1,q); E])) / factorial(q-1); % Simplex volume\nvols = zeros(q,1);\n\n% Search for maximum volume simplex\nfor j = 1:N;\n % Replace each column of E with sample vector M(:,j) \n % and compute the volume for each\n for k = 1:q;\n E_tmp = E;\n E_tmp(:,k) = M(:,j);\n vols(k) = abs(det([ones(1,q); E_tmp])) / factorial(q-1);\n end\n % If max volume is greater than previous V, update E and V\n [V_tmp,k_idx] = max(vols);\n if V_tmp > V\n V = V_tmp;\n E(:,k_idx) = M(:,j);\n U_idx(k_idx) = j;\n end\nend\n\n% Return endmembers\nU = M_orig(:, U_idx);\n", "meta": {"author": "davidkun", "repo": "HyperSpectralToolbox", "sha": "147d58e6efe839e8945dc0d4e8d65029884137f1", "save_path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox", "path": "github-repos/MATLAB/davidkun-HyperSpectralToolbox/HyperSpectralToolbox-147d58e6efe839e8945dc0d4e8d65029884137f1/newFunctions/hyperNfindr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6390603288986368}} {"text": "function [p sres sres_ns] = ResidScan(res, FWHM)\n% function [p sres sres_ns] = ResidScan(res, FWHM)\n%\n% Calculates P(M>=t) where M is the max value of the smoothed residuals.\n% In this implementation the residuals are smoothed using a Gaussian\n% kernel.\n% \n% INPUT:\n%\n% res - residual time course\n% FWHM - Full Width Half Maximum (in time units)\n%\n% OUTPUT:\n%\n% p - pvalues\n% sres - smoothed residuals\n% sres_ns - smoothed residuals (non standardized) \n%\n% By Martin Lindquist & Ji-Meng Loh, July 2007\n%\n% Edited by ML on 10/02/09\n\nres_ns = res;\nres = res./std(res);\nlen = length(res);\n\n% Create Gaussian Kernel\nsig = ceil(FWHM/(2*sqrt(2*log(2)))); \nklen = 3*sig;\nkern = normpdf((-klen:klen),0,sig); \nkern = kern./sqrt(sum(kern.^2));\n\n% Convolve\nx = conv(res,kern);\nsres = x((klen + 1):(end-klen));\n\nx = conv(res_ns,kern/sum(kern));\nsres_ns = x((klen + 1):(end-klen));\n\n\n% Find Max value\n[a,location] = max(abs(sres));\n\n% Find p-values using Gaussian Random Field theory\nz = Euler_p(1, a, len, FWHM);\nz = 2*z; %Two-sided test\np = min(1, z);\n\nend\n\n% END MAIN FUNCTION\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Subfunctions\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nfunction pval = Euler_p(myDim, value, N, fwhm)\n% function z = Euler_p(myDim, value, N, fwhm)\n%\n% Finds the p value using the expected Euler characteristic. \n% \n% This function returns P(M \\ge value) using the approximation \n% \\sum_{d=0}^D R_d(V) \\rho_d(value) following Worsley et al's \"A Unified\n% Statistical Approach for Determining Significant Signals in Images of\n% Cerebral Activation\".\n%\n% INPUTS:\n%\n% myDim - the number of dimensions in the data\n% value - the value of the maximum. \n% N - the number of (time) points in that 1 dimension \n% fwhm - the full width half maximum\n%\n% OUTPUTS:\n%\n% pval - the p-value\n\n% NOTE: CURRENTLY THIS FUNCTION IS ONLY IMPLEMENTED FOR THE 1D CASE\n\n % Constants \n myfactor = 4*log(2);\n pi2 = 2*pi;\n exptsq = exp(-(value^2)/2);\n\n % Euler Characteristc Densties\n rho = zeros(5,1);\n rho(1) = 1-normcdf(value);\n rho(2) = myfactor^(0.5)*exptsq/pi2;\n rho(3) = myfactor * exptsq * value / (pi2 ^ (1.5));\n rho(4) = myfactor ^ (1.5) * exptsq * (value^2-1) / (pi2 ^2);\n rho(5) = myfactor ^2 * exptsq * (value^3-3*value) / (pi2 ^ (5/2));\n \n % Resel Count\n R0 = 1;\n R1 = N/fwhm;\n\n % P-value\n pval = R0 * rho(1) + R1 * rho(2);\n\nend\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/HRF_Est_Toolbox2/Old_stuff/More_recent_old_stuff/ResidScan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6390016566819625}} {"text": "function [ g , mu ] = gsp_design_translates(G, g0,N )\n%GSP_DESIGN_TRANSLATES Create a filterbank by uniformly translating a window\n% Usage: g = gsp_design_translates( G, g0, Ntrans );\n% \n% Inputs parameters:\n% G : Graph structure\n% g0 : Mother window (anonymous function)\n% N : Number of translate\n%\n% Outputs parameters:\n% g : filterbank\n% mu : Centers of the filters\n%\n% This function construct a filter bank of *N* uniformly translated\n% filter from the mother filter *g0*.\n%\n\n% Author : Nathanael Perraudin\n% Date: 6 January 2016\n\n\nif isstruct(G)\n if ~isfield(G,'lmax')\n if param.verbose\n fprintf('GSP_DESIGN_TRANSLATE has to compute lmax \\n')\n end\n G = gsp_estimate_lmax(G);\n end\n lmax = G.lmax;\nelse\n lmax = G;\nend\n\n\nmu = linspace(0,lmax,N);\n\ng = cell(length(mu),1);\n\nfor ii = 1:length(mu)\n g{ii} = @(x) g0(x-mu(ii));\nend\n\n\nend\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/stationarity/gsp_design_translates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6389516812188615}} {"text": "function b = r83_mv ( m, n, a, x )\n\n%*****************************************************************************80\n%\n%% R83_MV multiplies an R83 matrix times an R8VEC.\n%\n% Discussion:\n%\n% The R83 storage format is used for a tridiagonal matrix.\n% The superdiagonal is stored in entries (1,2:N), the diagonal in\n% entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the\n% original matrix is \"collapsed\" vertically into the array.\n%\n% Example:\n%\n% Here is how an R83 matrix of order 5 would be stored:\n%\n% * A12 A23 A34 A45\n% A11 A22 A33 A44 A55\n% A21 A32 A43 A54 *\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(3,N), the R83 matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(M), the product A * x.\n%\n b = zeros ( m, 1 );\n\n mn = min ( m, n );\n\n if ( n == 1 )\n b(1,1) = a(2,1) * x(1,1);\n if ( 1 < m )\n b(2,1) = a(3,1) * x(1,1);\n end\n return\n end\n\n b(1,1) = a(2,1) * x(1,1) ...\n + a(1,2) * x(2,1);\n\n b(2:mn-1,1) = a(3,1:mn-2)' .* x(1:mn-2,1) ...\n + a(2,2:mn-1)' .* x(2:mn-1,1) ...\n + a(1,3:mn)' .* x(3:mn,1);\n\n b(mn,1) = a(3,mn-1) * x(mn-1,1) ...\n + a(2,mn) * x(mn,1);\n\n if ( n < m )\n b(mn+1,1) = b(mn+1,1) + a(3,mn) * x(mn,1);\n end\n\n if ( m < n )\n b(mn,1) = b(mn,1) + a(1,mn+1) * x(mn+1,1);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cg/r83_mv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6389516779947177}} {"text": "function [ final_dist ] = re_ranking( feat, M, W, query_num, k1, k2, lambda)\n% k-reciprocal re-ranking\n\n%% initial ranking list\noriginal_dist = MahDist(M, feat' * W, feat' * W);\n[~, initial_rank] = sort(original_dist, 2, 'ascend');\ngallery_num = size(original_dist,2);\n%% compute k-reciprocal feature\nV = zeros(size(original_dist), 'single');\noriginal_dist = original_dist./ repmat(max(original_dist, [], 2), 1, size(original_dist, 2));\nfor i = 1:size(original_dist, 1)\n %% k-reciprocal neighbors\n forward_k_neigh_index = initial_rank(i, 1: k1 + 1);\n backward_k_neigh_index = initial_rank(forward_k_neigh_index, 1: k1+1);\n [fi, ~, ~]= find(backward_k_neigh_index == i);\n k_reciprocal_index = forward_k_neigh_index(fi);\n k_reciprocal_expansion_index = k_reciprocal_index;\n for j = 1: length(k_reciprocal_index)\n candidate = k_reciprocal_index(j);\n candidate_forward_k_neigh_index = initial_rank(candidate, 1: round((k1+1)/2));\n candidate_backward_k_neigh_index = initial_rank(candidate_forward_k_neigh_index, 1: round((k1+1)/2));\n [fi_candidate, ~, ~]= find(candidate_backward_k_neigh_index == candidate);\n candidate_k_reciprocal_index = candidate_forward_k_neigh_index(fi_candidate);\n if length(intersect(k_reciprocal_index, candidate_k_reciprocal_index)) > 2/3*length(candidate_k_reciprocal_index)\n k_reciprocal_expansion_index = [k_reciprocal_expansion_index candidate_k_reciprocal_index];\n end\n end\n k_reciprocal_expansion_index = unique(k_reciprocal_expansion_index);\n %% feature encoding\n weight = exp(-original_dist(i, k_reciprocal_expansion_index));\n V(i, k_reciprocal_expansion_index) = weight/sum(weight);\nend\n%% local query expansion\nif k2 ~=1\n V_qe = zeros(size(V), 'single');\n for i = 1:size(V, 1)\n V_qe(i, :) = single(mean(V(initial_rank(i, 1:k2), :), 1));\n end\n V = V_qe;\n V_qe = [];\nend\n\n%% Inverted Index \n% Inpsired by Song Bai, Xiang Bai,\n% Sparse Contextual Activation for Efficient Visual Re-ranking, TIP, 2016.\n% We apply the inverted index to quickly compute the Jaccard distance.\n\ninvIndex = cell(gallery_num, 1);\nfor i = 1:gallery_num\n invIndex{i} = find(V(:, i) ~=0);\nend\n\njaccard_dist = zeros(size(original_dist), 'single');\n\nfor i = 1:query_num \n temp_min = zeros(1, gallery_num, 'single');\n indNonZero = find( V( i, : ) ~= 0 );\n indImages = invIndex( indNonZero );\n for j = 1 : length( indNonZero )\n temp_min( 1, indImages{j} ) = temp_min( 1, indImages{j} )...\n + single( min( V(i, indNonZero(j)), V(indImages{j}, indNonZero(j)) ) )';\n end\n jaccard_dist(i, :) = bsxfun(@minus, 1, temp_min./(2 - temp_min)); \nend\n\nfinal_dist = jaccard_dist*(1-lambda) + original_dist*lambda;\nfinal_dist = final_dist(1:query_num,query_num+1:end)';\n\nend", "meta": {"author": "Simon4Yan", "repo": "Learning-via-Translation", "sha": "f73210e35e1515528c454c681e7d6695fdecf818", "save_path": "github-repos/MATLAB/Simon4Yan-Learning-via-Translation", "path": "github-repos/MATLAB/Simon4Yan-Learning-via-Translation/Learning-via-Translation-f73210e35e1515528c454c681e7d6695fdecf818/duke_evaluation/utils/re_ranking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6388923467710066}} {"text": "function disp (F)\n%DISP displays the factorization F\n%\n% Example\n% F = factorize (A)\n% disp (F)\n%\n% See also factorize.\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\nfprintf (' A:\\n') ;\ndisp (F.A) ;\n\nif (~isempty (F.L))\n fprintf (' L:\\n') ;\n disp (F.L) ;\nend\n\nif (~isempty (F.U))\n fprintf (' U:\\n') ;\n disp (F.U) ;\nend\n\nif (~isempty (F.Q))\n fprintf (' Q:\\n') ;\n disp (F.Q) ;\nend\n\nif (~isempty (F.R))\n fprintf (' R:\\n') ;\n disp (F.R) ;\nend\n\nif (~isempty (F.p))\n fprintf (' p:\\n') ;\n disp (F.p) ;\nend\n\nif (~isempty (F.q))\n fprintf (' q:\\n') ;\n disp (F.q) ;\nend\n\nfprintf (' is_inverse: %d kind: %d\\n', F.is_inverse, F.kind) ;\n\n% print the kind of factorization that F contains\n\nswitch F.kind\n\n case 1\n\n fprintf (' Q-less economy sparse QR factorization: ') ;\n fprintf ('(A*q)''*A*q = R''*R\\n');\n\n case 2\n\n fprintf (' dense economy QR factorization: A = Q*R\\n') ;\n\n case 3\n\n fprintf (' Q-less economy sparse QR factorization: ') ;\n fprintf ('(p*A)*(p*A)'' = R''*R\\n') ;\n\n case 4\n\n fprintf (' dense economy QR factorization: A'' = Q*R\\n') ;\n\n case 5\n\n fprintf (' sparse Cholesky factorization: ') ;\n fprintf ('q*A*q'' = L*L''\\n');\n\n case 6\n\n fprintf (' dense Cholesky factorization: A = L*L''\\n') ;\n\n case 7\n\n fprintf (' sparse LU factorization: p*A*q = L*U\\n') ;\n\n case 8\n\n fprintf (' dense LU factorization: p*A = L*U\\n') ;\n\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/MATLAB_Tools/Factorize/@factorize/disp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6388745975427916}} {"text": "function new = colormap_optimization(cmap)\n%colormap_optimisation: minimally modify colormap to satisfy constraints.\n% In this case, the constraints are for linear grayscale luminance and a\n% neutral mid-gray central color.\n%\n% Example:\n% sprung = colormap_optimization(spring(5));\n% colormap_visualization(spring(5))\n% colormap_visualization(sprung)\n%\n% See also: colormap_investigation, colormap_visualization, bipolar\n\n% Copyright 2009 Ged Ridgway at gmail com\n\n%% Conversion from RGB to grayscale brightness/luminance\n\n% From http://www.poynton.com/ColorFAQ.html (Q.9)\n% coef = [0.2126 0.7152 0.0722]'\n\n% From rgb2gray:\n% T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]);\n% coef = T(1,:)';\n\n% From http://gimp-savvy.com/BOOK/index.html?node54.html\ncoef = [0.3 0.59 0.11]';\n% Note, the Gimp coef is almost identical to that from rgb2gray, and these\n% seem nicer in a print('-dps') grayscale copy than the Poynton version.\n\n%% Constraints\nm = size(cmap, 1);\nmid = zeros(1, m);\nmid(round((m+1)/2)) = 1;\nAeq = [\n kron(coef', eye(m)) % linearity in luminance\n kron(eye(2,3), mid) % centrality\n ];\nl = 0.1; % lower luminance (avoid black, to give contrast with text/lines)\nu = 0.9; % upper luminance (avoid white, to give contrast with background)\nbeq = [\n linspace(l, u, m)' % linearity in luminance\n ones(2, 1) / 2 % centrality\n ];\n\n%% Optimisation (using MATLAB optimisation toolbox)\norig = warning('off', 'optim:lsqlin:LinConstraints');\nx = lsqlin(eye(3*m), cmap(:), [], [], Aeq, beq, zeros(3*m, 1), ones(3*m, 1));\nx = max(min(x, 1), 0); % enforce bounds, since lsqlin can give e.g. -1e-18\nnew = reshape(x, m, 3);\nwarning(orig);\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/26026-bipolar-colormap/bipolar_colormap/colormap_optimization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.63887458463674}} {"text": "function [ SV ] = moveFV(V,F,S)\n% MOVEFV Move a scalar field defined on faces to vertices by averaging\n% \n% [ SV ] = moveFV(V,F,S)\n%\n% Input:\n% V,F mesh\n% S scalar field defined on faces, Fx1\n% \n% Output:\n% SV scalar field defined on vertices\n\nSV = zeros(size(V,1),size(S,2));\nCOUNT = zeros(size(V,1),1);\n\nfor i=1:size(F,1)\n SV(F(i,:)',:) = SV(F(i,:)',:) + repmat(S(i,:),size(F,2),1);\n COUNT(F(i,:)') = COUNT(F(i,:)') + 1;\nend\n\nSV = SV ./ repmat(COUNT, 1, size(S,2));\n\nend\n\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/moveFV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.638801635156491}} {"text": "function [M, L, Y, C] = lmnn(X, labels)\n%LMNN Learns a metric using large-margin nearest neighbor metric learning\n%\n% [M, L, Y, C] = lmnn(X, labels)\n%\n% The function uses large-margin nearest neighbor (LMNN) metric learning to\n% learn a metric on the data set specified by the NxD matrix X and the\n% corresponding Nx1 vector labels. The metric is returned in M.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n % Initialize some variables\n [N, D] = size(X);\n assert(length(labels) == N);\n [lablist, ~, labels] = unique(labels);\n K = length(lablist);\n label_matrix = false(N, K);\n label_matrix(sub2ind(size(label_matrix), (1:length(labels))', labels)) = true;\n same_label = logical(double(label_matrix) * double(label_matrix'));\n M = eye(D);\n C = Inf; prev_C = Inf;\n \n % Set learning parameters\n min_iter = 50; % minimum number of iterations\n max_iter = 1000; % maximum number of iterations\n eta = .1; % learning rate\n mu = .5; % weighting of pull and push terms\n tol = 1e-3; % tolerance for convergence\n best_C = Inf; % best error obtained so far\n best_M = M; % best metric found so far\n no_targets = 3; % number of target neighbors\n \n % Select target neighbors\n sum_X = sum(X .^ 2, 2);\n DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (X * X')));\n DD(~same_label) = Inf; DD(1:N + 1:end) = Inf;\n [~, targets_ind] = sort(DD, 2, 'ascend');\n targets_ind = targets_ind(:,1:no_targets);\n targets = false(N, N);\n targets(sub2ind([N N], vec(repmat((1:N)', [1 no_targets])), vec(targets_ind))) = true;\n \n % Compute pulling term between target neigbhors to initialize gradient\n slack = zeros(N, N, no_targets); \n G = zeros(D, D);\n for i=1:no_targets\n G = G + (1 - mu) .* (X - X(targets_ind(:,i),:))' * (X - X(targets_ind(:,i),:));\n end\n \n % Perform main learning iterations\n iter = 0;\n while (prev_C - C > tol || iter < min_iter) && iter < max_iter\n \n % Compute pairwise distances under current metric\n XM = X * M;\n sum_X = sum(XM .* X, 2);\n DD = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * (XM * X')));\n \n % Compute value of slack variables\n old_slack = slack;\n for i=1:no_targets\n slack(:,:,i) = ~same_label .* max(0, bsxfun(@minus, 1 + DD(sub2ind([N N], (1:N)', targets_ind(:,i))), DD));\n end\n \n % Compute value of cost function\n prev_C = C;\n C = (1 - mu) .* sum(DD(targets)) + ... % push terms between target neighbors\n mu .* sum(slack(:)); % pull terms between impostors\n \n % Maintain best solution found so far (subgradient method)\n if C < best_C\n best_C = C;\n best_M = M;\n end\n \n % Perform gradient update\n for i=1:no_targets\n \n % Add terms for new violations\n [r, c] = find(slack(:,:,i) > 0 & old_slack(:,:,i) == 0);\n G = G + mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ...\n (X(r,:) - X(targets_ind(r, i),:)) - ...\n (X(r,:) - X(c,:))' * (X(r,:) - X(c,:)));\n \n % Remove terms for resolved violations\n [r, c] = find(slack(:,:,i) == 0 & old_slack(:,:,i) > 0);\n G = G - mu .* ((X(r,:) - X(targets_ind(r, i),:))' * ...\n (X(r,:) - X(targets_ind(r, i),:)) - ...\n (X(r,:) - X(c,:))' * (X(r,:) - X(c,:)));\n end\n M = M - (eta ./ N) .* G;\n \n % Project metric back onto the PSD cone\n [V, L] = eig(M);\n V = real(V); L = real(L);\n ind = find(diag(L) > 0);\n if isempty(ind)\n warning('Projection onto PSD cone failed. All eigenvalues were negative.'); break\n end\n M = V(:,ind) * L(ind, ind) * V(:,ind)';\n if any(isinf(M(:)))\n warning('Projection onto PSD cone failed. Metric contains Inf values.'); break\n end\n if any(isnan(M(:)))\n warning('Projection onto PSD cone failed. Metric contains NaN values.'); break\n end\n \n % Update learning rate\n if prev_C > C\n eta = eta * 1.01;\n else\n eta = eta * .5;\n end\n \n % Print out progress\n iter = iter + 1;\n no_slack = sum(slack(:) > 0);\n if rem(iter, 10) == 0\n [~, sort_ind] = sort(DD, 2, 'ascend');\n disp(['Iteration ' num2str(iter) ': error is ' num2str(C ./ N) ...\n ', nearest neighbor error is ' num2str(sum(labels(sort_ind(:,2)) ~= labels) ./ N) ...\n ', number of constraints: ' num2str(no_slack)]);\n end\n end\n \n % Return best metric and error\n M = best_M;\n C = best_C;\n \n % Compute mapped data\n [L, S, ~] = svd(M);\n L = bsxfun(@times, sqrt(diag(S)), L);\n Y = X * L;\nend\n\nfunction x = vec(x)\n x = x(:);\nend\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/lmnn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6387815600905761}} {"text": "function [ CostMatric,Cost ] = MinimalDirectedMSF( CostMatric )\n% MST on a directed graph\n% Chu-Liu/Edmonds Algorithm:\n%1 Discard the arcs entering the root if any; For each node other than the root, select the entering arc with the highest cost; Let the selected n-1 arcs be the set S. \n% If no cycle formed, G( N,S ) is a MST. Otherwise, continue. \n%2 For each cycle formed, contract the nodes in the cycle into a pseudo-node (k), and modify the cost of each arc which enters a node (j) in the cycle from some node (i)\n% outside the cycle according to the following equation. c(i,k)=c(i,j)-(c(x(j),j)-min_{j}(c(x(j),j)) where c(x(j),j) is the cost of the arc in the cycle which enters j. \n%3 For each pseudo-node, select the entering arc which has the smallest modified cost; Replace the arc which enters the same real node in S by the new selected arc. \n%4 Go to step 2 with the contracted graph.\n\n% Pay attention, we extend the Chu-Liu algorithm into considering\n% forest.And we consider of discarding the premise of giving the root here.\n% CostMatric must be symmetric\n\n [ Number, Component ] = conncomp( biograph( CostMatric ),'Weak', true );\n for k = 1:Number \n LocalNodes = find( Component == k );\n Dim = size( LocalNodes,2 );\n if Dim == 1\n continue\n elseif Dim == 2\n if CostMatric( LocalNodes(1),LocalNodes(2) ) > CostMatric( LocalNodes(2),LocalNodes(1) ) \n CostMatric( LocalNodes(2),LocalNodes(1) ) = 0;\n else\n CostMatric( LocalNodes(1),LocalNodes(2) ) = 0;\n end\n elseif Dim > 2 \n ComponentCost = CostMatric( LocalNodes,LocalNodes );\n MinTree = zeros( Dim ); MinTreeCost = Inf; \n for m = 1:Dim\n Root = m;\n LocalCostMatric = ComponentCost;\n LocalCostMatric( :,Root ) = zeros( Dim,1 );\n [ LocalTree,LocalCostTree ] = DirectedMinimalSpanningTree( LocalCostMatric,Root );\n if MinTreeCost > LocalCostTree\n MinTree = LocalTree;\n MinTreeCost = LocalCostTree ;\n end\n end\n CostMatric( LocalNodes,LocalNodes ) = MinTree; \n end\n end\n Cost = sum( sum( CostMatric ));\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24327-maximumminimum-weight-spanning-tree-directed/DirectedSpanningTree/MinimalDirectedMSF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6387815525795018}} {"text": "% NOLM_Attractor - Plot a chaotic attractor for the NOLM.\n% Copyright Springer 2013 A.L. Steele and S. Lynch.\nclear\nN=50000;P=100;start=500;\nlambda=1.55E-6;n2=3.2E-20;Aeff=30E-12;L=80;\nE1(1)=0;phi=0*pi;\nEout(1:N)=0; \nphif=0*pi; E6p=0;\n\nkappa1=0.25;kappa2=0.8;kappa3=0.8;\nrootk1 = sqrt(kappa1); irootk1 = 1i*sqrt(1-kappa1);\nrootk2 = sqrt(kappa2); irootk2 = 1i*sqrt(1-kappa2);\nrootk3 = sqrt(kappa3); irootk3 = 1i*sqrt(1-kappa3);\n\nG=sqrt((1-kappa2)*(1-kappa3));\n% iterate\nfor n=1:N\n \n E1 = rootk3*sqrt(P)+irootk3*E6p;\n P1 = abs(E1)^2;\n \n E3 = rootk1*E1;\n E4 = irootk1*E1;\n \n phic=2*pi*n2*L*(2-kappa1)*P1/(lambda*Aeff);\n phicc=2*pi*n2*L*(1+kappa1)*P1/(lambda*Aeff);\n \n E3p = E3*exp(-1i*(phi+phic));\n E4p = E4*exp(-1i*(phi+phicc));\n \n E5 = rootk1*E3p+irootk1*E4p;\n \n Eout(n) = rootk2*E5;\n x(n)=real(Eout(n));\n y(n)=imag(Eout(n));\n E6 = irootk2*E5;\n \n E6p = E6*exp(1i*phif);\n \nend\naxis([-10 10 -10 10])\naxis equal\nplot(x(start:N),y(start:N),'.','MarkerSize',1);\nfsize=15;\nset(gca,'xtick',-10:5:10,'FontSize',fsize)\nset(gca,'ytick',-10:5:10,'FontSize',fsize)\nxlabel('Real E','FontSize',fsize)\nylabel('Imag E','FontSize',fsize)\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/32919-applications-of-chaos-and-nonlinear-dynamics-in-engineering-vol-1/NOLM_Attractor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6386570907078427}} {"text": "function E = energyVector(C,x,V,P,varargin)\n% Calculates Energy velocity vector (km/s)\n%\n% Description\n% Energy velocity for lossless elastic medium (i.e. no attenuation)\n% Good proxy for group velocity, which typically has some energy loss\n% The formula is given by\n% F.I. Fedorov(1968)Theory of Elastic Waves in Crystals, 375 pp. New York: Penum Press.\n%\n% Ve_i = C_ijkl P_j P_l X_k / rho*V\n% \n% N.B. E_magnitude should be equal or more than plane wave velocity vp, vs1 or vs2\n% \n% David Mainprice 6/02/2018\n%\n% Syntax\n% E = energyVector(C,x,v,p)\n% E = energyVector(C,x,v,p,rho)\n% E = energyVector(C,[],vFun,pFun)\n% E = energyVector(C,[],vFun,pFun,rho)\n%\n% Input\n% C - @stiffnessTensor (units GPa)\n% x - @vector3d propagation direction \n% v - plane wave velocity (unit km/s) e.g. vp,vs1 or vs2 \n% p - @vector3d plane wave polarization vector e.g. pp,ps1 or ps2\n% vFun - @S2Fun plane wave velocity (unit km/s) e.g. vp,vs1 or vs2 \n% pFun - @S2AxisField plane wave polarization vector e.g. pp,ps1 or ps2\n% rho - density in g/cm3\n%\n% Output\n% E - Energy velocity vector (units km/s)\n%\n\n\n% return a function if required\nif isempty(x)\n if isa(V,'S2FunTri')\n E = S2VectorFieldTri(V.tri,energyVector(C,V.vertices,V.values,P.values,varargin{:}));\n else\n E = S2VectorFieldHarmonic.quadrature(@(x) energyVector(C,x,V,P,varargin{:}),'bandwidth',128,C.CS);\n end\n return\nend\n\n% make X and P to be unit vectors\nx = x.normalize;\n\nif ~isa(P,'vector3d'), P = P.eval(x); end\nif ~isnumeric(V), V = V.eval(x); end\nP = P.normalize;\n\n% get density\nif nargin == 5\n rho = varargin{1};\nelseif isfield(C.opt,'density')\n rho = C.opt.density;\nelse\n rho = 1;\n warning('No density given! I''m going to use the density rho=1.'); \nend\n\n% E_vector\nE = vector3d(EinsteinSum(C,[1 -2 -3 -4],P(:),-2,P(:),-4,x(:),-3))./rho ./V(:);\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/TensorAnalysis/@stiffnessTensor/energyVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6386570843559257}} {"text": "% vgg_line3d_from_lP_nonlin Non-linear estimation of (possibly constrained) 3D line segment from image line segments.\n%\n% SYNOPSIS\n% L = vgg_line3d_from_lP_nonlin(s,P [,imsize] [,L0] [,X] [,nonlin_opt])\n%\n% s ... cell(K) of double(3,3), inv. covariance matrices of the K image line segments:-\n% - If the segments are estimated from edges, it is s(:,k) = x*x',\n% where x (3-by-N) are homog. coordinates of the edgels with last components 1.\n% - If only end points are available, s(:,k) = d*x*y' where x, y (column 2-vectors)\n% are the segment's end points and d its length.\n%\n% P ... K-cell with 3-by-4 camera matrices\n%\n% imsize ... size (2,K), image size(s) for preconditiong.\n% Omit if s and P are already preconditioned.\n%\n% L0 ... double(4,2), initial scene line (optional). Homogeneous points L0(:,i) span \n% the line. If omitted, linear estimation is done first.\n%\n% X ... constraint on L :-\n% - if X is omitted: no constraint on L\n% - if X is double(4,1): L goes thru point X\n% - if X is double(4,2): L goes thru 3D line spanned by X(:,i)\n%\n% nonlin_opt ... options for Levenberg-Marquardt. It is comma-separated list\n% of pairs ['option',value]. Possible options are :-\n% opt ... options structure with possible fields :-\n% - verbose ... 1 or 0 (default: 0)\n% - niter_term ... maximum number of iterations\n% - rmsstep_term ... terminating step of rms of residuals\n% - lambda_term ... terminating value of lambda (default: 1e10)\n% - lambda_init ... initial value of lambda\n% E.g., vgg_line3d_from_lP_nonlin(...,'lambda_init',1e-9,'niter_term',5).\n%\n% L ... double(4,2), estimated 3D line. Points L(:,i) span the line.\n%\n% Note: use [] if you want to omit a parameter and use a later one, e.g.\n% vgg_line3d_from_lP_nonlin(s,P,imsize,[],[],'verbose',1,'lam_init',1e-9)\n%\n% ALGORITHM\n% - Minimization is done by Levenberg-Marquardt.\n% - 3D line L is parameterized by image lines in the first two images.\n% The positions of these image lines are possibly constrained by X.\n\n% T.Werner, Feb 2002\n\nfunction L = vgg_line3d_from_lP_nonlin(s,P,imsize,L,X,varargin)\n\nif nargin < 3, imsize = []; end\nif nargin < 4, L = []; end\nif nargin < 5, X = []; end\n\nif isempty(L)\n L = vgg_line3d_from_lP_lin(s,P,imsize);\nend\nK = length(P); % number of images\nif K<2\n error('Cannot reconstruct 3D line from 1 image');\nend\nif isempty(X) & K==2 % no need for non-linear minimization\n return\nend\n\n% Prepare square root of covariance matrices; now s{k}(:,n) has meaning of 3 homogeneous image points\nfor k = 1:K\n [us,ss,vs] = svd(s{k},0);\n s{k} = us*sqrt(ss);\nend\n\n% Preconditioning\nif ~isempty(imsize)\n for k = 1:K\n H = vgg_conditioner_from_image(imsize(:,k));\n P{k} = H*P{k};\n s{k} = H*s{k};\n scale(k) = H(1,1); % save the scales for evaluating objective function\n end\nelse\n scale = ones(1,K);\nend\n\nswitch size(X,2)\n case 0 \n % Scene line L is unconstrained, having thus 4 DOF.\n % L is parameterized by two image lines in images 1 and 2, each having 2 DOF, as follows:\n % l1 = l0(1,:) + p(1:2)'*ldelta{1}\n % l2 = l0(2,:) + p(3:4)'*ldelta{2}\n % where row 4-vector p represents 4 DOF of L.\n for k = 1:2\n l0(k,:) = normx(vgg_wedge(P{k}*L)')';\n ldelta{k} = null(l0(k,:))';\n end\n\n % optimization\n p = levmarq(@F, {vertcat(P{:}),s,scale,l0,ldelta},...\n @normsolve,...\n [0;0;0;0],...\n varargin{:});\n l = l12_from_p(p,l0,ldelta);\n\n case 1 \n % Scene line L is constrained to intersect the scene point X, having thus 2 DOF.\n % L is parameterized by two image lines in images 1 and 2, each having 1 DOF, as follows:\n % l1 = l0(1,:) + p(1)*ldelta{1}\n % l2 = l0(2,:) + p(2)*ldelta{2}\n % where 2-vector p represents 2 DOF of L.\n for k = 1:2\n l0(k,:) = normx(vgg_wedge(P{k}*L)')';\n x = P{k}*X;\n \n % Since L might not intersect X, move l0(k,:) 'as little as possible' to intersect x.\n l0(k,:) = l0(k,:) - (l0(k,:)*x)/(x'*x).*x';\n \n Q = null(x')';\n ldelta{k} = null(l0(k,:)*pinv(Q))'*Q;\n end\n\n % optimization\n p = levmarq(@F, {vertcat(P{:}),s,scale,l0,ldelta},...\n @normsolve,...\n [0;0],...\n varargin{:});\n l = l12_from_p(p,l0,ldelta);\n\n case 2\n % Scene line L is constrained to intersect the scene line given by 2 points X.\n % This constraint is given by \n % l1*G*l2' = 0\n % where G is 3x3 rank 2 matrix (analogical in fact to fundamental matrix) and\n % G = P{1}*M*P{2}'\n % where M is Pluecker matrix of line given by X, M = X(:,1)*X(:,2)'-X(:,2)*X(:,1).\n %\n % This constraint can be written as\n % p(1:2)*D*p(3:4)' + p(1:2)*d{2}' + d{1}*p(3:4)' + c = 0\n % where D, d, c are given below and 4-vector p are 4 parameters of L.\n %\n % L is parameterized by two image lines in images 1 and 2, each having 2 DOF, as follows:\n % l1 = l0(1,:) + p(1:2)'*ldelta{1}\n % l2 = l0(2,:) + p(3:4)'*ldelta{2}\n % where p(1:3) are chosen freely and p(4) is computed from the above formula as\n % p(4) = -(p(1:2)'*(D(:,1)*p(3)+d{1})+p(3)*d{2}(1)+c)/(p(1:2)'*D(:,2)+d{2}(2)).\n Lpm = X(:,1)*X(:,2)' - X(:,2)*X(:,1)';\n G = P{1}*Lpm*P{2}';\n for k = 1:2\n l0(k,:) = normx(vgg_wedge(P{k}*L)')';\n end \n\n % As L might not intersect line X, move l0(2,:) 'as little as possible' to enforce l0(1,:)*G*l0(2,:)'==0.\n x = (l0(1,:)*G)';\n l0(2,:) = l0(2,:) - (l0(2,:)*x)/(x'*x).*x';\n \n for k = 1:2\n ldelta{k} = null(l0(k,:))';\n end \n \n D = ldelta{1}*G*ldelta{2}';\n d{1} = ldelta{1}*G*l0(2,:)';\n d{2} = ldelta{2}*G'*l0(1,:)';\n c = l0(1,:)*G*l0(2,:)';\n \n % optimization\n p = levmarq(@F, {vertcat(P{:}),s,scale,l0,ldelta,D,d,c},...\n @normsolve,...\n [0;0;0],...\n varargin{:});\n l = l12_from_p(p,l0,ldelta,D,d,c);\n\nend\nif all(~isnan(l(:)))\n L = null([l(1,:)*P{1}; l(2,:)*P{2}]);\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% objective function\n\n\n% Objective function of Levenberg-Marquardt\nfunction [y,w,J] = F(p,P,s,scale,varargin)\nK = length(s);\n\n% l := lines in images 1, 2 from p\nl = l12_from_p(p,varargin{:});\n\n% l := reprojection of lines in images 1, 2 to all images\nif all(abs(p) < inf)\n [dummy,dummy,L]= svd([l(1,:)*P(1:3,:); l(2,:)*P(4:6,:)],0);\nelse\n L = inf*ones(4);\nend\nl = norml(vgg_wedge(reshape(P*L(:,3),[3 K]),reshape(P*L(:,4),[3 K])));\n\n% compute residual function\ny = [];\nfor k = 1:K\n y = [y l(k,:)*s{k}];\nend\ny = y';\n\nw = [1;1;1] * (1./scale);\nw = w(:);\n\n% else, compute also jacobian\nif nargout < 2\n return\nend\ndif = 1e-6;\nJ = zeros(length(y),length(p));\nfor i = 1:length(p)\n pdif = p;\n pdif(i) = pdif(i) + dif;\n J(:,i) = (F(pdif,P,s,scale,varargin{:}) - y)/dif;\nend\nreturn\n\n\n% The following function computes lines in the first two images\n% from parameters p. Explanation see above.\nfunction l = l12_from_p(p,l0,ldelta,D,d,c)\nswitch length(p)\n case 4 % unconstrained\n l = [l0(1,:) + p(1:2)'*ldelta{1}\n l0(2,:) + p(3:4)'*ldelta{2}];\n case 2 % going thru X\n l = [l0(1,:) + p(1)*ldelta{1}\n l0(2,:) + p(2)*ldelta{2}];\n case 3 % going thru L\n p(4) = -(p(1:2)'*(D(:,1)*p(3)+d{1})+p(3)*d{2}(1)+c)/(p(1:2)'*D(:,2)+d{2}(2));\n l = [l0(1,:) + p(1:2)'*ldelta{1}\n l0(2,:) + p(3:4)'*ldelta{2}];\nend\nreturn\n\n\nfunction dp = normsolve(J,Y,w,lambda)\nOLDWARN = warning('off');\ndp = -( J'*diag(w)*J + lambda*eye(size(J,2)) ) \\ ( J'*(Y.*w) );\nwarning(OLDWARN);\nreturn\n\nfunction x = normx(x)\nif ~isempty(x)\n x = x./(ones(size(x,1),1)*sqrt(sum(x.*x)));\nend\n\nfunction l = norml(l)\n% l = norml(l) Multiplies hyperplane l by scalar so that for each n, norm(l(1:end-1,n))==1. \nl = l./(sqrt(sum(l(:,1:end-1).^2,2))*ones(1,size(l,2)));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% a = levmarq(@RES,PARAMS,@NORMSOLVE,a [,opt]) Non-linear least-squares by Levenberg-Marquardt.\n%\n% Minimizes f(a)'*W*f(a) over a.\n%\n% @RES ... residual function f called like [e,w,J] = RES(a,PARAMS{:}), where\n% - a ... double(M,1), parameter vector\n% - e ... double(N,1), residual vector\n% - J ... double(N,M), derivative of e wrt a\n% - w ... double(N,1), weights of e; covariance matrix of e is diag(1/e.^2).\n% Use 1 instead of ones(N,1).\n% For efficiency, RES should not compute the jacobian if called with two output parameters only.\n%\n% @NORMSOLVE ... function solving normal equations, called like da = NORMSOLVE(J,e,W,lambda).\n% a ... initial parameter vector\n% opt ... options structure, see code\n\nfunction [a,w] = levmarq(RES,PARAMS,NORMSOLVE,a0,varargin)\n\n% options\n[opt,rem_opt] = vgg_argparse( { 'niter_term', +inf,...\n 'drmsrel_term', 0,...\n 'loglambda_term', 6,...\n 'loglambda_init', -4,...\n 'verbose', 0 },...\n varargin );\nif ~isempty(rem_opt), if ~isempty(fieldnames(rem_opt))\n error(['Unknown option(s) ' fieldnames(rem_opt)]);\nend, end\n\n\n% Initial statistics\nif opt.verbose\n [e0,w0] = feval(RES,a0,PARAMS{:});\n ssd0 = sum( (e0.*w0).^2 );\n fprintf( ' [rms=%14.12g] [maxabs=%14.12g]\\n',...\n sqrt(ssd0/length(e0)),...\n max(abs(e0.*w0)) );\nend\n\n\nloglambda = opt.loglambda_init;\nniter = 0;\nwhile 1\n\n % Compute actual residual and jacobian\n [e0,w0,J] = feval(RES,a0,PARAMS{:}); \n\n % Update a as a := a0 + da, by finding\n % optimal lambda and solving normal equations for da.\n nfail = 1;\n while (loglambda < opt.loglambda_term)\n niter = niter + 1;\n \n a = a0 + feval(NORMSOLVE,J,e0,w0,10^loglambda);\n [e,w] = feval(RES,a,PARAMS{:});\n\n if sum((e.*w).^2) < sum((e0.*w0).^2) % success\n a0 = a;\n loglambda = loglambda - 1;\n break\n end\n\n if opt.verbose\n fprintf('%4i.%.2i: [loglambda=%3i] [REJECTED]\\n',niter,nfail,loglambda);\n end\n\n loglambda = loglambda + 1;\n nfail = nfail + 1;\n end\n\n % Print statistic after successful iteration\n ssd0 = sum( (e0.*w0).^2 );\n ssd = sum( (e.*w).^2 );\n if opt.verbose\n fprintf( '%4i : [loglambda=%3i] [rms=%14.12g] [maxabs=%14.12g] [drmsrel=%4g%%]\\n',...\n niter,...\n round(loglambda),...\n sqrt(ssd/length(e)),...\n max(abs(e.*w)),...\n 100*(1-sqrt(ssd/ssd0)) );\n end\n\n % Termination criteria\n test(1) = loglambda < opt.loglambda_term;\n test(2) = ssd0-ssd >= opt.drmsrel_term^2*ssd0;\n test(3) = niter < opt.niter_term;\n if any(test==0)\n break\n end\nend\n\nif opt.verbose\n onoff = {'YES','no'};\n fprintf( ' Levenberg-Marquardt finished succesfully.\\n Reason for termination:\\n' );\n fprintf( ' lambda = %s\\n', onoff{test(1)+1} );\n fprintf( ' drmsrel = %s\\n', onoff{test(2)+1} );\n fprintf( ' niter = %s\\n', onoff{test(3)+1} );\nend\n\nreturn\n\n\n\nfunction print_statistics(niter,loglambda,e0,w0,e,w,opt)\nif opt.verbose\n ssd0 = sum( (e0.*w0).^2 );\n ssd = sum( (e.*w).^2 );\n fprintf( '%4i : [loglambda=%3i] [rms=%14.12g] [maxabs=%14.12g] [drmsrel=%11.5g]\\n',...\n niter,...\n round(loglambda),...\n sqrt(ssd/length(e)),...\n max(abs(e.*w)),...\n sqrt(1-ssd/ssd0) );\nend\nreturn\n\n", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_multiview/vgg_line3d_from_lP_nonlin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6386570736436787}} {"text": "function phiFaceAverage = tvdMean2D(phi, u, FL)\n% This function gets the value of the field variable phi defined\n% over the MeshStructure and calculates the TVD average on\n% the cell faces, based on the direction of the velocity vector for a uniform mesh.\n%\n% SYNOPSIS:\n%\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% Written by Ali A. Eftekhari\n% See the license file\n\n% extract the velocity data\n% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]\nux = u.xvalue;\nuy = u.yvalue;\n\n% check the size of the variable and the mesh dimension\nNx = u.domain.dims(1);\nNy = u.domain.dims(2);\ndx=repmat(0.5*(u.domain.cellsize.x(1:end-1)+u.domain.cellsize.x(2:end)), 1, Ny);\ndy=repmat(0.5*(u.domain.cellsize.y(1:end-1)+u.domain.cellsize.y(2:end))', Nx, 1);\n\n%\nphiX_p = zeros(Nx+1,Ny);\nphiX_m = zeros(Nx+1,Ny);\nphiY_p = zeros(Nx,Ny+1);\nphiY_m = zeros(Nx,Ny+1);\n\n% calculate the upstream to downstream gradient ratios for u>0 (+ ratio)\n% x direction\ndphiX_p = (phi.value(2:Nx+2, 2:Ny+1)-phi.value(1:Nx+1, 2:Ny+1))./dx;\nrX_p = dphiX_p(1:end-1,:)./fsign(dphiX_p(2:end,:));\nphiX_p(2:Nx+1,:) = phi.value(2:Nx+1, 2:Ny+1)+0.5*FL(rX_p).* ...\n (phi.value(3:Nx+2,2:Ny+1)-phi.value(2:Nx+1, 2:Ny+1));\nphiX_p(1, :) = (phi.value(1, 2:Ny+1)+phi.value(2, 2:Ny+1))/2; % left boundary\n% y direction\ndphiY_p = (phi.value(2:Nx+1, 2:Ny+2)-phi.value(2:Nx+1, 1:Ny+1))./dy;\nrY_p = dphiY_p(:,1:end-1)./fsign(dphiY_p(:,2:end));\nphiY_p(:,2:Ny+1) = phi.value(2:Nx+1, 2:Ny+1)+0.5*FL(rY_p).* ...\n (phi.value(2:Nx+1,3:Ny+2)-phi.value(2:Nx+1, 2:Ny+1));\nphiY_p(:,1) = (phi.value(2:Nx+1,1)+phi.value(2:Nx+1,2))/2; % Bottom boundary\n\n% calculate the upstream to downstream gradient ratios for u<0 (- ratio)\n% x direction\nrX_m = dphiX_p(2:end,:)./fsign(dphiX_p(1:end-1,:));\nphiX_m(1:Nx,:) = phi.value(2:Nx+1, 2:Ny+1)+0.5*FL(rX_m).* ...\n (phi.value(1:Nx, 2:Ny+1)-phi.value(2:Nx+1, 2:Ny+1));\nphiX_m(Nx+1,:) = (phi.value(end, 2:Ny+1)+phi.value(end-1, 2:Ny+1))/2; % right boundary\n% y direction\nrY_m = dphiY_p(:,2:end)./fsign(dphiY_p(:,1:end-1));\nphiY_m(:,1:Ny) = phi.value(2:Nx+1, 2:Ny+1)+0.5*FL(rY_m).* ...\n (phi.value(2:Nx+1, 1:Ny)-phi.value(2:Nx+1, 2:Ny+1));\nphiY_m(:, Ny+1) = (phi.value(2:Nx+1, end)+phi.value(2:Nx+1, end-1))/2; % top boundary\n\n\n% calculate the average value\nxvalue = (ux>0).*phiX_p+ ...\n (ux<0).*phiX_m+ ...\n 0.5*(ux==0).*(phi.value(1:Nx+1,2:Ny+1)+phi.value(2:Nx+2,2:Ny+1));\nyvalue = (uy>0).*phiY_p+ ...\n (uy<0).*phiY_m+ ...\n 0.5*(uy==0).*(phi.value(2:Nx+1,1:Ny+1)+phi.value(2:Nx+1,2:Ny+2));\nphiFaceAverage=FaceVariable(phi.domain, xvalue, yvalue, []);\nend\n\nfunction phi_out = fsign(phi_in)\n% This function checks the value of phi_in and assigns an eps value to the\n% elements that are less than or equal to zero, while keeping the signs of\n% the nonzero elements\n phi_out = (abs(phi_in)>=eps).*phi_in+eps*(phi_in==0)+eps*(abs(phi_in) tol*e && cnt < maxiter\n e0 = e;\n Sx = S(x);\n if nnz(Sx) == 0\n Sx = rand(size(Sx));\n end\n e = norm(Sx);\n x = St(Sx);\n x = x/norm(x);\n cnt = cnt+1;\n end\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/NESTA-1.1/Misc/my_normest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.638614513338069}} {"text": "function I = mi_mixture_gd_vec(x, y, Ym)\n% MI_MIXTURE_GD_VEC Vectorized MI calculation between multiple Gaussian variables \n% and a common discrete variable in bits from Gaussian mixture. \n% I = mi_mixture_gd_vec(x,y,Ym) returns the MI between the (possibly multidimensional)\n% Gaussian variables x and the discrete variable y.\n% size(x) = [Ntrl Nvec Ndim]\n% so each output I(i) = mi_mixture_gd(squeeze(x(:,i,:)), y, Ym);\n%\n% y should contain integer values in the range [0 Ym-1] (inclusive).\n%\n% biascorrect : true / false option (default true) which specifies whether\n% bias correction should be applied to the esimtated MI.\n% demeaned : false / true option (default false) which specifies whether the\n% input data already has zero mean (true if it has been copula-normalized)\n% See also: MI_MIXTURE_GD, MI_MODEL_GD_VEC\n\n% ensure samples first axis for vectors\nif isvector(x)\n x = x(:);\nend\nif ndims(x)>3\n error('mi_model_gd: input arrays should be 3d')\nend\nif isvector(y)\n y = y(:);\nelse\n error('mi_model_gd: only univariate discrete variable supported');\nend\n\nNtrl = size(x,1);\nNvec = size(x,2);\nXdim = size(x,3);\n\nif size(y,1) ~= Ntrl\n error('mi_model_gd: number of trials do not match');\nend\n\n\nI = zeros(Nvec,1);\n\n% y = y-1;\n% for vi=1:Nvec\n% I(vi) = mi_model_gd(squeeze(x(:,vi,:)),y,Ym,true,true);\n% end\n% \n% return\n\n% one-hot encoding of Y\nYhot = indexed2boolean(y);\n\n% remove class means\n[Xcen class_means] = removeclassmeans(x, Yhot);\n\n% allocate memory for class-conditional entropies and covariances\nNtrl_y = sum(Yhot);\nHcond = zeros(Nvec,Ym);\nCm = zeros(Nvec,Xdim,Xdim,Ym);\n\n\nfor vi1=1:Xdim\n % all voxels for this dimension\n x1 = Xcen(:,:,vi1);\n for yi=1:Ym\n tmp = x1(Yhot(:,yi),:);\n Cm(:,vi1,vi1,yi) = sum(tmp.^2);\n end\n\n for vi2=(vi1+1):Xdim\n x2 = Xcen(:,:,vi2);\n for yi=1:Ym\n tmp = transpose(sum(x1(Yhot(:,yi),:).*x2(Yhot(:,yi),:)));\n Cm(:,vi1,vi2,yi) = tmp;\n Cm(:,vi2,vi1,yi) = tmp;\n end\n end\nend\n\n\nfor yi=1:Ym\n Cm(:,:,:,yi) = Cm(:,:,:,yi) / (Ntrl_y(yi) - 1);\n Cm(:,:,:,yi) = vecchol(Cm(:,:,:,yi));\n for vi=1:Xdim\n Hcond(:,yi) = Hcond(:,yi)+log(Cm(:,vi,vi,yi));\n end\nend\n% class weights\nw = Ntrl_y ./ Ntrl;\n% normalise entropy properly\nHcond = Hcond + 0.5*Xdim*(log(2*pi)+1);\n\n% mixture entropy via unscented transform\n% See:\n% Huber, Bailey, Durrant-Whyte and Hanebeck\n% \"On entropy approximation for Gaussian mixture random vectors\"\n% http://dx.doi.org/10.1109/MFI.2008.4648062\n%\n% Goldberger, Gordon, Greenspan\n% \"An efficient image similarity measure based on approximations of \n% KL-divergence between two Gaussian mixtures\"\n% http://dx.doi.org/10.1109/ICCV.2003.1238387\n\nD = Xdim;\nDs = sqrt(Xdim);\nHmix = zeros(Nvec,1);\nchC = Cm;\n\nm = reshape(class_means,[Nvec Xdim Ym]);\nfor yi=1:Ym\n % vector transpose\n Ps = Ds * permute(chC(:,:,:,yi), [1 3 2]);\n % unscented points for this class\n usc = cat(3,bsxfun(@plus,Ps,m(:,:,yi)), bsxfun(@minus,m(:,:,yi),Ps));\n \n % class log-likelihoods at unscented points\n log_lik = zeros(Ym,Nvec,2*Xdim);\n for mi=1:Ym\n % demean points\n dx = bsxfun(@minus,usc,m(:,:,mi));\n % gaussian likelihood\n log_lik(mi,:,:) = bsxfun(@minus,norm_innerv(dx, chC(:,:,:,mi)), Hcond(:,mi)) + 0.5*Xdim;\n end\n % log mixture likelihood for these unscented points\n logmixlik = maxstar(log_lik, w);\n % add to entropy estimate\n Hmix = Hmix + w(yi)*sum(logmixlik,2);\nend\nHmix = -Hmix/(2*D);\n\n% compute mutual information\nI = Hmix - Hcond*w';\n\n% convert to bits\nI = I / log(2);\n\nfunction [Xcen, class_means] = removeclassmeans(X, design)\n[Ntrl, Nvec, Ndim] = size(X);\nXcen = X(:,:);\nclass_means = zeros(Nvec*Ndim,size(design,2));\nfor k = 1:size(design,2)\n sel = design(:,k);\n tmp = Xcen(sel,:);\n class_means(:,k) = mean(tmp,1);\n Xcen(sel,:) = bsxfun(@minus,tmp,class_means(:,k).');\nend\nXcen = reshape(Xcen,[Ntrl Nvec Ndim]);\n\nfunction Y = indexed2boolean(X)\nuX = unique(X);\nY = false(numel(X),numel(uX));\nfor k = 1:size(Y,2)\n Y(X==uX(k),k) = true;\nend\n\nfunction w = norm_innerv(x, chC)\n% normalised innervations\nNvec = size(chC,1);\nw = zeros(Nvec,size(x,3));\nfor vi=1:Nvec\n m = (squeeze(chC(vi,:,:))')\\(squeeze(x(vi,:,:)));\n w(vi,:) = -0.5 *sum(m.*m,1);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/gcmi/mi_mixture_gd_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6385839047523509}} {"text": "% system process model in ecef frame with dcm formulation, Cse is the \n% transformation between the sensor and e-frame, with the assumption that\n% the sensor is also the body frame, we have Cse=Cbe.\n%implement this function as sys_llh_phipsi_v000\nfunction [STM Qd]=sys_ecef_dcm_v001(xyz_imu, Cse, acc, gyro, dt, imutype, modelNo)\n% for modelNo=5 and imutype=5\n% position (1-3)\n% velocity (4-6)\n% attitude (7-9) \n% acc bias drift\n% gyro bias drift\n% acc scale factor\n% gyro scale factor\n% acc turn on bias\n% gyro turn on bias\n% for modelNo=1 and imutype=5 the acc and gyro turn on bias are removed\nWIE_E=7292115e-11; %Earth rotation rate\ng = 9.7803267714; % nominal g on earth surface\nR=6317000; % earth average radius\n%system disturbance coefs\nN=zeros(9,6);\nN(7:9,4:6)=-Cse; %attitude\nN(4:6,1:3)=Cse; %velocity\n\n%system matrix\nA=zeros(9);\nacc_e=Cse*acc;\n\n%Position\nA(1,4)=1;\nA(2,5)=1;\nA(3,6)=1;\n\n%Velocity\nunit=xyz_imu/norm(xyz_imu,2);\nA(4:6,1:3)=-g*R^2/norm(xyz_imu,2)^3*(eye(3)-3*(unit*unit'))-skew([0;0;WIE_E])*skew([0;0;WIE_E]);\nA(4:6,4:6)=-2*skew([0;0;WIE_E]);\nA(4:6,7:9)=skew(acc_e);\n\n%Attitude\nA(7:9,7:9)=-skew([0;0;WIE_E]);\nAnav=A;\nNnav=N;\n% X(k+1) = ffun[X(k),U(k),V(k)]\n% X(k+1) = Ak*X(k)+Gk*Vk\n\n%%%%Imu error model parameters\n[Aimu_d, Qimu_d, Cimu, Rimu]=imu_err_model_v001(acc, gyro, dt, imutype, modelNo);\n\n%%%%Combine and discretize nav and imu models\n% this discretization can also be accomplished by Loan's matrix exponential\n% method, see sys_metric_phipsi_v000.m\nAnav_d=eye(9)+dt*Anav; %Use 1st order taylor series to discretize Anav\nQnav=Nnav*Rimu*Nnav';\nQnav_d=dt/2*(Anav_d*Qnav+Qnav*Anav_d'); %Use trapezoidal rule to discretize Rimu\n\nSTM=zeros(9+size(Aimu_d,1));\nSTM(1:9,1:9)=Anav_d;\nSTM(1:9,10:end)=Nnav*Cimu*dt;\nSTM(10:end,10:end)=Aimu_d;\n\nQd=zeros(9+size(Aimu_d,1));\nQd(1:9,1:9)=Qnav_d;\nQd(10:end,10:end)=Qimu_d;\nQd(1:9,10:end)=Nnav*Cimu*Qimu_d*dt/2;\nQd(10:end,1:9)=Qd(1:9,10:end)';\nend\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/propagation/sys_ecef_dcm_v001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6385617680835055}} {"text": "function c=ref_fcdgt(f,g,a,M,m_t,m_f,w_t,w_f)\n%REF_CDGT Reference centered DGT\n% Usage: c=ref_dgtiv(f,g,a,M,c_t,c_f,c_w);\n%\n% Linear algebra version of the algorithm. Create big matrix\n% containing all the basis functions and multiply with the transpose.\n%\n% For easy work, m_t,m_f,w_t,w_f are all just 0/1 indicator variables.\n\nL=size(f,1);\nN=L/a;\nb=L/M;\n\nm_t=m_t*.5;\nw_t=w_t*floor(a/2);\nw_f=w_f*ceil(b/2);\n\n\nF=zeros(L,M*N);\n\nl=(0:L-1).';\n\nif m_f==0\n\n for n=0:N-1\t \n for m=0:M-1\n F(:,M*n+m+1)=exp(2*pi*i*(m*b+w_f)*(l+m_t)/L).*circshift(g,n*a+w_t);\n end;\n end;\n\nelse\n\n for n=0:N-1\t \n for m=0:M-1\n F(:,M*n+m+1)=exp(2*pi*i*(m*b+.5+w_f)*(l+m_t-n*a)/L).*circshift(g,n*a+w_t);\n end;\n end;\n\n\nend;\n\nc=F'*f;\n\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_fcdgt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6384928357929301}} {"text": "% ct_beta_study\n% study how to adjust beta when pixel size changes in X-ray CT recon.\n% results:\n% changing nx has neglible effect, as expected\n% changing pixel size has minimal effect when fwhm is converted to mm!\n% values used CT studies:\n% l2b=9, fov=500, fwhm = 1.62 mm\n% l2b=9, fov=250, fwhm = 1.63 mm\n% so we can use the same beta regardless of pixel size and get nearly same fwhm\n% caution: if other factors change, such as the # of views, may need to revisit!\n\n%nx = 256;\n%nx = 128;\nnx = 64;\nny = nx;\n\nif ~isvar('R')\n\tmask = true(nx,ny);\n\tl2b = 9;\n\tR = Robject(mask, 'edge_type', 'tight', 'beta', 2^l2b);\nend\n\npixel_size_list = [500/512 250/512 0.25];\nfor ii=1:length(pixel_size_list)\n\tpixel_size = pixel_size_list(ii);\n\n\tsys = ct_sys('nx', nx, 'ny', ny, 'pixel_size', pixel_size);\n\n\tG = Gtomo2_dscmex(sys, 'nthread', 2);\n\n%\tpsf = qpwls_psf(G, C, 2^l2b, mask, 1);\n\tpsf = qpwls_psf(G, R, 1, mask, 1);\n\tfwhm = fwhm2(psf);\n\tprintf('fwhm in mm = %g', fwhm * pixel_size)\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/ct/ct_beta_study.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7057850216484839, "lm_q1q2_score": 0.6384887975004945}} {"text": "function [LMTRad,LMT1,LMT2]=TT2LMT(TT1,TT2,rObsITRS,deltaT,xpyp)\n%%TT2LMT Convert from terrestrial time to local mean solar time (LMT). This\n% is a measure of the time at a place on the Earth given the mean\n% location of the Sun, not a high-precision ephemeris.\n%\n%INPUTS: Jul1,Jul2 Two parts of a Julian date given in TT. The\n% units of the date are days. The full date is the sum of\n% both terms. The date is broken into two parts to\n% provide more bits of precision. It does not matter how\n% the date is split.\n% rObsITRS The 3X1 location of the observer in the International\n% Terrestrial Reference System (ITRS). Only the direction\n% matters, not the magnitude.\n% deltaT An optional parameter specifying the offset between TT\n% and UT1 in seconds. If this parameter is omitted or if\n% an empty matrix is passed, then the value of the\n% function getEOP will be used.\n% xpyp xpyp=[xp;yp] are the polar motion coordinates in radians\n% including the effects of tides and librations. If this\n% parameter is omitted or if an empty matrix is passed,\n% the value from the function getEOP will be used.\n%\n%OUTPUTS: LMTRad The local apparent solar time in radians. 0 radians is\n% solar midnight. pi radians is solar noon. The mapping is\n% is 2*pi radians for 24 hours. Thus, LATRad*(24/(2*pi))\n% gives the time of day in hours.\n% LMT1,LMT2 Two parts of the local mean solar time in Julian days. The\n% date is split so that LMT1 is the integer part and LMT2 is\n% the fractional part. Like UT1, a zero fractional part of\n% the day corresponds to noon, not midnight.\n%\n%The local mean solar time is UT1 plus the East longitude of the observer\n%in radians in the Terrestrial Intermediate Reference System (TIRS). The\n%East longitude is added using the convention that 360 degrees equals 24\n%hours of 60 minutes and 60 seconds. For LMT in radians, an additional 12\n%hours (pi radians) is added to adhere to the convention that 0 hours/ 0\n%radians is midnight, not noon.\n%\n%The use of UT1 as a definition of Greenwhich mean solar time is given in\n%[1]. Since UT1 is defined as a rotation in the TIRS, it only makes sense\n%that a local mean solar time is defined by using the longitude offset in\n%the TIRS.\n%\n%REFERENCES:\n%[1] D. D. McCarthy, \"Evolution of timescales from astronomy to physical\n% metrology,\" Metrologia, vol. 48, no. 4, pp. S132-S144, Aug. 2011.\n%\n%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Get any Earth orientation parameters that were not provided.\nif(nargin<5||isempty(deltaT)||isempty(xpyp))\n [UTC1,UTC2]=TT2UTC(TT1,TT2);\n [xpypNew,~,~,deltaTTUT1]=getEOP(UTC1,UTC2);\n \n if(nargin<4||isempty(deltaT))\n deltaT=deltaTTUT1;\n end\n \n if(nargin<5||isempty(xpyp))\n xpyp=xpypNew;\n end\nend\n\n[UT11,UT12]=TT2UT1(TT1,TT2,deltaT);\nrObsTIRS=ITRS2TIRS(rObsITRS,TT1,TT2,xpyp);\nrObsSphere=Cart2Sphere(rObsTIRS);\n\n%2*pi radians per day.\ndeltaUT1=rObsSphere(2)/(2*pi);\n\n%Add preserving precision.\nif(UT11.\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\ngps_start_datenum = 723186; %This is datenum([1980,1,6,0,0,0])\n\ngps_dow = fix(gps_sow/86400); %day of week\ndate = datevec(gps_start_datenum + 7*gps_week + gps_dow); %calendar date up to days\ngps_sod = gps_sow - gps_dow*86400; %seconds of day\ndate(:,4) = floor(gps_sod/3600); %hours\ndate(:,5) = floor(gps_sod/60 - date(:,4)*60); %minutes\ndate(:,6) = gps_sod - date(:,4)*3600 - date(:,5)*60; %seconds\n\n%day of year (DOY)\nif (nargout > 1)\n doy = date2doy(datenum(date));\n doy = floor(doy);\nend\n\n%day of week\nif (nargout > 2)\n dow = gps_dow;\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/time/gps2date.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6383516727009029}} {"text": "function binomial_test ( )\n\n%*****************************************************************************80\n%\n%% BINOMIAL_TEST tests BINOMIAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BINOMIAL_TEST:\\n' );\n fprintf ( 1, ' A demonstration of the binomial method\\n' );\n fprintf ( 1, ' for option valuation.\\n' );\n\n s0 = 2.0;\n e = 1.0;\n r = 0.05;\n sigma = 0.25;\n t1 = 3.0;\n m = 256;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The asset price at time 0, S0 = %f\\n', s0 );\n fprintf ( 1, ' The exercise price E = %f\\n', e );\n fprintf ( 1, ' The interest rate R = %f\\n', r );\n fprintf ( 1, ' The asset volatility SIGMA = %f\\n', sigma );\n fprintf ( 1, ' The expiry date T1 = %f\\n', t1 );\n fprintf ( 1, ' The number of intervals M = %d\\n', m );\n\n c = binomial ( s0, e, r, sigma, t1, m );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The option value is %f\\n', c );\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/black_scholes/binomial_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6381869613948316}} {"text": "function y = sfb3D(lo, hi, sf1, sf2, sf3)\n\n% 3D Synthesis Filter Bank\n%\n% USAGE:\n% y = sfb3D(lo, hi, sf1, sf2, sf3);\n% INPUT:\n% lo, hi - lowpass subbands\n% sfi - synthesis filters for dimension i\n% OUPUT:\n% y - output array\n% See afb3D\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\nif nargin < 4\n sf2 = sf1;\n sf3 = sf1;\nend\n\nLLL = lo;\nLLH = hi{1};\nLHL = hi{2};\nLHH = hi{3};\nHLL = hi{4};\nHLH = hi{5};\nHHL = hi{6};\nHHH = hi{7};\n\n% filter along dimension 3\nLL = sfb3D_A(LLL, LLH, sf3, 3);\nLH = sfb3D_A(LHL, LHH, sf3, 3);\nHL = sfb3D_A(HLL, HLH, sf3, 3);\nHH = sfb3D_A(HHL, HHH, sf3, 3);\n\n% filter along dimension 3\nL = sfb3D_A(LL, LH, sf2, 2);\nH = sfb3D_A(HL, HH, sf2, 2);\n\n% filter along dimension 1\ny = sfb3D_A(L, H, sf1, 1);\n\n\n% LOCAL FUNCTION\n\nfunction y = sfb3D_A(lo, hi, sf, d)\n\n% 3D Synthesis Filter Bank\n% (along single dimension only)\n%\n% y = sfb3D_A(lo, hi, sf, d);\n% sf - synthesis filters\n% d - dimension of filtering\n% see afb2D_A\n\nlpf = sf(:, 1); % lowpass filter\nhpf = sf(:, 2); % highpass filter\n\n% permute dimensions of lo and hi so that dimension d is first.\np = mod(d-1+[0:2], 3) + 1;\nlo = permute(lo, p);\nhi = permute(hi, p);\n\n[N1, N2, N3] = size(lo);\nN = 2*N1;\nL = length(sf);\ny = zeros(N+L-2, N2, N3);\n\nfor k = 1:N3\n y(:, :, k) = upfirdn(lo(:, :, k), lpf, 2, 1) + upfirdn(hi(:, :, k), hpf, 2, 1);\nend\ny(1:L-2, :, :) = y(1:L-2, :, :) + y(N+[1:L-2], :, :);\ny = y(1:N, :, :);\ny = cshift3D(y, 1-L/2, 1);\n\n% permute dimensions of y (inverse permutation)\ny = ipermute(y, p);\n\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/DTCWT/sfb3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6381869566226075}} {"text": "function N = tangentspacefactory(M, x)\n% Returns a manifold structure representing the tangent space to M at x.\n%\n% N = tangentspacefactory(M, x)\n%\n% N defines a (linear) manifold that is the tangent space to M at x. Points\n% are represented as tangent vectors to M at x. Tangent vectors are also\n% represented as tangent vectors to M at x.\n%\n% This is chiefly useful to solve optimization problems involving tangent\n% vectors to M at x, which notably comes up when solving linear systems\n% involving, for example, the Hessian of the cost on M at x (think of the\n% Newton equations.) The Riemannian (actually, Euclidean) structure on N is\n% that of the tangent space to M, that is, the inner product is inherited.\n%\n% See also: preconhessiansolve\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, April 9, 2015.\n% Contributors: \n% Change log: \n%\n% Jan. 25, 2017 (NB):\n% Following a comment by Jesus Briales on the Manopt forum, the\n% functions N.egrad2rgrad, N.ehess2rhess and N.tangent now include a\n% projection (they were formerly identities.)\n%\n% Feb. 2, 2017 (NB):\n% Following a comment by Jesus Briales on the Manopt forum, the\n% function N.proj now calls M.proj(x, .) instead of M.proj(y, .).\n% Furthermore, N.ehess2rhess was corrected in the same way.\n%\n% Dec. 14, 2019 (NB):\n% Fixed N.tangent so that it should now work with factories that\n% have a non-identity tangent2ambient, e.g., fixedrankembeddedfactory\n% and rotationsfactory.\n\n % N is the manifold we build. y will be a point on N, thus also a\n % tangent vector to M at x. This is a typical Euclidean space, hence it\n % will be easy to describe in terms of the tools available for M.\n N = struct();\n \n % u, u1 and u2 will be tangent vectors to N at y. The tangent space to\n % N at y is the tangent space to M at x, thus u, u1 and u2 are also\n % tangent vectors to M at x.\n \n if isfield(M, 'name')\n N.name = @() ['Tangent space to ' M.name()];\n end\n N.dim = @() M.dim();\n N.inner = @(y, u1, u2) M.inner(x, u1, u2);\n N.norm = @(y, u) M.norm(x, u);\n N.proj = @(y, u) M.proj(x, u);\n N.typicaldist = @() sqrt(N.dim());\n if isfield(M, 'tangent2ambient')\n N.tangent = @(y, u) M.proj(x, M.tangent2ambient(x, u));\n else\n N.tangent = N.proj;\n end\n \n N.egrad2rgrad = N.proj;\n N.ehess2rhess = @(y, eg, eh, d) M.proj(x, eh);\n N.exp = @exponential;\n N.retr = @exponential;\n N.log = @(y1, y2) M.lincomb(x, 1, y2, -1, y1);\n N.pairmean = @(y1, y2) M.lincomb(x, 0.5, y1, 0.5, y2);\n N.rand = @() M.randvec(x);\n N.randvec = @(y) M.randvec(x);\n N.zerovec = M.zerovec;\n N.lincomb = M.lincomb;\n N.transp = @(y1, y2, u) u;\n N.hash = @(y) ['z' hashmd5(M.vec(x, y))];\n \n % In a Euclidean space, the exponential is merely the sum: y + tu.\n function yy = exponential(y, u, t)\n if nargin == 2\n t = 1;\n end\n yy = M.lincomb(x, 1, y, t, u);\n end\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/tools/tangentspacefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.638092138108574}} {"text": "clear;\nclc;\nclose all;\nformat\n\n%% 参考: https://x-io.co.uk/oscillatory-motion-tracking-with-x-imu/\n\n% 利用速度,位置高通滤波来获得短时位移曲线\n\n%load filter_vel.mat\n% load example_ins4.mat\n\ndata = ch_data_import('data_20210609_163153.csv');\nacc = data.imu.acc*9.8;\ngyr = deg2rad(data.imu.gyr);\n%% 读取数据\nacc = acc';\ngyr = gyr';\n\nq= [1 0 0 0]';\n\nFs = 100; \ndt = 1 / Fs;\nN = length(acc);\n\nfprintf(\"共%d数据,用时:%.3fs\\n\", N, N/Fs);\n\n\n% 惯导解算, 初始化\np = zeros(3, 1);\nv = zeros(3, 1);\nlinVel = zeros(N,3);\n\nfor i=1:N\n [p , v , q] = ch_nav_equ_local_tan(p, v, q, acc(i,:)', gyr(i,:)', 1 / Fs, [0, 0, -9.8]');\n \n % 获得惯性系下加速度并扣除重力\n linAcc(i,:) = ch_qmulv(q, acc(i,:));\n linAcc(i,3) = linAcc(i,3) -9.8;\n \n% linVel(i,:) = v;\nend\n \n% 速度积分\n\nfor i = 2:N\n linVel(i,:) = linVel(i-1,:) + linAcc(i,:) * dt;\nend\n\n\norder = 1;\nfiltCutOff = 0.01;\n[b, a] = butter(order, (2*filtCutOff)/(1/dt), 'high');\n%linVelHP = filtfilt(b, a, linVel);\nlinVelHP = filter(b, a, linVel);\n\n% 位置积分\nlinPos = zeros(size(linVelHP));\nfor i = 2:length(linVelHP)\n linPos(i,:) = linPos(i-1,:) + linVelHP(i,:) * dt;\nend\n\norder = 1;\nfiltCutOff = 0.5;\n[b, a] = butter(order, (2*filtCutOff)/(1/dt), 'high');\n%linPosHP = filtfilt(b, a, linPos);\nlinPosHP = filter(b, a, linPos);\n\n\n%% Plot\nfigure('NumberTitle', 'off', 'Name', '速度');\nsubplot(2,1,1);\nplot(linVel);\ntitle('速度');\nlegend('X', 'Y', 'Z');\nsubplot(2,1,2);\nplot(linVelHP);\ntitle('HP后速度');\nlegend('X', 'Y', 'Z');\n\n\nfigure('NumberTitle', 'off', 'Name', '位置');\nsubplot(2,1,1);\nplot(linPos);\ntitle('位置');\nlegend('X', 'Y', 'Z');\nsubplot(2,1,2);\nplot(linPosHP);\ntitle('HP后位置');\nlegend('X', 'Y', 'Z');\n\n\nfigure('NumberTitle', 'off', 'Name', '原始数据');\nsubplot(2,1,1);\nplot(acc);\nlegend(\"X\", \"Y\", \"Z\");\ntitle(\"加速度\");\nsubplot(2,1,2);\nplot(gyr);\ntitle(\"陀螺\");\nlegend(\"X\", \"Y\", \"Z\");\n\n\nfigure('NumberTitle', 'off', 'Name', '3D位置');\nplot3(linPosHP(1,1), linPosHP(1,2), linPosHP(1,3), '-ks');\nhold on;\nplot3(linPosHP(:,1), linPosHP(:,2), linPosHP(:,3), '.b');\naxis equal\nxlabel('X(m)'); ylabel('Y(m)'); zlabel('Z(m)'); \ntitle('3D位置');\nlegend('起始', '3D');\n\n\n\nlinPosHP(end,:)\n\n% SamplePlotFreq = 4;\n% \n% SixDOFanimation(linPosHP, R, ...\n% 'SamplePlotFreq', SamplePlotFreq, 'Trail', 'Off', ...\n% 'Position', [9 39 400 400], ...\n% 'AxisLength', 0.1, 'ShowArrowHead', false, ...\n% 'Xlabel', 'X (m)', 'Ylabel', 'Y (m)', 'Zlabel', 'Z (m)', 'ShowLegend', false, 'Title', 'Unfiltered',...\n% 'CreateAVI', false, 'AVIfileNameEnum', false, 'AVIfps', ((1/dt) / SamplePlotFreq)); \n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/ins_test/example_ins5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6380493606927772}} {"text": "function qr = rightQuaternionProductMatrix(q)\n% q 4x1 w,x,y,z\n% p * q = rightQuaternionProductMatrix(q) * p\n% eq 18 in Sola Quaternion kinematics for the error-state Kalman filter\nw = q(1);\nx = q(2);\ny = q(3);\nz = q(4);\nqr = [w, -x, -y, -z; \n x, w, z, -y;\n y, -z, w, x;\n z, y, -x, w];\nend\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/kinematics/rightQuaternionProductMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6380493465814906}} {"text": "function [lat2,lon2,derr,aerr]=vdistinv(lat1,lon1,dist,azim)\n% VDISTINV - Invert VDIST function using numerical inversion\n%\n% Usage:\n%\n% [lat2,lon2] = vdistinv(lat1,lon1,dist,azim)\n% [lat2,lon2,derr,aerr] = vdistinv(lat1,lon1,dist,azim)\n%\n% Variables:\n%\n% lat1, lon1 = coordinates of intial point in degrees\n% dist = geodesic distance in meters\n% azim = geodesic azimuth in degrees clockwise from north\n% lat2,lon2 = destination coordinates in degrees\n% derr = optional output: error between input distance and the\n% calculated length of the path to the computed endpoint\n% (as computed by VDIST)\n% aerr = optional output: error between the provided azimuth and the\n% calculated azimuth (as computed by VDIST)\n%\n% Notes: (1) This \"quick and dirty\" approach was written in response to\n% a user request. The use of a numerical optimization to invert\n% VDIST is a relatively slow and crude approach. (It would be\n% better to implement an algorithm written specifically for that\n% purpose by Vincenty or others.)\n% (2) The distance between essentially antipodal points on an\n% ellipsoid is very sensitive to small deviations in azimuth,\n% so such points should be avoided. (A warning is given.)\n% (3) For other cases, precision is set to about one part in 10^12\n% (3) Tested but no warranty; use at your own risk.\n% (4) Written by Michael Kleder, April 2006\n%\n% Example:\n% >> [dist,azim]=vdist(10,20,30,40)\n% dist = 3035728.95690893\n% azim = 40.3196402221127\n% >> [lat2,lon2]=vdistinv(10,20,dist,azim)\n% lat2 = 29.9999999999981\n% lon2 = 39.9999999999979\n% >>\n\n% initial guess for path endpoint is computed using spherical earth trig:\nt1=lat1*0.0174532925199433; % degrees to radians\nn1=lon1*0.0174532925199433; % degrees to radians\na=azim*0.0174532925199433; % degrees to radians\nd=dist*1.56961230576048e-007; % meters to radians\nlat2 = asin(sin(t1)*cos(d)+cos(t1)*sin(d)*cos(a));\nlon2 = n1+atan2(sin(d)*sin(a),cos(t1)*cos(d)-sin(t1)*sin(d)*cos(a));\nX=[lat2;lon2]*57.2957795130823; % radians to dgrees\n% other parameters (start point, arc length, and azimuth) are fixed:\nparams=[lat1;lon1;dist;azim];\n% optimization control settings:\nopt=optimset('MaxFunEvals',5000,'TolFun',1e-12);\n% solve for accurate end point:\nX=fminsearch(@tryone,X,opt,params);\n% recover coordinates of endpoint:\nlat2=X(1);\nlon2=X(2);\nif nargout > 2 % if error data is requested\n % compute distance and azimuth from startpoint to endpoint\n [d,a] = vdist(lat1,lon1,lat2,lon2);\n % error in distance:\n derr=abs(dist-d);\n % error in azimuth:\n azim = mod(azim,360);\n a = mod(a,360);\n aerr = abs(azim-a);\n aerr = min(aerr,abs(360-aerr));\nend\nreturn\nfunction err=tryone(X,params)\nlat2=X(1);\nlon2=X(2);\nlat1=params(1);\nlon1=params(2);\ndist=params(3);\nazim=params(4);\n% crude catch for out-of-bounds attempts:\nif lat1<-90 || lat1 > 90 || lat2 < -90 || lat2 > 90\n err = 1e6;\n return\nend\n[trydist,tryazim]=vdist(lat1,lon1,lat2,lon2);\n% compute overall error. First convert distance to approximate arc length\n% in degrees so as to weight the terms reasonably closely. (Both move to\n% zero in the optimization, but reasonably balancing the units can help.)\nerr = sqrt((9e-6*(dist-trydist))^2 + (azim-tryazim)^2);\nreturn\nfunction varargout = vdist(lat1,lon1,lat2,lon2)\n% VDIST - Using the WGS-84 Earth ellipsoid, compute the distance between\n% two points within a few millimeters of accuracy, compute forward\n% azimuth, and compute backward azimuth, all using a vectorized\n% version of Vincenty's algorithm.\n%\n% s = vdist(lat1,lon1,lat2,lon2)\n% [s,a12] = vdist(lat1,lon1,lat2,lon2)\n% [s,a12,a21] = vdist(lat1,lon1,lat2,lon2)\n%\n% s = distance in meters (inputs may be scalars, vectors, or matrices)\n% a12 = azimuth in degrees from first point to second point (forward)\n% a21 = azimuth in degrees from second point to first point (backward)\n% (Azimuths are in degrees clockwise from north.)\n% lat1 = GEODETIC latitude of first point (degrees)\n% lon1 = longitude of first point (degrees)\n% lat2, lon2 = second point (degrees)\n%\n% Original algorithm source:\n% T. Vincenty, \"Direct and Inverse Solutions of Geodesics on the Ellipsoid\n% with Application of Nested Equations\", Survey Review, vol. 23, no. 176,\n% April 1975, pp 88-93.\n% Available at: http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n%\n% Notes: (1) lat1,lon1,lat2,lon2 can be any (identical) size/shape. Outputs\n% will have the same size and shape.\n% (2) Error correcting code, convergence failure traps, antipodal\n% corrections, polar error corrections, WGS84 ellipsoid\n% parameters, testing, and comments: Michael Kleder, 2004.\n% (3) Azimuth implementation (including quadrant abiguity\n% resolution) and code vectorization, Michael Kleder, Sep 2005.\n% (4) Vectorization is convergence sensitive; that is, quantities\n% which have already converged to within tolerance are not\n% recomputed during subsequent iterations (while other\n% quantities are still converging).\n% (5) Vincenty describes his distance algorithm as precise to within\n% 0.01 millimeters, subject to the ellipsoidal model.\n% (6) For distance calculations, essentially antipodal points are\n% treated as exactly antipodal, potentially reducing accuracy\n% slightly.\n% (7) Distance failures for points exactly at the poles are\n% eliminated by moving the points by 0.6 millimeters.\n% (8) The Vincenty distance algorithm was transcribed verbatim by\n% Peter Cederholm, August 12, 2003. It was modified and\n% translated to English by Michael Kleder.\n% Mr. Cederholm's website is http://www.plan.aau.dk/~pce/\n% (9) Distances agree with the Mapping Toolbox, version 2.2 (R14SP3)\n% with a max relative difference of about 5e-9, except when the\n% two points are nearly antipodal, and except when one point is\n% near the equator and the two longitudes are nearly 180 degrees\n% apart. This function (vdist) is more accurate in such cases.\n% For example, note this difference (as of this writing):\n% >>vdist(0.2,305,15,125)\n% 18322827.0131551\n% >>distance(0.2,305,15,125,[6378137 0.08181919])\n% 0\n% (10) Azimuths FROM the north pole (either forward starting at the\n% north pole or backward when ending at the north pole) are set\n% to 180 degrees by convention. Azimuths FROM the south pole are\n% set to 0 degrees by convention.\n% (11) Azimuths agree with the Mapping Toolbox, version 2.2 (R14SP3)\n% to within about a hundred-thousandth of a degree, except when\n% traversing to or from a pole, where the convention for this\n% function is described in (10), and except in the cases noted\n% above in (9).\n% (12) No warranties; use at your own risk.\n\n% reshape inputs\nkeepsize = size(lat1);\nlat1=lat1(:);\nlon1=lon1(:);\nlat2=lat2(:);\nlon2=lon2(:);\n% Input check:\nif any(abs(lat1)>90 | abs(lat2)>90)\n error('Input latitudes must be between -90 and 90 degrees, inclusive.')\nend\n% Supply WGS84 earth ellipsoid axis lengths in meters:\na = 6378137; % definitionally\nb = 6356752.31424518; % computed from WGS84 earth flattening coefficient\n% preserve true input latitudes:\nlat1tr = lat1;\nlat2tr = lat2;\n% convert inputs in degrees to radians:\nlat1 = lat1 * 0.0174532925199433;\nlon1 = lon1 * 0.0174532925199433;\nlat2 = lat2 * 0.0174532925199433;\nlon2 = lon2 * 0.0174532925199433;\n% correct for errors at exact poles by adjusting 0.6 millimeters:\nkidx = abs(pi/2-abs(lat1)) < 1e-10;\nif any(kidx);\n lat1(kidx) = sign(lat1(kidx))*(pi/2-(1e-10));\nend\nkidx = abs(pi/2-abs(lat2)) < 1e-10;\nif any(kidx)\n lat2(kidx) = sign(lat2(kidx))*(pi/2-(1e-10));\nend\nf = (a-b)/a;\nU1 = atan((1-f)*tan(lat1));\nU2 = atan((1-f)*tan(lat2));\nlon1 = mod(lon1,2*pi);\nlon2 = mod(lon2,2*pi);\nL = abs(lon2-lon1);\nkidx = L > pi;\nif any(kidx)\n L(kidx) = 2*pi - L(kidx);\nend\nlambda = L;\nlambdaold = 0*lat1;\nitercount = 0;\nnotdone = logical(1+0*lat1);\nalpha = 0*lat1;\nsigma = 0*lat1;\nsinsigma=nan*lat1;\ncossigma=nan*lat1;\ncos2sigmam = 0*lat1;\nC = 0*lat1;\nwarninggiven = false;\nwhile any(notdone) % force at least one execution\n %disp(['lambda(21752) = ' num2str(lambda(21752),20)]);\n itercount = itercount+1;\n if itercount > 50\n if ~warninggiven\n warning('VDIST:antipodal',['Essentially antipodal points ' ...\n 'encountered. Precision may be reduced.']);\n end\n lambda(notdone) = pi;\n break\n end\n lambdaold(notdone) = lambda(notdone);\n sinsigma(notdone) = sqrt((cos(U2(notdone)).*sin(lambda(notdone)))...\n .^2+(cos(U1(notdone)).*sin(U2(notdone))-sin(U1(notdone)).*...\n cos(U2(notdone)).*cos(lambda(notdone))).^2);\n cossigma(notdone) = sin(U1(notdone)).*sin(U2(notdone))+...\n cos(U1(notdone)).*cos(U2(notdone)).*cos(lambda(notdone));\n % eliminate rare imaginary portions at limit of numerical precision:\n sinsigma(notdone)=real(sinsigma(notdone));\n cossigma(notdone)=real(cossigma(notdone));\n sigma(notdone) = atan2(sinsigma(notdone),cossigma(notdone));\n alpha(notdone) = asin(cos(U1(notdone)).*cos(U2(notdone)).*...\n sin(lambda(notdone))./sin(sigma(notdone)));\n cos2sigmam(notdone) = cos(sigma(notdone))-2*sin(U1(notdone)).*...\n sin(U2(notdone))./cos(alpha(notdone)).^2;\n C(notdone) = f/16*cos(alpha(notdone)).^2.*(4+f*(4-3*...\n cos(alpha(notdone)).^2));\n lambda(notdone) = L(notdone)+(1-C(notdone)).*f.*sin(alpha(notdone))...\n .*(sigma(notdone)+C(notdone).*sin(sigma(notdone)).*...\n (cos2sigmam(notdone)+C(notdone).*cos(sigma(notdone)).*...\n (-1+2.*cos2sigmam(notdone).^2)));\n %disp(['then, lambda(21752) = ' num2str(lambda(21752),20)]);\n % correct for convergence failure in the case of essentially antipodal\n % points\n if any(lambda(notdone) > pi)\n warning('VDIST:antipodal',['Essentially antipodal points ' ...\n 'encountered. Precision may be reduced.']);\n warninggiven = true;\n lambdaold(lambda>pi) = pi;\n lambda(lambda>pi) = pi;\n end\n notdone = abs(lambda-lambdaold) > 1e-12;\nend\nu2 = cos(alpha).^2.*(a^2-b^2)/b^2;\nA = 1+u2./16384.*(4096+u2.*(-768+u2.*(320-175.*u2)));\nB = u2./1024.*(256+u2.*(-128+u2.*(74-47.*u2)));\ndeltasigma = B.*sin(sigma).*(cos2sigmam+B./4.*(cos(sigma).*(-1+2.*...\n cos2sigmam.^2)-B./6.*cos2sigmam.*(-3+4.*sin(sigma).^2).*(-3+4*...\n cos2sigmam.^2)));\nvarargout{1} = reshape(b.*A.*(sigma-deltasigma),keepsize);\nif nargout > 1\n % From point #1 to point #2\n % correct sign of lambda for azimuth calcs:\n lambda = abs(lambda);\n kidx=sign(sin(lon2-lon1)) .* sign(sin(lambda)) < 0;\n lambda(kidx) = -lambda(kidx);\n numer = cos(U2).*sin(lambda);\n denom = cos(U1).*sin(U2)-sin(U1).*cos(U2).*cos(lambda);\n a12 = atan2(numer,denom);\n kidx = a12<0;\n a12(kidx)=a12(kidx)+2*pi;\n % from poles:\n a12(lat1tr <= -90) = 0;\n a12(lat1tr >= 90 ) = pi;\n varargout{2} = reshape(a12 * 57.2957795130823,keepsize); % to degrees\nend\nif nargout > 2\n a21=NaN*lat1; %#ok this variable won't be computed if not needed\n % From point #2 to point #1\n % correct sign of lambda for azimuth calcs:\n lambda = abs(lambda);\n kidx=sign(sin(lon1-lon2)) .* sign(sin(lambda)) < 0;\n lambda(kidx)=-lambda(kidx);\n numer = cos(U1).*sin(lambda);\n denom = sin(U1).*cos(U2)-cos(U1).*sin(U2).*cos(lambda);\n a21 = atan2(numer,denom);\n kidx=a21<0;\n a21(kidx)= a21(kidx)+2*pi;\n % backwards from poles:\n a21(lat2tr >= 90) = pi;\n a21(lat2tr <= -90) = 0;\n varargout{3} = reshape(a21 * 57.2957795130823,keepsize); % to degrees\nend\nreturn", "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/10821-vdistinv-find-the-endpoint-of-a-geodesic-on-the-ellipsoidal-earth/vdistinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.638023028318887}} {"text": "function [Xt,Yt] = elec_3d_2d(X,Y,Z,Zrad)\n\n% elec_3d_2d - Project Cartesian 3D coordinates to a 2D plane.\n%\n% [Xt,Yt] = elec_3d_2d(X,Y,Z,Zrad)\n%\n% Project 3D electrode positions onto a 2D plane, using \n% gnomonic projection, which draws a line from a point \n% halfway between equator and south pole, through electrode, \n% to a plane tangential to north pole.\n%\n% Given: Set of 3D Cartesian coordinates (X,Y,Z with Z > 0)\n% X,Y midpoint at 0\n% Zrad is radius in Z\n%\n% See also elec_2d_3d.m\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:54 $\n\n% Licence: GNU GPL, no implied or express warranties\n% History: 10/1999, Chris Harvey\n% 07/2001, Darren.Weber_at_radiology.ucsf.edu\n% - using matrix algebra rather than indexed looping\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nrad = Zrad / 2;\n\nt = (Z + rad) * ( 1/rad );\n\nXt = X .* t;\nYt = Y .* t;\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/elec_3d_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6380230203142828}} {"text": "function R = gqr3 (A)\n%GQR3 QR factorization, based on Givens rotations\n%\n% Example:\n% R = gqr3 (A)\n% See also: testall\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n\n[m n] = size (A) ;\n\n% parent = cs_etree (sparse (A), 'col') ;\n\nfor i = 2:m\n % i\n for k = 1:min(i-1,n)\n % k\n % Givens rotation to zero out A(i,k) using A(k,k)\n G = givens2 (A(k,k), A(i,k)) ;\n A ([k i],k:n) = G * A ([k i],k:n) ;\n A (i,k) = 0 ;\n % fprintf ('A(21,25)=%g\\n', A(21,25)) ;\n % if (A(21,25) ~= 0)\n % pause\n % end\n end\nend\nR = A ;\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/gqr3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6380230174967078}} {"text": "function [v1, v2] = lambertBattinVector(r1, r2, dt, numRevs, gmu)\n%lambertBattin Summary of this function goes here\n% Detailed explanation goes here\n if(size(r1,1) ~= 3)\n error('r1 not of length 3');\n end\n \n if(size(r2,1) ~= 3)\n error('r2 not of length 3');\n end\n \n r1Mag = sqrt(sum(abs(r1).^2,1));\n r2Mag = sqrt(sum(abs(r2).^2,1));\n \n tm = zeros(size(dt));\n if(any(dt(dt<0)))\n B = dt<0;\n tm(B) = -1.0;\n end\n if(any(dt(dt>0)))\n B = dt>0;\n tm(B) = 1.0;\n end\n if(any(dt(dt==0)))\n error('dt = 0; lambert cannot compute');\n end\n dt = abs(dt);\n \n cosDeltaTA = dot(r1,r2,1)./(r1Mag.*r2Mag);\n sinDeltaTA = tm .* sqrt(1 - cosDeltaTA.^2);\n deltaTA = atan2(sinDeltaTA,cosDeltaTA);\n deltaTA = AngleZero2Pi(deltaTA);\n \n c = sqrt(r1Mag.^2 + r2Mag.^2 - 2.*r1Mag.*r2Mag.*cosDeltaTA);\n s = (r1Mag + r2Mag + c)./2;\n epsilon = (r2Mag - r1Mag)./r1Mag;\n \n intemed1 = r2Mag./r1Mag;\n TanSqr2w = (epsilon.^2/4) ./ (sqrt(intemed1) + intemed1.*(2 + sqrt(intemed1)));\n \n sinSqrDeltaTAOver4 = (sin(deltaTA/4)).^2;\n cosSqrDeltaTAOver4 = (cos(deltaTA/4)).^2;\n rop = sqrt(r1Mag.*r2Mag) .* (cosSqrDeltaTAOver4 + TanSqr2w);\n \n l = zeros(size(tm));\n if(any(tm(tm==1.0)))\n bool = tm==1.0;\n l(bool) = (sinSqrDeltaTAOver4(bool) + TanSqr2w(bool))./(sinSqrDeltaTAOver4(bool) + TanSqr2w(bool) + cos(deltaTA(bool)/2));\n end\n if(any(tm(tm==-1.0)))\n bool = tm==-1.0;\n l(bool) = (cosSqrDeltaTAOver4(bool) + TanSqr2w(bool) - cos(deltaTA(bool)/2)) ./ (cosSqrDeltaTAOver4(bool) + TanSqr2w(bool));\n end\n \n m = (gmu .* dt.^2)./(8*rop.^3);\n \n x = l;\n x_change = 1;\n loops=0;\n while(any(x_change > 1E-6) && loops <= 30)\n ksi = computeKsi(x, 20);\n \n h1 = ((l+x).^2.*(1 + 3.*x + ksi)) ./ ((1+2.*x+l).*(4.*x + ksi.*(3+x)));\n h2 = (m.*(x - l + ksi)) ./ ((1+2.*x+l).*(4.*x + ksi.*(3+x)));\n \n B=27*h2./(4*(1+h1).^3);\n U=B./(2*(sqrt(1+B)+1));\n K_U=Kay(U);\n y=(1+h1)./3.*(2+sqrt(1+B)./(1+2*U.*K_U.^2));\n \n x_new = sqrt(((1-l)/2).^2 + m./(y.^2)) - (1+l)/2;\n x_change=abs(x-x_new);\n x = x_new;\n loops=loops+1;\n end\n a = (gmu .* dt.^2)./(16*(rop.^2).*x.*(y.^2));\n \n sinBetaEOver2 = zeros(size(a));\n betaE = zeros(size(a));\n amin = zeros(size(a));\n tmin = zeros(size(a));\n alphaE = zeros(size(a));\n deltaE = zeros(size(a));\n alphaH = zeros(size(a));\n betaH = zeros(size(a));\n deltaH = zeros(size(a));\n f = zeros(size(a));\n g = zeros(size(a));\n g_dot = zeros(size(a));\n if(any(a(a > 0.0)))\n bool = a > 0.0;\n \n sinBetaEOver2(bool) = sqrt((s(bool)-c(bool))./(2*a(bool)));\n betaE(bool) = real(2*asin(sinBetaEOver2(bool))); %real needed to prevent complex numbers from appearing\n \n if(any(deltaTA(bool) > pi))\n bool2 = bool & deltaTA > pi;\n betaE(bool2) = -betaE(bool2);\n end\n\n amin(bool) = s(bool)./2;\n tmin(bool) = sqrt(amin(bool).^3./gmu(bool)) .* (pi - betaE(bool) + sin(betaE(bool)));\n \n alphaE(bool) = real(2*asin(sqrt(s(bool)./(2*a(bool))))); %real needed to prevent complex numbers from appearing\n \n if(any(dt > tmin))\n bool2 = bool & dt > tmin;\n alphaE(bool2) = 2*pi - alphaE(bool2);\n end\n \n deltaE(bool) = alphaE(bool) - betaE(bool);\n \n f(bool) = real(1 - (a(bool)./r1Mag(bool)) .* (1 - cos(deltaE(bool)))); %real() necessary to prevent complex doubles from forming\n g(bool) = real(dt(bool) - sqrt(a(bool).^3./gmu(bool)) .* (deltaE(bool) - sin(deltaE(bool)))); %real() necessary to prevent complex doubles from forming\n g_dot(bool) = real(1 - (a(bool)./r2Mag(bool)) .* (1- cos(deltaE(bool)))); %real() necessary to prevent complex doubles from forming\n end\n if(any(a(a < 0.0)))\n bool = a < 0.0;\n \n alphaH(bool) = 2*asinh(sqrt(s(bool)./(-2*a(bool))));\n betaH(bool) = 2*asinh(sqrt((s(bool)-c(bool))./(-2*a(bool))));\n deltaH(bool) = alphaH(bool)-betaH(bool);\n \n f(bool) = real(1 - (a(bool)./r1Mag(bool)) .* (1 - cosh(deltaH(bool)))); %real() necessary to prevent complex doubles from forming\n g(bool) = real(dt(bool) - sqrt(-(a(bool).^3)./gmu(bool)) .* (sinh(deltaH(bool)) - deltaH(bool))); %real() necessary to prevent complex doubles from forming\n g_dot(bool) = real(1 - (a(bool)./r2Mag(bool)) .* (1 - cosh(deltaH(bool)))); %real() necessary to prevent complex doubles from forming\n end\n if(any(a(a == 0.0)))\n error('a = 0.0');\n end\n \n v1 = bsxfun(@rdivide,r2 - bsxfun(@times,r1,f),g);\n v2 = bsxfun(@rdivide,bsxfun(@times,r2,g_dot) - r1,g);\nend\n\nfunction ksi = computeKsi(x, numLevels) \n eta = x./(sqrt(1+x) + 1).^2;\n num = 8.*(sqrt(1+x) + 1);\n denom = 1;\n\n if(numLevels>0) \n denom = 3 + 1./(eta + computeKsi(eta, numLevels-1));\n end\n ksi = num ./ denom;\n% disp(ksi);\nend\n\nfunction [K_U]=Kay(U)\n % setup the C variable\n c(1)=4/27; %@n=0\n c(2)=8/27; %@n=1\n c(3)=208/891; %n=2\n c(4)=340/1287; %@n=3\n c(5)=700/2907;\n c(6)=928/3591;\n c(7)=296/1215;\n c(8)=1804/7047;\n c(9)=2548/10395;\n c(10)=2968/11655;\n c(11)=3904/15867;\n c(12)=884/3483;\n c(13)=5548/22491;\n c(14)=6160/24327;\n c(15)=7480/30267;\n c(16)=8188/32391;\n c(17)=1940/7839;\n c(18)=10504/41607;\n c(19)=12208/49275;\n c(20)=13108/51975;\n\n % sum up all the intermediate variables\n Z=1+c(20).*U;\n Z=1+c(19).*U./Z;\n Z=1+c(18).*U./Z;\n Z=1+c(17).*U./Z;\n Z=1+c(16).*U./Z;\n Z=1+c(15).*U./Z;\n Z=1+c(14).*U./Z;\n Z=1+c(13).*U./Z;\n Z=1+c(12).*U./Z;\n Z=1+c(11).*U./Z;\n Z=1+c(10).*U./Z;\n Z=1+c(9).*U./Z;\n Z=1+c(8).*U./Z;\n Z=1+c(7).*U./Z;\n Z=1+c(6).*U./Z;\n Z=1+c(5).*U./Z;\n Z=1+c(4).*U./Z;\n Z=1+c(3).*U./Z;\n Z=1+c(2).*U./Z;\n Z=1+c(1).*U./Z;\n\n K_U=1./(3*Z);\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/astrodynamics/lambertBattinVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6380230120856181}} {"text": "function b = dsisl ( a, lda, n, kpvt, b )\n\n%*****************************************************************************80\n%\n%% DSISL solves a real symmetric system factored by DSIFA.\n%\n% Discussion:\n%\n% To compute inverse(A) * C where C is a matrix with P columns\n%\n% call dsifa ( a, lda, n, kpvt, info )\n%\n% if ( info == 0 ) then\n% do j = 1, p\n% call dsisl ( a, lda, n, kpvt, c(1,j) )\n% end do\n% end if\n%\n% A division by zero may occur if the inverse is requested\n% and DSICO has set RCOND == 0.0D+00 or DSIFA has set INFO /= 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the output from DSIFA.\n%\n% Input, integer LDA, the leading dimension of the array A.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer KPVT(N), the pivot vector from DSIFA.\n%\n% Input, real B(N), the right hand side.\n%\n% Output, real B(N), the solution.\n%\n\n%\n% Loop backward applying the transformations and D inverse to B.\n%\n k = n;\n\n while ( 0 < k )\n\n if ( 0 <= kpvt(k) )\n%\n% 1 x 1 pivot block.\n%\n if ( k ~= 1 )\n\n kp = kpvt(k);\n%\n% Interchange.\n%\n if ( kp ~= k )\n temp = b(k);\n b(k) = b(kp);\n b(kp) = temp;\n end\n%\n% Apply the transformation.\n%\n b(1:k-1) = daxpy ( k-1, b(k), a(1:k-1,k), 1, b(1:k-1), 1 );\n\n end\n%\n% Apply D inverse.\n%\n b(k) = b(k) / a(k,k);\n k = k - 1;\n\n else\n%\n% 2 x 2 pivot block.\n%\n if ( k ~= 2 )\n\n kp = abs ( kpvt(k) );\n%\n% Interchange.\n%\n if ( kp ~= k-1 )\n temp = b(k-1);\n b(k-1) = b(kp);\n b(kp) = temp;\n end\n%\n% Apply the transformation.\n%\n b(1:k-2) = daxpy ( k-2, b(k), a(1:k-2,k), 1, b(1:k-2), 1 );\n b(1:k-2) = daxpy ( k-2, b(k-1), a(1:k-2,k-1), 1, b(1:k-2), 1 );\n \n end\n%\n% Apply D inverse.\n%\n ak = a(k,k) / a(k-1,k);\n akm1 = a(k-1,k-1) / a(k-1,k);\n bk = b(k) / a(k-1,k);\n bkm1 = b(k-1) / a(k-1,k);\n denom = ak * akm1 - 1.0;\n b(k) = ( akm1 * bk - bkm1 ) / denom;\n b(k-1) = ( ak * bkm1 - bk ) / denom;\n k = k - 2;\n\n end\n\n end\n%\n% Loop forward applying the transformations.\n%\n k = 1;\n\n while ( k <= n )\n\n if ( 0 <= kpvt(k) )\n%\n% 1 x 1 pivot block.\n%\n if ( k ~= 1 )\n%\n% Apply the transformation.\n%\n b(k) = b(k) + b(1:k-1)' * a(1:k-1,k);\n kp = kpvt(k);\n%\n% Interchange.\n%\n if ( kp ~= k )\n temp = b(k);\n b(k) = b(kp);\n b(kp) = temp;\n end\n\n end\n\n k = k + 1;\n\n else\n%\n% 2 x 2 pivot block.\n%\n if ( k ~= 1 )\n%\n% Apply the transformation.\n%\n b(k) = b(k) + b(1:k-1) * a(1:k-1,k);\n b(k+1) = b(k+1) + b(1:k-1) * a(1:k-1,k+1);\n kp = abs ( kpvt(k) );\n%\n% Interchange.\n%\n if ( kp ~= k )\n temp = b(k);\n b(k) = b(kp);\n b(kp) = temp;\n end\n\n end\n\n k = k + 2;\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dsisl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6379307477010026}} {"text": "function enlarged_tt = add_non_essential_dims(small_tt, new_n, old_vars_pos)\n % enlarged_tt = add_non_essential_dims(small_tt, new_n, old_vars_pos) \n % creates enlarged version of tt_tensor, expanding it by ones.\n % Mode sizes of the enlarged_tt are equal to new_n.\n % First dimension of the small_tt is old_vars_pos(1) dimension of the enlarged_tt.\n % This procedure doesn't increase the maximal TT-rank.\n % \n % Input:\n % \tsmall_tt -- P-dimensional tensor in the TT-format.\n % \tnew_n -- Q by 1 vector with enlarged_tt mode sizes (Q > P).\n % \told_vars_pos -- P by 1 vector in ascending order. Consists of positions\n % \t\t\t\t\t\t\tof the small_tt dimensions in the enlarged_tt tensor.\n % \n % Output:\n % \tenlarged_tt -- Q-dimensional tensor in the TT format.\n % \t\t\tenlarged_tt(i1, ..., iQ)\n % \t\t\ti1 take values from {1, ..., new_n(1)}\n % \t\t\t...\n % \t\t\tiQ take values from {1, ..., new_n(Q)}\n % \n % Example:\n % m = rand(3, 4);\n % small_tt = tt_tensor(m); % small_tt(i2, i4)\n % enlarged_tt = add_non_essential_dims(small_tt, [2, 3, 6, 4, 4], [2, 4]);\n % % enlarged_tt(i1, i2, i3, i4, i5, i6) == small_tt(i2, i4) for any i1, i3, i5, i6\n % \n \n\n if (~issorted(old_vars_pos))\n error('Dimensions (third argument) must be in ascending order.');\n end\n\n if ~isvector(new_n) | ~isvector(old_vars_pos) | small_tt.d ~= length(old_vars_pos)\n \terror('Wrong usage, see help tt_tensor.add_non_essential_dims.');\n end\n\n\n\n d = length(new_n);\n enlarged_tt = tt_tensor;\n enlarged_tt.d = d;\n enlarged_tt.r = zeros(d + 1, 1);\n enlarged_tt.r(1) = 1;\n enlarged_tt.n = new_n(:);\n enlarged_tt.core = [];\n enlarged_tt.ps = zeros(d + 1, 1);\n enlarged_tt.over = 0;\n curr_var_i = 0;\n vars_length = length(old_vars_pos);\n before_first_var = true;\n after_last_var = false;\n for dimension_i = 1:d\n if curr_var_i == vars_length\n after_last_var = true;\n end\n\n if curr_var_i < vars_length && old_vars_pos(curr_var_i + 1) == dimension_i\n curr_var_i = curr_var_i + 1;\n before_first_var = false;\n if new_n(dimension_i) ~= small_tt.n(curr_var_i)\n error('Dimensions must agree!');\n end\n end\n\n if before_first_var || after_last_var\n % Dimension_i is before old_vars_pos(1) or after old_vars_pos(end).\n curr_core = ones(new_n(dimension_i), 1);\n curr_rank = 1;\n elseif old_vars_pos(curr_var_i) == dimension_i\n % It's real dimension.\n curr_core = core(small_tt, curr_var_i);\n curr_rank = small_tt.r(curr_var_i);\n else\n % Non-essential dimension between two real ones.\n curr_rank = small_tt.r(curr_var_i + 1);\n curr_core = core_eye(curr_rank, new_n(dimension_i));\n end\n enlarged_tt.r(dimension_i) = curr_rank;\n enlarged_tt.ps(dimension_i) = length(enlarged_tt.core) + 1;\n enlarged_tt.core = [enlarged_tt.core; curr_core(:)];\n end\n enlarged_tt.r(end) = 1;\n enlarged_tt.ps(end) = length(enlarged_tt.core) + 1;\nend\n\nfunction core = core_eye(r, n)\n % Return 3-dimensional array filled with eye matrices,\n % which corresponds to non-essential dimension core.\n core = zeros(r, n, r);\n for i = 1:n\n core(:, i, :) = eye(r);\n end\nend\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/@tt_tensor/add_non_essential_dims.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6379307294699185}} {"text": "function [I,J] = stam_order(F,A)\n % STAM_ORDER For a regular patch of 13 faces and 12 vertices of a mesh (V,F)\n % around a \"center\" facet f determined by all its corners having valence 6,\n % determine the reordering of vertices, so that the reordered mesh\n % (V(I,:),J(F)) will fit Jos Stam's ordering in \"Evaluation of Loop\n % Subdivision Surfaces\". The facet F(f,:) is mapped to [4 7 8] in Stam's\n % patch.\n %\n % [I,J] = stam_order(F)\n % [I,J] = stam_order(F,A)\n %\n % Input:\n % F 13 by 3 list of triangle indices into some V\n % A max(F) by max(F) adjacency matrix {[]}\n % Output:\n % I 12 long list of indices such that V(I,:) are the reorderd vertices.\n % J 12 long list of indices such that J(F) are the reordered faces,\n % {J=full(sparse(I,1,1:12))}\n %\n % Example:\n % % Canonical regular patch\n % WV = [-1 0;0 -1;-1 1;0 0;1 -1;-1 2;0 1;1 0;2 -1;0 2;1 1;2 0];\n % F = [ ...\n % 1 3 4;4 2 1;4 5 2; ...\n % 6 7 3;7 4 3;4 7 8;8 5 4;8 9 5; ...\n % 6 10 7;10 11 7;7 11 8;11 12 8;12 9 8];\n % % Scramble patch vertex order and face order\n % R = randperm(size(WV,1));\n % G = R(F(randperm(end),:));\n % U = full(sparse([R R],repmat([1 2],size(WV,1),1),WV));\n % % Uncover order\n % [I,J] = stam_order(G);\n % % plot before and after\n % subplot(1,2,1);\n % tsurf(G,U,'VertexIndices',1); \n % set(gca,'YDir','reverse');\n % subplot(1,2,2);\n % tsurf(J(G),U(I,:),'VertexIndices',1); \n % set(gca,'YDir','reverse');\n %\n\n % There should be 13 face in a regular patch\n assert(size(F,1)==13,'F should have 13 faces to be a regular patch');\n\n if nargin<2 || isempty(A)\n A = adjacency_matrix(F);\n end\n assert(nnz(any(A)) == 12,'F should reference 12 vertices');\n % valences \n C6 = sum(A,2) == 6;\n % Locate the center face:\n f = find(all(C6(F),2),1);\n if isempty(f) \n error('F is not a regular patch');\n end\n % Stams 4,7,8 vertices\n I = zeros(12,1);\n I(4) = F(f,1);\n I(7) = F(f,2);\n I(8) = F(f,3);\n A(:,F(f,:)) = 0;\n I(5) = find(A(I(4),:) & A(I(8),:));\n I(3) = find(A(I(7),:) & A(I(4),:));\n I(11) = find(A(I(8),:) & A(I(7),:));\n A(:,I(I~=0)) = 0;\n I(12) = find(A(I(11),:) & A(I(8),:));\n I( 9) = find(A(I(12),:) & A(I(8),:));\n I( 2) = find(A(I( 5),:) & A(I(4),:));\n I( 1) = find(A(I( 2),:) & A(I(4),:));\n I( 6) = find(A(I( 3),:) & A(I(7),:));\n I(10) = find(A(I( 6),:) & A(I(7),:));\n J = full(sparse(I,1,1:12));\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/stam_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7634837689358858, "lm_q1q2_score": 0.6378781135366188}} {"text": "function G = gsp_jtv_graph(G,T,fs,param)\n% GSP_JTV_GRAPH Add time information to the graph structure\n% Usage: G = gsp_jtv_graph(G);\n% G = gsp_jtv_graph(G,T);\n% G = gsp_jtv_graph(G,T,fs);\n% G = gsp_jtv_graph(G,T,fs,param);\n%\n% Input parameters:\n% G : Graph structure\n% T : Time length\n% fs : Sampling frequency (default 1)\n% param : Structure of optional parameters\n%\n% Output parameters:\n% G : Time-Vertex Graph structure\n%\n% This function adds the time domain information to the structure G.\n% The fields stored inside G.jtv are:\n% - T : Time length\n% - fs : Sampling frequency\n% - NFFT : Number of frequency point (default [])\n% - Transform : Time Fourier basis: 'dft' or 'dct'\n% - Extension : Signal will be zero padded in time to take into account negative lag\n% - Lag : Lag axis\n% - omega : Frequency axis\n% - DiffT : Time Gradient\n% - LT : Time Laplacian\n%\n% Additional parameters\n% ---------------------\n%\n% * *param.transform* : Fourier basis: 'dft' or 'dct'. (default 'dft')\n% * *param.approx* : Stencil approx for the gradient: 'forward' or 'backward'. (default 'forward')\n% * *param.extension* : Signal will be zero padded in time when needed. (default '0')\n% * *param.NFFT* : Number of frequency point. (default [])\n%\n\n% Author : Francesco Grassi\n% Date : September 2016\n\nif nargin<4\n param = struct;\nend\n\nif ~isstruct(G)\n error('G is not a valid graph');\nend\n\nif nargin<2 || ~isnumeric(T) || T<1\n error('Time length T must be a numeric value greater than 0');\nend\n\nif nargin<3 || isempty(fs)\n fs=1;\nend\n\nif ~isnumeric(fs) || fs<0\n error('Sampling frequency fs must be a numeric value greater than 0');\nend\n\nif ~isfield(param,'NFFT'), param.NFFT = []; end\nif ~isfield(param,'transform'), param.transform = 'dft'; end\nif ~isfield(param,'approx'), param.approx = 'forward'; end\nif ~isfield(param,'extension'), param.extension = 0; end\n\n\n%% JTV PARAMETERS\nG.jtv = struct;\nG.jtv.T = T;\nG.jtv.fs = fs;\nG.jtv.NFFT = param.NFFT;\nG.jtv.transform = param.transform;\nG.jtv.extension = param.extension;\nG.jtv.omega = gsp_jtv_fa(G);\n\nif G.jtv.extension\n G.jtv.lag = 2*G.jtv.T-1;\nelse\n G.jtv.lag = T;\nend\n\n%% DIFFERENTIAL OPERATORS\nz = ones(T,1);\n\n% G.jtv.LT = spdiags([-z 2*z -z], [-1 0 1], T, T);\n\nG.jtv.DiffT = spdiags([-z z], [0 1], T, T);\n\nswitch param.transform\n case 'dft'\n G.jtv.DiffT(T,1) = 1;\n case 'dct'\n G.jtv.DiffT(T,T-1) = 1;\n otherwise\n error('Unknown transform');\nend\n \nG.jtv.LT = G.jtv.DiffT'*G.jtv.DiffT;\n\nif strcmpi(param.approx,'backward')\n G.jtv.DiffT = -G.jtv.DiffT.';\nend\n\n% toeplitz([-1 zeros(T-2,1) 1],[-1 1 zeros(T-2,1)]); %periodic forward\n% toeplitz([1 -1 zeros(T-2,1)],[1 zeros(T-2,1) -1]); %periodic backward (= -transpose(periodic forward))\n\n\nend\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/graphs/gsp_jtv_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6378069951021257}} {"text": " function [sino, hn, nn, Hk] = fbp2_sino_hilbert(sino, varargin)\n%|function [sino, hn, nn, Hk] = fbp2_sino_hilbert(sino, [options])\n%|\n%| Apply band-limited Hilbert-transform filter to 2D sinogram.\n%| Frequency response: H(u) = -1i * sign(u) * rect(u/2/umax)\n%|\n%| in\n%|\tsino\t[nb (L)] sinogram(s)\n%|\n%| options\n%|\tdr | ds\t(real)\tsample spacing (in distance units, e.g., cm) (default 1)\n%|\tnpad\t\t# of padded samples. (default: 0, means next power of 2)\n%|\tdecon1\t\tdeconvolve effect of linear interpolator? (default: 0)\n%|\twindow\t[npad]\tsamples of apodization window function\n%|\t\t\tfor [-np/2,...,np/2-1]. (default: '' = plain ramp)\n%|\t\t\tor a string like 'hann' for some predefined windows\n%| out\n%|\tsino\t[nb (L)] filtered sinogram rows\n%|\thn\t[npad]\tsamples of band-limited Hilbert transform filter\n%|\tnn\t[npad]\t[-np/2,...,np/2-1] vector for convenience\n%|\tHk\t[npad]\tspectral samples on [0 ... np-1]\n%|\n%| Copyright 2011-07-16, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(sino, 'test'), fbp2_sino_hilbert_test, clear, return, end\nif nargin < 1, ir_usage, end\n\narg.dr = 1;\narg.window = '';\narg.npad = 0;\narg.decon1 = false;\narg = vararg_pair(arg, varargin, 'subs', {'ds', 'dr'});\n\ndims = size(sino);\nsino = reshape(sino, dims(1), []);\n[sino hn nn Hk] = fbp2_sino_hilbert_do(sino, ...\n\targ.dr, arg.window, arg.npad, arg.decon1);\nsino = reshape(sino, [size(sino, 1) dims(2:end)]);\n\n\n% fbp2_sino_hilbert_do()\nfunction [sino, hn, nn, Hk] ...\n\t= fbp2_sino_hilbert_do(sino, dr, window, npad, decon1);\n\n[nb na] = size(sino);\nif ~npad\n\tnpad = 2^ceil(log2(2*nb-1)); % padded size\nend\nsino = [sino; zeros(npad-nb,na)]; % padded sinogram\n\n[hn nn] = fbp2_filter_hilbert_make(npad, dr);\n\nHk = 1i * imag_check(fft(fftshift(hn))); % trick: pure imaginary!\n\nHk = Hk .* fbp2_window(npad, window);\n\nHk = dr * Hk; % differential for discrete-space convolution vs integral\n\n% linear interpolation is like blur with a triangular response,\n% so we can compensate for this approximately in frequency domain\nif decon1\n\tHk = Hk ./ fftshift(nufft_sinc(nn / npad).^2);\nend\n\nsino = ifft_sym( fft(sino, [], 1) .* repmat(Hk, [1 na]), [], 1); % apply filter\n\n\n% fbp2_filter_hilbert_make()\nfunction [hn, nn] = fbp2_filter_hilbert_make(n, dr)\nnn = [-(n/2):(n/2-1)]';\nu0 = 1/2/dr;\nhn = 2 * u0 * nufft_sinc(nn/2) .* sin(pi/2 * nn);\n\n\n% imag_check()\n% take imaginary part but check that real part is negligible\nfunction out = imag_check(in, varargin)\nout = reale(-1i * in, varargin{:});\n\n\n% fbp2_sino_hilbert_test()\nfunction fbp2_sino_hilbert_test\nnb = 2^5;\ndr = 0.1;\n[sino1 h1 nn H1] = fbp2_sino_hilbert(zeros(nb,2), 'dr', dr);\nh2 = 1 ./ (pi * nn * dr); % samples of ideal non-bandlimited\n\nif im\n\tclf, subplot(121)\n\tplot(nn, h1, '.-', nn, h2, '-')\n\txlabel 'n', ylabel 'h[n]'\n\tlegend('band-limited', 'ideal')\n\n\tsubplot(122)\n\tplot(nn, imag_check(fftshift(H1)), '.-', nn, -sign(nn), '-')\n\txlabel 'k', ylabel 'imag(H[k])'\n\tlegend('band-limited', 'ideal', 'location', 'north')\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/fbp2_sino_hilbert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6378069948470367}} {"text": "function fom = figuremerit(ideal,detected)\n\n Ni = numel(find(ideal == 1));\n Nd = numel(find(detected == 1));\n \n [h w c] = size(ideal);\n\n alpha = 1/9;\n sum = 0.0;\n for r = 1:h\n for c = 1:w\n if (detected(r,c) == 1)\n dist = distance(ideal,detected,r,c)^2;\n sum = sum + (1/(1+alpha*dist));\n end\n end\n end\n\n fom = (1/max(Ni,Nd))*sum;\n\n \nfunction d = distance(ideal,detected,rind,cind)\n\n [h w c] = size(ideal);\n\n diff = 1;\n found = 0;\n d = 10.0^100;\n\n if (ideal(rind,cind) == detected(rind,cind))\n d = 0.0; \n found = 1;\n end\n\n left = cind - diff;\n right = cind + diff;\n top = rind - diff;\n bottom = rind + diff;\n while (~found)\n \n for c = left:right\n if ((top >= 1) && (c >= 1) && (c <= w))\n if (ideal(top,c) == detected(rind,cind))\n tmp = sqrt((top-rind)^2 + (c-cind)^2);\n found = 1;\n\n if (tmp < d)\n d = tmp;\n end\n end\n end\n end\n \n for c = left:right\n if ((bottom <= h) && (c >= 1) && (c <= w))\n if (ideal(bottom,c) == detected(rind,cind))\n tmp = sqrt((bottom-rind)^2 + (c-cind)^2);\n found = 1;\n\n if (tmp < d)\n d = tmp;\n end\n end\n end\n end\n \n for r = top+1:bottom-1\n if ((left >= 1) && (r >= 1) && (r <= h))\n if (ideal(r,left) == detected(rind,cind))\n tmp = sqrt((r-rind)^2 + (left-cind)^2);\n found = 1;\n\n if (tmp < d)\n d = tmp;\n end\n end\n end\n end\n \n for r = top+1:bottom-1\n if ((right <= w) && (r >= 1) && (r <= h))\n if (ideal(r,right) == detected(rind,cind))\n tmp = sqrt((r-rind)^2 + (right-cind)^2);\n found = 1;\n\n if (tmp < d)\n d = tmp;\n end\n end\n end\n end\n\n diff = diff + 1;\n left = cind - diff;\n right = cind + diff;\n top = rind - diff;\n bottom = rind + diff;\n if ((left < 1) && (right > w) && (top < 1) && (bottom > h))\n found = 1;\n end\n end\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/hga_image_denoising-master/code/figuremerit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6378069797310967}} {"text": "function [W_RF,W_BB]=OMP_Combining(F_RF,F_BB)\nglobal Nr Ns Nrf H Vn Codebook_w\nW_RF = [];\nW_MMSE = ((F_BB' * F_RF' * H' * H * F_RF * F_BB + Vn * Ns * eye(Ns))^(-1) * F_BB' * F_RF' * H')';\nWres = W_MMSE;\nn = 1 / Ns * H * F_RF * F_BB * F_BB' * F_RF' *H' + Vn * eye(Nr);\nfor i = 1 : Nrf \n y = Codebook_w' * n * Wres;\n k = find(diag(y * y')==max(diag(y * y')));\n W_RF(:,i) = Codebook_w(:,k);\n W_BB = (W_RF' * n * W_RF)^(-1) * W_RF' * n * W_MMSE;\n Wres = (W_MMSE - W_RF * W_BB) / norm(W_MMSE - W_RF * W_BB,'fro');\nend\n", "meta": {"author": "Zzhaoxingyu", "repo": "hybrid-beamforming-for-three-scenes", "sha": "396ae70db7dd464a65458f274a65aa113ed73c8b", "save_path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes", "path": "github-repos/MATLAB/Zzhaoxingyu-hybrid-beamforming-for-three-scenes/hybrid-beamforming-for-three-scenes-396ae70db7dd464a65458f274a65aa113ed73c8b/narrowband/Algorithms/SSP_OMP/OMP_Combining.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.637766212147041}} {"text": "function [H] = scale(f)\n\n% SCALE returns the homogenous coordinate transformation matrix\n% corresponding to a scaling along the x, y and z-axis\n% \n% Use as\n% [H] = translate(S)\n% where\n% S [sx, sy, sz] scaling along each of the axes\n% H corresponding homogenous transformation matrix\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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% 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 numel(f)~=3\n ft_error('incorrect input vector');\nend\n\nH = [\n f(1) 0 0 0 \n 0 f(2) 0 0\n 0 0 f(3) 0\n 0 0 0 1\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/external/fieldtrip/utilities/private/scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6377370417677235}} {"text": "function [h, compUpVV, compUpVP, compUp] = lfmComputeH3VV(gamma1_p, gamma1_m, sigma2, t1, ...\n t2, preFactor, mode)\n\n% LFMCOMPUTEH3VV Helper function for computing part of the LFMVXLFMV kernel.\n% FORMAT\n% DESC computes a portion of the LFMVXLFMV kernel.\n% ARG gamma1 : Gamma value for first system.\n% ARG gamma2 : Gamma value for second system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG preFactor : precomputed constants.\n% ARG mode: indicates the correct precomputations.\n% RETURN h : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\n% Evaluation of h\n\nif nargout>1\n [compUpVV{1}, compUpVP{1}, compUp{1}] = lfmvvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);\n [compUpVV{2}, compUpVP{2}, compUp{2}] = lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n h = preFactor(1)*compUpVV{1} + preFactor(2)*compUpVV{2};\nelse\n h = preFactor(1)*lfmvvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...\n + preFactor(2)*lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode); \n \n% %h = preFactor(2)*lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode); \n% \n% h = lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n% \n% epsilon = 1e-6;\n% valg = gamma1_m;\n% gamma1_m = valg + epsilon;\n% h1 = lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n% gamma1_m = valg - epsilon;\n% h2 = lfmvvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n% gamma1_m = valg;\n% numerics = 0.5*(h1-h2)/epsilon;\n% theo = lfmvvGradientUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);\n \n \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/lfmComputeH3VV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6377370320630376}} {"text": "function coef = sandia_sgmgg_coef_naive ( dim_num, point_num, sparse_index )\n\n%*****************************************************************************80\n%\n%% SANDIA_SGMGG_COEF_NAIVE returns the combinatorial coefficients.\n%\n% Discussion:\n%\n% The coefficient of point I is calculated as follows:\n%\n% *) point J is a \"neighbor\" of point I if every entry of the sparse\n% index for point J is either equal to, or 1 greater than, the\n% corresponding entry of the sparse index of point I.\n%\n% *) If point J is a neighbor of point I, then it contributes\n% (-1)^D to the coefficient, where D is the sum of the differences\n% between the sparse indices of point I and point J.\n%\n% This is a completely naive implementation of the calculation,\n% intended simply as a demonstration for small examples.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 August 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% An Anisotropic Sparse Grid Stochastic Collocation Method for Partial\n% Differential Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2411-2442.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the dimension of the vector.\n%\n% Input, integer POINT_NUM, the number of points.\n%\n% Input, integer SPARSE_INDEX(DIM_NUM,POINT_NUM),\n% the indices that define the points.\n%\n% Output, integer COEF(POINT_NUM), the coefficients.\n%\n coef = zeros ( point_num, 1 );\n\n for j1 = 1 : point_num\n\n for j2 = 1 : point_num\n\n neighbor = 1;\n term = + 1;\n\n for i = 1 : dim_num\n\n dif = sparse_index(i,j2) - sparse_index(i,j1);\n\n if ( dif == 0 )\n\n elseif ( dif == 1 )\n term = - term;\n else\n neighbor = 0;\n break;\n end\n\n end\n\n if ( neighbor )\n coef(j1) = coef(j1) + term;\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sandia_sgmgg/sandia_sgmgg_coef_naive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6377022688107798}} {"text": "function [ R t s ]=computeOrientation(x,xp,method,varargin)\n% Compute Absolute or Exterior Orientation (Pose Estimation)\n%\n% Absolute is : given x and xp (2 arrays of 3D coordinates), find the best\n% transformation such that x=s*R*xp+t\n%\n% Exterior is : 1 array of 3D position x is known and its 2D orthographic\n% projection xp.\n% Find the best transformation such that xp=projection*(s*R*x+t)\n% (same as Pose Estimation, ePNP). Projection is ortho for now\n%\n% The routines below are only for the orthographic case for now\n%\n% USAGE\n% [R,t,s]=computeOrientation(x,xp,method)\n%\n% INPUTS\n% x,xp - 3xN or 2xN array of points or right/left.\n% For 'exteriorSequence', it can be of size\n% 2 x nPoint x nFrame and 3 x nPoint x nFrame\n% method - 'absolute', 'absoluteHard' (try more if Horn's fails)\n% or 'exterior' and 'exteriorSequence'\n% varargin - list of paramaters in quotes alternating with their values\n% - 'RIni' initial rotation from which the optimization will be\n% started (only for 'exterior' and 'exteriorSequence')\n%\n% OUTPUTS\n% R - rotation matrix\n% t - translation vector\n% s - scale factor (if not requested, s=1)\n%\n% EXAMPLE\n%\n% See also\n%\n% Vincent's Structure From Motion Toolbox Version 3.1\n% Copyright (C) 2008-2011 Vincent Rabaud. [vrabaud-at-cs.ucsd.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the GPL [see external/gpl.txt]\n\nnPoint=size(x,2);\n\nswitch method\n case { 'absolute', 'absoluteHard' }\n % Computes the absolute orientation between 2 sets of 3D points\n % Xright=s*R*Xleft + t . We want to recover s,R,T\n % Ref: B.K.P. Horn, H.M. Hilden, and S. Negahdaripour, Closed-Form\n % Solution of Absolute Orientation Using Orthonormal Matrices\n rr=normalizePoint(x,4); rl=normalizePoint(xp,4);\n rrBar=mean(rr,2); rlBar=mean(rl,2);\n rrp=rr-rrBar(:,ones(1,nPoint)); rlp=rl-rlBar(:,ones(1,nPoint));\n \n M=zeros(3); for i=1:nPoint; M=M+rrp(:,i)*rlp(:,i)'; end\n [V,D]=eig(M'*M);\n V=real(V);\n \n R=1/sqrt(D(2,2))*V(:,2)*V(:,2)' + 1/sqrt(D(3,3))*V(:,3)*V(:,3)';\n temp=V(:,1)*V(:,1)';\n if D(1,1)>0\n R=R+1/sqrt(D(1,1))*temp;\n else\n if det(R+temp)>0; R=R+temp; else R=R-temp; end\n end\n R=M*R;\n \n R=rotationMatrix(R);\n \n if det(R)<0 && strcmp(method,'absoluteHard') % if Horn's method fails\n warning('Horn''s method failed. Trying GloptiPoly3 solution');\n RHorn=R;\n try\n % Sedumi and GloptiPoly3 must be installed and in the path !\n mpol R 3 3;\n \n g0=rlp-R*rrp;\n g0=g0(1,:)*g0(1,:)'+g0(2,:)*g0(2,:)'+g0(3,:)*g0(3,:)';\n \n % define the rotation constraints\n K = [ R(1,:)*R(1,:)' == 1, R(2,:)*R(2,:)'==1, R(3,:)*R(3,:)'==1,...\n R(1,:)*R(2,:)' == 0, R(1,:)*R(3,:)' == 0, R(2,:)*R(3,:)' == 0,...\n det(R)>=0 ];\n \n % define the problem and solve it\n P=msdp(min(g0),K);\n [ status obj ] = msol(P);\n \n R=rotationMatrix( double(R) );\n catch %#ok\n R = RHorn;\n end\n end\n \n % Figure out s and t\n if nargout==2\n s=1;\n else\n s=norm(rrp,'fro')/norm(rlp,'fro');\n if norm( rrp+s*R*rlp, 'fro' ) < norm( rrp-s*R*rlp, 'fro' ); s=-s; end\n end\n \n t=rrBar-s*R*rlBar;\n case 'exterior'\n if ~isempty(varargin); RIni = varargin{0};\n else RIni=[];\n end\n\n if isempty(RIni)\n try\n % Sedumi and GloptiPoly3 must be installed and in the path !\n mpol R 2 3;\n if nargout<2; t=0; else mpol t 2 1; end\n if nargout<3; s=1; else mpol s; end\n \n g0=0;\n for i=1:nPoint\n tmp=xp(:,i) - s*(R*x(:,i)+t); %#ok\n g0 = g0 + tmp'*tmp;\n end\n \n % define the rotation constraints\n K = [ R(1,:)*R(1,:)' == 1, R(2,:)*R(2,:)'==1, R(1,:)*R(2,:)' == 0];\n \n % define the problem and solve it\n mset('verbose',false);\n P=msdp(min(g0),K);\n\n [ status obj ] = msol(P);\n \n R=rotationMatrix( double(R) );\n \n if nargout>=2; t=[ double(t); 0]; end\n if nargout==3; s=double(s); end\n catch %#ok\n warning(['GloptiPoly3 not installed or Gloptypoly crashed,' ...\n 'using ePnP']);\n try\n mset clear;\n catch %#ok\n [ R t ] = efficient_pnp( x', xp', eye(3,3) );\n t=t(1:2);\n end\n end\n if any(isnan(R))\n warning(['GloptiPoly failed, using ePnP']);\n [ R t ] = efficient_pnp( x', xp', eye(3,3) );\n t=t(1:2);\n end\n else\n R=RIni;\n end\n \n % perform gradient descent to optimize the rotation\n Q = refineExteriorOrientation(x,xp,quaternion(R));\n R=quaternion( Q );\n case 'exteriorSequence'\n RIni=getPrmDflt( varargin, {'RIni' [] }, 1 );\n if length(RIni)>1\n Q=quaternion(RIni);\n else\n Q=2*rand(4,size(xp,3))-1;\n end\n [ Q err ]=refineExteriorOrientation(x,xp,Q);\n \n for i = 1 : 10\n [ QNew errNew ]=refineExteriorOrientation(x,xp,2*rand(4,size(xp,3))-1);\n temp = errNew,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\nout = moment(y,theMom) / std(y); % normalized\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/DN_Moments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6376824164430347}} {"text": "function [cx, cy, w, h] = get_axis_aligned_BB(region)\n% GETAXISALIGNEDBB extracts an axis aligned bbox from the ground truth REGION with same area as the rotated one\nnv = numel(region);\nassert(nv==8 || nv==4);\n\nif nv==8\n cx = mean(region(1:2:end));\n cy = mean(region(2:2:end));\n x1 = min(region(1:2:end));\n x2 = max(region(1:2:end));\n y1 = min(region(2:2:end));\n y2 = max(region(2:2:end));\n A1 = norm(region(1:2) - region(3:4)) * norm(region(3:4) - region(5:6));\n A2 = (x2 - x1) * (y2 - y1);\n s = sqrt(A1/A2);\n w = s * (x2 - x1) + 1;\n h = s * (y2 - y1) + 1;\nelse\n x = region(1);\n y = region(2);\n w = region(3);\n h = region(4);\n cx = x+w/2;\n cy = y+h/2;\nend\n", "meta": {"author": "bertinetto", "repo": "cfnet", "sha": "971e7922b7f0f9140e0d995b598e8d97dece277c", "save_path": "github-repos/MATLAB/bertinetto-cfnet", "path": "github-repos/MATLAB/bertinetto-cfnet/cfnet-971e7922b7f0f9140e0d995b598e8d97dece277c/src/tracking/get_axis_aligned_BB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6375741096316169}} {"text": "% Coupled nonlinear PDE's\n% Buckley Leverett equation\n% dependent variables: pressure and water saturation\n% Prepared for educational purposes by ** AAE **\n% Spontaneous imbibition in a core, IMPES, works fine\n% not as fast as expected, can be improved\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc\n%% define the geometry\nNx = 20; % number of cells in x direction\nNy = 50; % number of cells in y direction\nW = 0.02; % [m] length of the domain in x direction\nH = 0.07; % [m] length of the domain in y direction\n% m = createMesh1D(Nx, W);\nm = createMeshCylindrical2D(Nx, Ny, W, H); % creates a 2D mesh\n%% define the physical parametrs\nkrw0_ww = 0.3;\nkrw0_ow = 1.0;\nkro0_ww = 0.6;\nkro0_ow = 0.76;\nnw = 2.4;\nno = 2.0;\nsor_ww=0.1;\nsor_ow=0.12;\nswc_ww=0.09;\nswc_ow=0.09;\nSF=createFaceVariable(m, 0.0); % 1 is water wet, 0 is oil wet\nkrw0=krw0_ww*SF+krw0_ow*(1-SF);\nkro0=kro0_ww*SF+kro0_ow*(1-SF);\nsor=sor_ww*SF+sor_ow*(1-SF);\nswc=swc_ww*SF+swc_ow*(1-SF);\nsws=@(sw, sor, swc)((sw>swc).*(sw<1-sor).*(sw-swc)./(1-sor-swc)+(sw>=1-sor));\nkro=@(sw, kro0, sor, swc)((sw>=swc).*kro0.*(1-sws(sw, sor, swc)).^no+(sw1-sor).*(-(1-krw0)./sor.*(1.0-sw)+1.0));\ndkrwdsw=@(sw, krw0, sor, swc)((sw<=1-sor).*nw.*krw0.*(1./(1-sor-swc)).*sws(sw, sor, swc).^(nw-1)+(sw>1-sor).*((1-krw0)./sor));\ndkrodsw=@(sw, kro0, sor, swc)((sw>=swc).*(-kro0.*no.*(1-sws(sw, sor, swc)).^(no-1))./(-swc-sor+1)+(sweps_p) || (error_sw>eps_sw))\n while(1)\n % calculate parameters\n pgrad = gradientTerm(p);\n% pcgrad=gradientTerm(pc(sw));\n sw_face = upwindMean(sw, -pgrad); % average value of water saturation\n sw_grad=gradientTerm(sw);\n sw_ave=arithmeticMean(sw);\n pcgrad=dpc(sw_ave, sor, swc).*sw_grad+dpcdk(sw_ave, sor, swc).*grad_phik;\n % solve for pressure at known Sw\n labdao = lo.*funceval(kro, sw_face, kro0, sor, swc);\n labdaw = lw.*funceval(krw, sw_face, krw0, sor, swc);\n labda = labdao+labdaw;\n % compute [Jacobian] matrices\n Mdiffp1 = diffusionTerm(-labda);\n RHSpc1=divergenceTerm(labdao.*pcgrad);\n [Mbcp, RHSbcp] = boundaryCondition(BCp);\n RHS1 = RHSpc1+RHSbcp; % with capillary\n p_new=solvePDE(m, Mdiffp1+Mbcp, RHS1);\n \n % solve for Sw\n pgrad = gradientTerm(p_new);\n uw=-labdaw.*pgrad;\n [Mbcsw, RHSbcsw] = boundaryCondition(BCs);\n RHS_sw=-divergenceTerm(uw);\n sw_new=solveExplicitPDE(sw_old, dt, RHS_sw, BCs, phi);\n\n error_p = max(abs((p_new.value(:)-p.value(:))./p_new.value(:)))\n error_sw = max(abs(sw_new.value(:)-sw.value(:)))\n dt_new=dt*min(dp_alwd/error_p, dsw_alwd/error_sw);\n % assign new values of p and sw\n if error_sw>dsw_alwd\n dt=dt*(dsw_alwd/error_sw)\n else\n t=t+dt;\n p = p_new;\n sw = sw_new;\n p_old = p;\n sw_old = sw;\n dt=min(dt*(dsw_alwd/error_sw), 10*dt);\n break;\n end\n end\n \n rec_fact=[rec_fact (oil_init-domainInt(1-sw))/oil_init];\n t_day=[t_day t];\n figure(1);visualizeCells(1-sw); drawnow;\n figure(2); plot(t_day/3600/24, rec_fact)\n xlabel('time [day]');\n ylabel('recovery factor');\n title([num2str(t/3600/24) ' day']); drawnow;\nend", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Advanced/imbib_wet_IMPES.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6375741032555485}} {"text": "% AUSM (Liou-Steffen) scheme for one-dimensional Euler equations\n\n% Copyright 2001 P. Wesseling\n% This program and its subprograms may be freely used, modified and distributed\n% under the GNU General Public License: http://www.gnu.org/copyleft/gpl.html\n\n% Theory in Section 10.5 of:\n\n% \tP. Wesseling: Principles of Computational Fluid Dynamics\n% \tSpringer, Heidelberg, 2000 ISBN 3-5453-0. XII, 642 pp.\n% See http://ta.twi.tudelft.nl/nw/users/wesseling/cfdbook.html\n\n% This program makes Figs. 10.17, 10.20 in the book\n\n% Function called: f\n% Programs called: problem_specification, Riemann\n\nclear all\n\nglobal PRL CRL MACHLEFT gamma pleft pright rholeft rhoright uleft...\n\turight tend lambda\t\t% lambda = dt/dx\n\n\t\t% .....................Input............................\ngamma = 1.4; \t% Ratio of specific heats\nJ = 48;\t\t% Number of grid cells\nbouncon = 0;\t% bouncon chooses outflow boundary conditions\n\t\t% = 0: Nothing happens: infinite domain\n\t\t% = 1: Solid wall at x = 1 with direct prescription of uwall\n\t\t% = 2: Solid wall at x = 1 with reflection b.c.\n\t\t% ....................End of input........................\n\ngammab = 1/(gamma - 1); gam1 = gamma-1; gamgam = gamma^gamma;\nproblem_specification\t\n\t\t\nh = 1/J; \t\t\t\t% Cell size\ndt = lambda*h;\t\t\t\t% Time step\nn = floor(tend/dt);\t\t\t% Number of time-steps\n\n% \t\tDefinition of grid numbering \n% x=0 \t\t\t\t\t x=1\n% grid |---o---|---o---|---o--- ... --|---o---|\n% 1 1 2 2 3 J-1 J \n\nxcenter = h*[1:J] - h/2;\t\t% Location of cell centers\n\npress = zeros(size(xcenter));\t\t% Preallocation of pressure, \nrhoold = press; uold = press;\t\t% density and velocity\nrhonew = press; mnew = press;\t\t% momentum \ntotenew = press; enthalpy = press;\t%\ttotal energy and enthalpy\n\nfor j = 1:length(xcenter)\t\t% Initial conditions\n if xcenter(j) < 0.5, press(j) = pleft; rhoold(j) = rholeft; uold(j) = uleft; \n else, \t press(j) = pright; rhoold(j) = rhoright; uold(j) = uright;\n end\nend\n\n\t% Initialization of cell center variables\ntotenold = rhoold.*(0.5*uold.*uold + gammab*press./rhoold); % Total energy rho*E\ntotenleft = totenold(1); totenright = totenold(J);\nmold = rhoold.*uold;\t\t\t\t\t % Momentum m\nc = sqrt(gamma*press./rhoold);\t\t\t\t % Sound speed \nmach = uold./c;\t\t\t\t\t\t % Mach number\nenthalpy = 0.5*uold.*uold + gammab*c.^2;\t\t % Enthalpy\n\nmachplus = mach; machminus = mach;\t\t% Preallocation of \npresplus = mach; presminus = mach;\t\t% \tsplit fluxes \nflux1 = zeros(J-1,1); flux2 = flux1;\t\t% \tand Liou-Steffen \nflux3 = flux1; machhalf = flux1;\t\t%\tfluxes\nm1 = flux1; m2 = flux1;\n\nt = 0;\nfor i = 1:n, t = t + dt; \n for j = 1:J\n if mach(j) > 1\n machplus(j) = mach(j); machminus(j) = 0; \n presplus(j) = press(j); presminus(j) = 0;\n elseif mach(j) < -1\n machplus(j) = 0; machminus(j) = mach(j); \n presplus(j) = 0; presminus(j) = press(j);\n else\n machplus(j) = 0.25*(mach(j) + 1)^2;\n machminus(j) = -0.25*(mach(j) - 1)^2; \n presplus(j) = 0.5*press(j)*(1 + mach(j));\n presminus(j) = 0.5*press(j)*(1 - mach(j));\n end\n end\n\n\t% Liou-Steffen fluxes\n for j = 1:J-1, machhalf(j) = machplus(j) + machminus(j+1); end\n m1 = 0.5*(machhalf + abs(machhalf)); m2 = 0.5*(machhalf - abs(machhalf));\n rhoc = rhoold.*c;\n for j = 1:J-1\n flux1(j) = m1(j)*rhoc(j) + m2(j)*rhoc(j+1); \n flux2(j) = m1(j)*rhoc(j)*uold(j) + m2(j)*rhoc(j+1)*uold(j+1) +...\n presplus(j) + presminus(j+1); \n flux3(j) = m1(j)*rhoc(j)*enthalpy(j) + m2(j)*rhoc(j+1)*enthalpy(j+1); \n end\n \n\t% Update of state variables\n rhonew(1) = rholeft; \trhonew(J) = rhoright; \n mnew(1) = rholeft*uleft;\tmnew(J) = rhoright*uright;\n totenew(1) = totenleft; \ttotenew(J) = totenright;\n for j = 2:J-1\n rhonew(j) = rhoold(j) - lambda*(flux1(j) - flux1(j-1));\n mnew(j) = mold(j) - lambda*(flux2(j) - flux2(j-1));\n totenew(j) = totenold(j) - lambda*(flux3(j) - flux3(j-1));\n end\n uold = mnew./rhonew; press = gam1*(totenew - 0.5*mnew.*uold);\n rhoold = rhonew; \ttotenold = totenew; \tmold = mnew;\n c = sqrt(gamma*press./rhoold); \tmach = uold./c;\n enthalpy = 0.5*uold.*uold + gammab*c.^2;\nend\nentropy = log(press./rhoold.^gamma);\n\nfigure(1), clf\nsubplot(2,3,1),hold on,title('DENSITY','fontsize',14),plot(xcenter,rhonew,'o')\nsubplot(2,3,2),hold on,title('VELOCITY','fontsize',14),plot(xcenter,uold,'o')\nsubplot(2,3,3),hold on,title('PRESSURE','fontsize',14),plot(xcenter,press,'o')\nsubplot(2,3,4),hold on,title('MACHNUMBER','fontsize',14),plot(xcenter,mach,'o')\nsubplot(2,3,5),hold on,title('ENTROPY','fontsize',14),plot(xcenter,entropy,'o')\nsubplot(2,3,6),axis('off'),title('Liou-Steffen scheme','fontsize',14)\n\nRiemann\t\t% Plot exact solution\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/cfdbook/chap10.3457/AUSM_scheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6375514354712619}} {"text": "%DEMO_REGRESSION_HIER Hierarchical regression demonstration using\n% Rats data\n%\n% Description\n% The example data is taken from section 6 of Gelfand et al\n% (1990) (also used in WinBUGS/OpenBUGS), and concerns 30 young\n% rats whose weights were measured weekly for five week. This\n% demo demosntrates how to make hierarchical linear and\n% non-linear models.\n%\n% Reference\n% Gelfand, A. E., Hills, S. E., Racine-Poon, A. and Smith, A. F. \n% M. (1990) Illustration of Bayesian Inference in Normal Data\n% Models Using Gibbs Sampling. Journal of the American\n% Statistical Association 85(412):972-985.\n%\n\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nS = which('demo_regression_hier');\nL = strrep(S,'demo_regression_hier.m','demodata/rats.mat');\ndata=load(L);\nxx = data.x;\nyy = data.y;\n% Show data : 5 weight measurements per rat for 30 rats\nfigure\nplot(xx,yy,'o-')\naxis([7 37 100 400])\ntitle('Data')\ndrawnow\n\n% Reshape data\nntime = size(xx,2);\nnrats = size(yy,1);\n% All y's to one vector\ny=yy(:);\n% Repeat x for each rat\nx=reshape(repmat(xx,nrats,1),ntime*nrats,1);\n% Add ratid\nx=[x repmat([1:nrats]',ntime,1)];\n% Now 'x' consist of the inputs (ratid,time) and 'y' of the output (weight). \n% Normalize x and y\n[xn,xmean,xstd]=normdata(x);\n[yn,ymean,ystd]=normdata(y);\n\n% optmization options\nopt=optimset('TolFun',1e-4,'TolX',1e-4,'Display','on');\n\n% common Gaussian likelihood with weakly informative prior for variance\nlik=lik_gaussian('sigma2',.1,...\n 'sigma2_prior',prior_sinvchi2('s2',0.01,'nu',1));\n% common categorical covariance term\ncc=gpcf_cat('selectedVariables',2);\n\n% 1) Linear model with intercept and slope wrt time\ndisp('1) Linear model with intercept and slope wrt time')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\ncfl=gpcf_linear('coeffSigma2',1,'selectedVariables',1,...\n 'coeffSigma2_prior',prior_t());\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfl});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,1)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Linear model')\ndrawnow\n\n% 2) Linear model with hierarchical intercept\ndisp('2) Linear model with hierarchical intercept')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\ncfl=gpcf_linear('coeffSigma2',1,'selectedVariables',1,...\n 'coeffSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfl});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,2)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Linear model with hierarchical intercept')\ndrawnow\n\n% 3) Linear model with hierarchical intercept and slope\ndisp('3) Linear model with hierarchical intercept and slope')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\ncfl=gpcf_linear('coeffSigma2',1,'selectedVariables',1,...\n 'coeffSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% linear covariance term for each rat\ncfli=gpcf_prod('cf',{cfl cc});\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfl cfli});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,3)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Linear model with hierarchical intercept and slope')\ndrawnow\n\n% 4) Nonlinear model with hierarchical intercept\n% include linear part, too\ndisp('4) Nonlinear model with hierarchical intercept')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\ncfl=gpcf_linear('coeffSigma2',1,'selectedVariables',1,...\n 'coeffSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% nonlinear part\ncfs=gpcf_sexp('selectedVariables',1);\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfl cfs});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,4)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear model with hierarchical intercept')\ndrawnow\n\n% 5) Nonlinear model with hierarchical intercept and curve\n% include linear part, too\ndisp('5) Non-linear hierarchical model 1 with MAP')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\ncfl=gpcf_linear('coeffSigma2',1,'selectedVariables',1,...\n 'coeffSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% linear covariance term for each rat\ncfli=gpcf_prod('cf',{cfl cc});\n% nonlinear part\ncfs=gpcf_sexp('selectedVariables',1);\n% nonlinear covariance term for each rat\ncfsi=gpcf_prod('cf',{cfs cc});\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfl cfli cfs cfsi},...\n 'jitterSigma2',1e-6);\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,5)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 1 with MAP')\ndrawnow\n\n% 6) With increasing flexibility of the modeling function\n% we need to integrate over the parameteres\n% integrate over parameters\ndisp('6) Non-linear hierarchical model 1 with IA')\n[gps,pth,th]=gp_ia(gp,xn,yn);\n% predict and plot\nEf=gp_pred(gps,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,6)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 1 with IA')\ndrawnow\n\n% 7) Nonlinear model with hierarchical intercept and curve\n% Same as 5, but with no linear and product covariances\ndisp('7) Non-linear hierarchical model 2 with MAP')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% nonlinear part with delta distance for ratid\ncfs=gpcf_sexp('metric',metric_euclidean('components',{[1] [2]},...\n 'deltadist', [0 1], ...\n 'lengthScale_prior',prior_t()));\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfs});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% predict and plot\nEf=gp_pred(gp,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,7)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 2 with MAP')\ndrawnow\n\n% 8) With increasing flexibility of the modeling function\n% we need to integrate over the parameteres\n% integrate over parameters\ndisp('8) Non-linear hierarchical model 2 with IA')\ngps=gp_ia(gp,xn,yn);\n% predict and plot\nEf=gp_pred(gps,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,8)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 2 with IA')\ndrawnow\n\n% 9) With neuralnetwork covariance and integration over the parameters\ndisp('9) Non-linear hierarchical model 3 with IA')\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_t());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% nonlinear part with neuralnetwork covariance\ncfnn=gpcf_neuralnetwork('selectedVariables',1,'biasSigma2_prior',prior_t(),...\n 'weightSigma2_prior',prior_t());\n% nonlinear covariance term for each rat\ncfnni=gpcf_prod('cf',{cfnn cc});\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfnn cfnni});\n% optimize\ngp=gp_optim(gp,xn,yn,'opt',opt);\n% integrate over parameters\ngps=gp_ia(gp,xn,yn);\n% predict and plot\nEf=gp_pred(gps,xn,yn,xn);\nEff=reshape(denormdata(Ef,ymean,ystd),nrats,ntime);\nsubplot(3,3,9)\nplot(xx,Eff,'o-')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 3 with IA')\ndrawnow\n\n%*** Missing Data Example ***\n% In the original paper (Gelfand et al, 1990) data was also to\n% demonstrate missing data handling, by removing 1-4 weeks of data\n% for part of the rats. Handling missing data in this case is trivial\n% for GPs, too\n\ndisp('10) Missing data example')\nS = which('demo_regression_hier');\nL = strrep(S,'demo_regression_hier.m','demodata/rats.mat');\ndata=load(L);\nxx = data.x;\nyy = data.y;\nyymiss = data.ymiss;\n% Show data : 5 weight measurements per rat for 30 rats\nfigure\nplot(xx,yymiss,'o-')\naxis([7 37 100 400])\ntitle('Data')\n% Reshape data\nntime = size(xx,2);\nnrats = size(yy,1);\n% All y's to one vector\nym=yymiss(:);\n% Repeat x for each rat\nxm=reshape(repmat(xx,nrats,1),ntime*nrats,1);\n% Add ratid\nxm=[xm repmat([1:nrats]',ntime,1)];\n% Now 'x' consist of the inputs (ratid,time) and 'y' of the output (weight). \n% Normalize x and y\n[xmn,xmmean,xmstd]=normdata(xm);\n[ymn,ymmean,ymstd]=normdata(ym);\n% test x is the complete x\nxmnt=xmn;\n% remove missing data from the training data\nmissi=isnan(ym);\nymn(missi,:)=[];\nxmn(missi,:)=[];\n\n% 10) neuralnetwork covariance, IA and missing data\ncfc=gpcf_constant('constSigma2',1,'constSigma2_prior',prior_gaussian());\n% own constant term for each rat\ncfci=gpcf_prod('cf',{cfc cc});\n% nonlinear part with neuralnetwork covariance\ncfnn=gpcf_neuralnetwork('selectedVariables',1,'biasSigma2_prior',prior_gaussian('s2',10));\n% nonlinear covariance term for each rat\ncfnni=gpcf_prod('cf',{cfnn cc});\n% construct GP\ngp=gp_set('lik',lik,'cf',{cfc cfci cfnn cfnni});\n% optimize\ngp=gp_optim(gp,xmn,ymn);\n% integrate over parameters\ngps=gp_ia(gp,xmn,ymn);\n% predict and plot\nEf=gp_pred(gps,xmn,ymn,xmnt);\nEff=reshape(denormdata(Ef,ymmean,ymstd),nrats,ntime);\nEffc=Eff;Effc(isnan(ym))=NaN;\nplot(xx,Effc,'bo-',xx,Eff,'bo--')\naxis([7 37 100 400])\ntitle('Non-linear hierarchical model 3 with IA and missing data')\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/demo_regression_hier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6375514335595355}} {"text": "function perimeterEdges=findPerimeter(mesh)\n% function perimeterPoints=findPerimeter(mesh,faceIndexList)\n% Finds perimeter points.\n% Works by looking at the connection matrix (which is a list of edges)\n% The perimeter points are those points that are on edges that are used by only one face\n\n%nVerts=length(mesh.uniqueVertices);\n\n% Create a list of edges...\n[edgeList1,edgeList2]=find(triu(mesh.connectionMatrix));\n\nedgeList=[edgeList1,edgeList2];\n\ndisp ('Number of edges found:');\nnumUniqueEdges=length(edgeList);\n\ndisp (length(edgeList));\n\nsortedEdgeList=sort(edgeList')';\nsortedEdgeList=sub2ind([numUniqueEdges,numUniqueEdges],sortedEdgeList(:,1),sortedEdgeList(:,2));\n\n% Now convert the list of faces into three sets of (sorted!) edges\n% And convert the x,y coordinates into unique indices \nFaceEdges1=[mesh.uniqueFaceIndexList(:,1),mesh.uniqueFaceIndexList(:,2)];\nFaceEdges2=[mesh.uniqueFaceIndexList(:,1),mesh.uniqueFaceIndexList(:,3)];\nFaceEdges3=[mesh.uniqueFaceIndexList(:,2),mesh.uniqueFaceIndexList(:,3)];\n\n% Sort them so that [a b] and [b a] are seen as the same edge.\nsortedFaceEdges1=sort(FaceEdges1')';\nsortedFaceEdges2=sort(FaceEdges2')';\nsortedFaceEdges3=sort(FaceEdges3')';\n\n% Make them into unique index numbers to help searching and sorting\n[FaceEdges1]=sub2ind([numUniqueEdges,numUniqueEdges],sortedFaceEdges1(:,1),sortedFaceEdges1(:,2));\n[FaceEdges2]=sub2ind([numUniqueEdges,numUniqueEdges],sortedFaceEdges2(:,1),sortedFaceEdges2(:,2));\n[FaceEdges3]=sub2ind([numUniqueEdges,numUniqueEdges],sortedFaceEdges3(:,1),sortedFaceEdges3(:,2));\n\n% concatenate the list of Face edges into one long list of indices\nFaceEdges=[FaceEdges1,FaceEdges2,FaceEdges3]';\n\n% Sort them - should produce doublets of most edges 'cos most edges are part of two faces\nsortedFaceEdges=sort(FaceEdges(:));\n\n% SortedFaceEdges is a sorted list of all the edges in the face list. If all the edges are\n% members of two faces, it'll just be pairs of numbers.\n% Lone edges (part of only one face) will be on their own here as well.\n% So the list might look like \n% 1,1,2,2,3,3,4,4,5,5,6,6,7,8,9,9,10,10....\n% Where edge 7 and edge 8 are lone...\n% if n(i)==n(i+1) or n(i)==n(i-1) then n(i) is an internal edge\n% So in fact we're looking for cases where the above fails...\ndiffFromUpper=sortedFaceEdges-shift(sortedFaceEdges,[1,0]);\ndiffFromLower=sortedFaceEdges-shift(sortedFaceEdges,[-1,0]);\nloneEdges=sortedFaceEdges(find(diffFromUpper.*diffFromLower));\n\n[a b c]=unique(sortedFaceEdges(:));\n% Just a quick check:\n% 'a' tells you what unique edges there are in the faces. This should be the same as edgeList\n\nnFound=length(loneEdges);\nif (nFound>0)\n disp(nFound);\n disp ('Perimeter edges found');\n \n% In the test cases, the mesh is closed so there's no perimeter, loneEdges should be empty\n% But let's pretend we've found some...\n[perimeterEdges(:,1),perimeterEdges(:,2)]=ind2sub([numUniqueEdges,numUniqueEdges],loneEdges);\nelse\n disp ('No Perimeter edges found - mesh is closed');\n perimeterEdges=[];\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/meshOperations/findPerimeter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6375514255824343}} {"text": "% NOLM_Bifurcation_Diagram.\n% Copyright Springer 2013 A.L. Steele and S. Lynch.\nclear\nN=49999;halfN=N/2;\nlambda=1.55E-6;n2=3.2E-20;Aeff=30E-12;L=80;\nE1(1)=0;Pmax=40;phi=0;Gauss(1)=0;\nPin(1:N)=0; Pout(1:N)=0; \nphif=0*pi; E6p=0;\nkappa1=0.25;kappa2=0.8;kappa3=0.8;\nrootk1 = sqrt(kappa1); irootk1 = 1i*sqrt(1-kappa1);\nrootk2 = sqrt(kappa2); irootk2 = 1i*sqrt(1-kappa2);\nrootk3 = sqrt(kappa3); irootk3 = 1i*sqrt(1-kappa3);\nG=sqrt((1-kappa2)*(1-kappa3));\n% Ramp the power up and down\nfor n=1:N\n \n Ein = sqrt(Pmax*exp(-0.02*((n*Pmax/N-Pmax/2))^2));\n E1 = rootk3*Ein+irootk3*E6p;\n P1 = abs(E1)^2;\n \n E3 = rootk1*E1;\n E4 = irootk1*E1;\n \n phic=2*pi*n2*L*(2-kappa1)*P1/(lambda*Aeff);\n phicc=2*pi*n2*L*(1+kappa1)*P1/(lambda*Aeff);\n \n E3p = E3*exp(-1i*(phi+phic));\n E4p = E4*exp(-1i*(phi+phicc));\n \n E5 = rootk1*E3p+irootk1*E4p;\n \n Pout(n) = abs(rootk2*E5)^2;\n Pin(n) = abs(Ein)^2;\n E6 = irootk2*E5;\n \n E6p = E6*exp(1i*phif);\n \nend\n\n% Plot the bifurcation diagrams\nfigure(1)\nclf\nfsize=15;\nsubplot(2,1,1)\nhold on\nplot(Pout(1:N),'.','MarkerSize',1)\nplot(Pin(1:N),'.','MarkerSize',1);\nxlabel('Number of Ring Passes','FontSize',fsize);\nylabel('Output Power','FontSize',fsize);\nhold off\n\nsubplot(2,1,2)\nhold on\nplot(Pin,Pout,'.','MarkerSize',1);\nxlabel('Input Power','FontSize',fsize);\nylabel('Output Power','FontSize',fsize);\nhold off\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/32919-applications-of-chaos-and-nonlinear-dynamics-in-engineering-vol-1/NOLM_Bifurcation_Diagram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6375402354147031}} {"text": "% GPCG algorithm adapted for NMF\nfunction X = gpcg_nmf(Y,A,X,MaxIter,CostFun,Alpha)\n% Our implementation of GPCG;\n\n[R,T] = size(X); [M,T] = size(Y);\nbeta = 0.5; mu = 0.01; MaxSearchIter = 10;\nDiff_DF_max = 0; gamma_GP = 0.01;\n\nif CostFun == 1\n H = spalloc(R*T,R*T,T*R^2);\n Hx = A'*A;\n H = kron(speye(T),Hx); % Hessian\nend\n\nfor k = 1:MaxIter \n \n% Step 1\n Xp = X;\n if CostFun ~= 1\n H = CostFunHess(Y,A,X,Alpha); % Hessian\n end\n P = -CostFunGrad(Y,A,X,CostFun,Alpha); % Gradient Matrix\n p = P(:); % Vectorization\n \n% Step 2 \n eta = (p'*p)/(p'*(H*p)); \n for i = 0:MaxSearchIter % Armijo rule\n eta = eta*beta.^i;\n X = max(X + eta*P,0);\n if (CostFunEval(Y,A,X,CostFun,Alpha) - CostFunEval(Y,A,Xp,CostFun,Alpha)) <= (norm(X - Xp,'fro')*mu/eta)\n break;\n end\n end\n \n% Step 3 \n Z = zeros(size(X));\n Z(X > eps) = 1;\n z = vec(Z);\n\n% Step 4 \n Pc = CostFunGrad(Y,A,X,CostFun,Alpha); % Gradient Matrix\n pc = Pc(:); % Vectorization\n \n% Step 5 \n pR = z.*pc; % Reduced gradient\n if CostFun ~= 1\n H = CostFunHess(Y,A,X,Alpha); % Hessian\n end\n \nHR = repmat(z,1,R*T).*H.*repmat(z',R*T,1) + speye(R*T) - spdiags(z,0,R*T,R*T); % reduced Hessian\n \n% Step 6\n [pc,flag,relres,iter,resvec] = pcg(HR,-pR);\n P = reshape(pc,R,T); % Matricization\n \n % Step 7 \n DF = CostFunEval(Y,A,X,CostFun,Alpha);\n eta = 1; \n for j = 0:MaxSearchIter % Armijo rule\n eta = eta*beta.^j;\n X = max(X + eta*P,0);\n if (CostFunEval(Y,A,X,CostFun,Alpha) < DF) \n break;\n end\n end\n \n Fn(k) = CostFunEval(Y,A,X,CostFun,Alpha); \n \n % Stopping criterion\n DF_old = norm(Y - A*Xp,'fro'); DF = norm(Y - A*X,'fro');\n Diff_DF = DF_old - DF; Diff_DF_max = max(Diff_DF,Diff_DF_max);\n if (Diff_DF <= gamma_GP*Diff_DF_max) & (k > 1)\n break;\n end\n \nend\n\n% Cost Function \nfunction F = CostFunEval(Y,A,X,CostFun,Alpha);\n\n switch CostFun\n \n case 1 % Eucliden distance\n \n F = norm(Y - A*X,'fro'); \n \n case 2 % Alpha divergence\n \n Z = A*X + 1E2*eps;\n Y = Y + 1E2*eps;\n if Alpha == 1 % KL divergence\n F = sum(sum(Y.*log(Y./Z) + Z - Y)); \n elseif Alpha == 0 % Dual KL divergence\n F = sum(sum(Z.*log(Z./(Y+eps)) + Y - Z)); \n else % Alpha-divergence\n F = (1/Alpha)*sum(sum(Y.*( (Y./Z).^(Alpha - 1) - 1)/(Alpha - 1) + Z - Y));\n end\n end\n \n% Gradient of Cost Function \nfunction G = CostFunGrad(Y,A,X,CostFun,Alpha);\n\n switch CostFun\n \n case 1 % Eucliden distance\n \n G = A'*(A*X - Y);\n \n case 2 % Alpha divergence\n \n Z = A*X+1E2*eps;\n if ~Alpha % Dual KL divergence\n G = A'*log(Z./(Y + 1E2*eps));\n else\n G = (1/Alpha)*A'*(1 - ((Y+1E2*eps)./Z).^Alpha);\n end\n end\n\n% Hessian of Cost Function \nfunction H = CostFunHess(Y,A,X,Alpha);\n\n[R,T] = size(X);\nM = size(Y,1);\nH = spalloc(R*T,R*T,T*R^2);\nZ = A*X+1E2*eps;\nif ~Alpha % Dual KL divergence\n Zx = 1./Z + 1E2*eps;\nelse\n Zx = ((Y+1E2*eps).^Alpha)./(Z.^(Alpha + 1));\nend\n for t = 1:T\n H(((t-1)*R+1):t*R,((t-1)*R+1):t*R) = A'*repmat(Zx(:,t),1,M)*A;\n end\n \n \n \n \n \n ", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/gpcg_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6375315306540198}} {"text": "function [x,fval,exitflag,output]=cplexmiqcp(H, f, Aineq, bineq, Aeq, beq, l, Q, r, sostype, sosind, soswt, lb, ub, ctype, x0, options)\n%%\n% Purpose\n% Solve quadratically constrained linear or quadratic integer programming\n% problems.\n%\n% Syntax\n% x = cplexmiqcp(H,f,Aineq,bineq)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,\n% ub)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,\n% ub,ctype,x0)\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,\n% ub,ctype,x0,options)\n% x = cplexmiqcp(problem)\n% [x,fval] = cplexmiqcp(...)\n% [x,fval,exitflag] = cplexmiqcp(...)\n% [x,fval,exitflag,output] = cplexmiqcp(...)\n% [x,fval,exitflag,output,lambda] = cplexmiqcp(...)\n%\n% Description\n% Finds the minimum of a problem specified by\n% min 0.5*x'*H*x+f*x or f*x\n% st. Aineq*x <= bineq\n% Aeq*x = beq\n% l*x + x'*Q*x <= r\n% lb <= x <= ub\n% x belongs to BICSN\n%\n% f, bineq, beq, l, r, lb and ub are column vectors.\n% H, Aineq, Aeq, and Q are matrices.\n% x is a BICSN vector -- that is, its individual entries are each required\n% to be binary, general integer, continuous, semi-continuous or \n% semi-integer.\n%\n% x = cplexmiqcp(H,f,Aineq,bineq) solves the mixed integer programming\n% problem min 1/2*x'*H*x + f*x subject to Aineq*x <= bineq. If no\n% quadratic objective term exists, set H=[].\n%\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq) solves the preceding problem\n% while additionally satisfying the equality constraints Aeq*x = beq. If no\n% inequalities exist, set Aineq=[] and bineq=[].\n%\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r) solves the preceding\n% problem while additionally satisfying the quadratic inequality\n% constraints l*x + x'*Q*x <= r. If no equalities exist, set Aeq=[] and beq=[].\n%\n% x = cplexmiqcp(f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt) solves\n% the preceding problem with the additional requirement that the SOS\n% constraints are satisfied. If no quadratic inequalities exist, set l=[],\n% Q=[] and r=[].\n%\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,ub)\n% defines a set of lower and upper bounds on the design variables, x, so\n% that the solution is in the range lb <= x <= ub. If no SOS constraints\n% exist, set sostype=[],sosind=[] and soswt=[].\n%\n% x =\n% cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,ub,ctype\n% ) defines the types for each of the design variables. If no bounds exist,\n% set lb=[] and ub=[].\n%\n% x =\n% cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,sostype,sosind,soswt,lb,ub,x0)\n% sets the starting point to x0. If all design variables are continuous,\n% set ctype=[].\n%\n% x = cplexmiqcp(H,f,Aineq,bineq,Aeq,beq,l,Q,r,lb,ub,ctype,x0,options) minimizes\n% with the optimization options specified in the structure options, which\n% can be created using the function cplexoptimset If you do not wish to\n% give an initial point, set x0=[].\n%\n% x = cplexmiqcp(problem) where problem is a structure.\n%\n% [x,fval] = cplexmiqcp(...) returns the value of the objective function at\n% the solution x: fval = 0.5*x'*H*x + f*x.\n%\n% [x,fval,exitflag] = cplexmiqcp(...) returns a value exitflag that\n% describes the exit condition of cplexmiqcp.\n%\n% [x,fval,exitflag,output] = cplexmiqcp(...) returns a structure output\n% that contains information about the optimization.\n%\n% Input Arguments\n% H Double matrix for objective function\n% f Double column vector for objective function\n% Aineq Double matrix for linear inequality constraints\n% bineq Double column vector for linear inequality constraints\n% Aeq Double matrix for linear equality constraints\n% beq Double column vector for linear equality constraints\n% l Double column vector or matrix\n% Linear part of quadratic constraints\n% Q Double matrix or double matrix cell for quadratic\n% constraints\n% r Double or double row vector\n% Righthand side of quadratic inequality constraints\n% sostype String with possible char values '1', '2'\n% sosind Double column vector or column vector cell of indices for\n% the SOSs to be added\n% soswt Double column vector or column vector cell of weights for\n% the SOSs to be added\n% lb Double column vector of lower bounds\n% ub Double column vector of upper bounds\n% ctype String with possible char values 'B','I','C','S','N'\n% ctype(j) to 'B', 'I','C', 'S', or 'N' to indicate\n% that x(j) should be binary, general integer,\n% continuous, semi-continuous or semi-integer\n% (respectively).\n% x0 Double column vector for initial point for x\n% options Options structure created with cplexoptimset\n%\n% problem Structure containing the following fields:\n% H Double matrix for objective function\n% f Double column vector for objective function\n% Aineq Double matrix for linear inequality constraints\n% bineq Double column vector for linear inequality constraints\n% Aeq Double matrix for linear equality constraints\n% beq Double column vector for linear equality constraints\n% \t qc \t Struct vector\n% \t qc(i).a \t Double column vector for linear part of the \n% quadratic constraint\n% \t qc(i).rhs Double for righthand side for quadratic constraint\n% \t qc(i).Q \t Double matrix for quadratic part of the \n% quadratic constraint\n% \tsos \t Struct vector representing the SOSs\n% \t sos(i).type String with possible char values '1', '2'\n% \tsos(i).ind Double column vector of indices for the SOSs \t\n% to be added\n% \t sos(i).wt Double column vector of weights for the SOSs\t\n% to be added\n% lb Double column vector of lower bounds\n% ub Double column vector of upper bounds\n% ctype String with possible char values 'B','I','C','S','N'\n% ctype(j) to 'B', 'I','C', 'S', or 'N' to indicate\n% that x(j) should be binary, general integer,\n% continuous, semi-continuous or semi-integer\n% (respectively).\n% x0 Double column vector for initial point for x\n% options Options structure created with cplexoptimset\n%\n% Output Arguments\n% x Solution found by the optimization function. If exitflag > 0,\n% then x is a solution; otherwise, x is the value of the\n% optimization routine when it terminated prematurely.\n% fval Value of the objective function at the solution x\n% exitflag Integer identifying the reason the optimization algorithm\n% terminated\n% output Structure containing information about the optimization. The\n% fields of the structure are:\n% iterations Number of iterations\n% algorithm Optimization algorithm used\n% message Exit message\n% time Execution time of the algorithm\n% cplexstatus Status code of the solution\n% cplexstatusstring Status string of the solution\n%\n%\n% See also cplexoptimset\n%\n\n% ---------------------------------------------------------------------------\n% File: cplexmiqcp.m\n% ---------------------------------------------------------------------------\n% Licensed Materials - Property of IBM\n% 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55\n% Copyright IBM Corporation 2008, 2010. All Rights Reserved.\n%\n% US Government Users Restricted Rights - Use, duplication or\n% disclosure restricted by GSA ADP Schedule Contract with\n% IBM Corp.\n% ---------------------------------------------------------------------------\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/lib/cplex-12.2/cplexmiqcp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6375315305761664}} {"text": "function wulff() \n % wulff -- Program for plotting a Wulff net\n % to plot points, first calculate theta = pi*(90-azimuth)/180\n % then rho = tan(pi*(90-dip)/360), and finally the components\n % xp = rho*cos(theta) and yp = rho*cos(theta)\n % turned into function by Celso G Reyes 2017\n \n N = 50;\n cx = cos(0:pi/N:2*pi); % points on circle\n cy = sin(0:pi/N:2*pi);\n xh = [-1 1]; % horizontal axis\n yh = [0 0];\n xv = [0 0]; % vertical axis\n yv = [-1 1];\n axis([-1 1 -1 1]);\n axis('square');\n plot(xh,yh,'-k',xv,yv,'-k'); %plot green axes\n axis off;\n set(gca,'NextPlot','add');\n plot(cx,cy,'-k'); %plot white circle\n psi = 0:pi/N:pi;\n for i = 1:8 %plot great circles\n rdip = i*(pi/18); %at 10 deg intervals\n radip = atan(tan(rdip)*sin(psi));\n rproj = tan((pi/2 - radip)/2);\n x1 = rproj .* sin(psi);\n x2 = rproj .* (-sin(psi));\n y = rproj .* cos(psi);\n plot(x1,y,':k',x2,y,':k');\n end\n for i = 1:8 %plot small circles\n alpha = i*(pi/18);\n xlim = sin(alpha);\n % ylim = cos(alpha);\n x = -xlim:0.01:xlim;\n d = 1/cos(alpha);\n rd = d*sin(alpha);\n y0 = sqrt(rd*rd - (x .* x));\n y1 = d - y0;\n y2 = - d + y0;\n plot(x,y1,':k',x,y2,':k');\n end\n axis('square');\n set(gcf,'color','w');\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/wulff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.6374942713576063}} {"text": "%This computes the hand-eye calibration using the method described in \n%\"Hand-Eye Calibration Using Dual Quaternions\" from \n%Konstantinos Daniilidis\n%\n%Input:\n%Hmarker2world a 4x4xNumber_of_Views Matrix of the form\n% Hmarker2world(:,:,i) = [Ri_3x3 ti_3x1;[ 0 0 0 1]] \n% with \n% i = number of the view, \n% Ri_3x3 the rotation matrix \n% ti_3x1 the translation vector.\n% Defining the transformation of the robot hand / marker\n% to the robot base / external tracking device\n%Hgrid2cam a 4x4xNumber_of_Views Matrix (like above)\n% Defining the transformation of the grid to the camera\n%\n%Output:\n%Hcam2marker_ The transformation from the camera to the marker /\n% robot arm\n%err The residuals from the least square processes\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\nfunction [Hcam2marker_, err] = hand_eye_dual_quaternion(Hmarker2world, Hgrid2cam)\n%Our quaternions are like this (q1 q2 q3,s )\n %Get n\n n = size(Hmarker2world,3);\n %Make movements (a,B) which are interposition transformations\n %(marker2wordl and cam2grid)\n %transform A,B into dual quaternions \n for i=1:n-1\n A = inv(Hmarker2world(:,:,i+1))*Hmarker2world(:,:,i);\n B = Hgrid2cam(:,:,i+1)*inv(Hgrid2cam(:,:,i)); \n [q,qprime] = getDualQuaternion(A(1:3,1:3),A(1:3,4)); \n Qa(i).q = q;\n Qa(i).qprime = qprime;\n\n [q,qprime] = getDualQuaternion(B(1:3,1:3),B(1:3,4)); \n Qb(i).q = q;\n Qb(i).qprime = qprime;\n end\n \n %The dual quaternion is (Q.q + epsilon*Q.prime)\n %a = Qa.q, a' = Qa.prime idem for b\n S = [];\n for i=1:n-1\n S(:,:,i) = [Qa(i).q(1:3)-Qb(i).q(1:3) crossprod(Qa(i).q(1:3)+Qb(i).q(1:3)) zeros(3,1) zeros(3,3);...\n Qa(i).qprime(1:3)-Qb(i).qprime(1:3) crossprod(Qa(i).qprime(1:3)+Qb(i).qprime(1:3)) Qa(i).q(1:3)-Qb(i).q(1:3) crossprod(Qa(i).q(1:3)+Qb(i).q(1:3))]; \n end \n \n %Construct T\n T = []; \n for i=1:n-1\n T = [T S(:,:,i)']; \n end\n \n T = T';\n %SVD \n [U,S,V] = svd(T);\n \n %Solution, right null vectors of T\n v7 = V(:,7);\n v8 = V(:,8);\n \n u1 = v7(1:4);\n v1 = v7(5:8);\n \n u2 = v8(1:4);\n v2 = v8(5:8);\n %Now lambda1*v7+lambda2*v8 = [q;qprime]\n %\n %or other:\n %\n %lambda1^2*u1'*u1+2*lambda1*lambda2*u1'*u2+lambda2^2*u2'*u2 = 1 \n %and\n %lambda1^2*u1'*v1 + lambda1*lambda2*(u1'*v2+u2'*v1)+lambda2*u2'*v1 = 0\n %Setting lambda1/lambda2 = s\n %lambda1^2/lambda2^2*u1'*v1 + lambda1*lambda2/lambda2^2*(u1'*v2+u2'*v1)+lambda2^2/lambda2^2*u2'*v1 = 0\n %s^2*u1'*v1 + s*(u1'*v2+u2'*v1)+u2'*v1 = 0\n %s^2*u1'*v1 + s*(u1'*v2+u2'*v1)+u2'*v1 = 0\n a = u1'*v1;\n b = (u1'*v2+u2'*v1);\n% c = u2'*v1;\n c = u2'*v2 ;\n s = roots([a b c]);\n \n %insert into equation\n val1 = s(1)^2*u1'*u1+2*s(1)*u1'*u2+u2'*u2;\n val2 = s(2)^2*u1'*u1+2*s(2)*u1'*u2+u2'*u2;\n %Take bigger value\n if(val1>val2)\n s = s(1);\n val = val1;\n else\n s = s(2);\n val = val2;\n end\n %Get lambdas\n lambda2 = sqrt(1/val);\n lambda1 = s*lambda2;\n \n %This algorithm gives quaternion with the form of (s, q1 q2\n %q3)->contrary to the notation we used above (q1 q2 q3,s )\n %Therefore we must rearrange the elements! \n qfinal = lambda1*v7+lambda2*v8; \n q = [qfinal(2:4);qfinal(1)];\n qprime = [qfinal(6:8);qfinal(5)];\n \n %Extract transformation\n R = q2dcm(q); \n t = 2*qmult(qprime,qconj(q));\n t = t(1:3);\n \n %Assign output arguments\n Hcam2marker_ = [R -R*t;[0 0 0 1]]^-1; \n err=[];\n \n\n%Creates a dual quaternion from a rotation matrix and a translation vector \nfunction [q,qprime] = getDualQuaternion(R,t) \n %Conversion from R,t to the screw representation [d,theta,l,m]\n \n r = rodrigues(R);\n theta = norm(r);\n l = r/norm(theta);\n %Pitch d\n d = l'*t; \n %Make point c\n c = .5*(t-d*l)+cot(theta/2)*cross(l,t);\n %moment vector\n m = cross(c,l);\n %Rotation quaternion\n %(q1 q2 q3,s )\n q = [sin(theta/2)*l; cos(theta/2)];\n %Get dual\n qprime = [.5*(q(4)*t+cross(t,q(1:3)));-.5*q(1:3)'*t];\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/hand_eye_dual_quaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.6374942634698798}} {"text": "function y = geo_mean( varargin )\n\n%GEO_MEAN Geometric mean.\n% Y=GEO_MEAN(X), where X is a vector, computes the geometrix mean of X. If any\n% of the elements of X are negative, then Y=-Inf. Otherwise, it is equivalent\n% to Y=PROD(X).^(1/LENGTH(X)). All elements must be real.\n%\n% For matrices, GEO_MEAN(X) is a row vector containing the geometric means of\n% the columns. For N-D arrays, GEO_MEAN(X) is an array of the geometric means\n% taken along the first non-singleton dimension of X.\n%\n% GEO_MEAN(X,DIM) takes the geometric mean along the dimension DIM of X.\n%\n% GEO_MEAN(X,DIM,W), where W is a vector of nonnegative integers, computes a\n% weighted geometric mean Y = PROD(X.^W)^(1/SUM(W)). This is more efficient\n% than replicating the values of X W times. Note that W must be a vector,\n% even if X is a matrix, and its length must be the same as SIZE(X,DIM).\n%\n% Disciplined convex programming information:\n% GEO_MEAN is concave and nondecreasing; therefore, when used in CVX\n% specifications, its argument must be concave.\n\n%\n% Check arguments\n%\n\npersistent P\nif isempty( P ),\n P.map = cvx_remap( { 'real' ; 'concave' ; 'l_convex' ; 'l_concave' } );\n P.map = bsxfun( @and, P.map, ~cvx_remap( 'negative' ) );\n P.funcs = { @geo_mean_1, @geo_mean_2, @geo_mean_2, @geo_mean_2 };\n P.zero = 1;\n P.constant = 1;\n P.reduce = true;\n P.reverse = false;\n P.name = 'geo_mean';\n P.errargs = [];\n P.dimarg = 2;\nend\n[ sx, x, dim, w ] = cvx_get_dimension( varargin, 2 );\nif ~isempty( w ),\n if ~( numel(w)==length(w) && isnumeric(w) && isreal(w) && all(w>=0) ),\n cvx_throw( 'Third argument must be a vector of nonnegative numbers.' );\n elseif ~any( w ),\n cvx_throw( 'The weight vector cannot be all zeros.')\n elseif numel( w ) ~= sx(dim),\n cvx_throw( 'Third argument must be a vector of length %d', sx(dim) );\n else\n w = w(:) / sum(w);\n end\nend\ny = cvx_reduce_op( P, x, dim, w );\n\nfunction y = geo_mean_1( x, w )\n[ nx, nv ] = size( x );\nif isempty( w ), \n w = 1 / nx;\nelse\n w = repmat( w, [ 1, nv ] ); \nend\ny = prod( x .^ w, 1 );\n\nfunction y = geo_mean_2( x, w ) %#ok\n[ nx, nv ] = size( x );\ncvx_begin\n hypograph variable y(1,nv);\n { linearize(x), y } == geo_mean_cone( [nx,nv], 1, w, 'func' ); %#ok\n cvx_setnneg(y);\ncvx_end\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.% Copyright 2005-2014 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/functions/geo_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6374658149617446}} {"text": "% EX_MAXWELL_SRC_CUBE: solve Maxwell source problem in a thick ring.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nclear problem_data \n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_thick_ring.txt';\n\n% Type of boundary conditions\nproblem_data.nmnn_sides = [1 2];\nproblem_data.drchlt_sides = [3 4 5 6];\n\n% Physical parameters\nproblem_data.c_mass = @(x, y, z) ones(size(x));\nproblem_data.c_stiff = @(x, y, z) ones(size(x));\n\n% Source and boundary terms\nproblem_data.f = @(x, y, z) cat(1, ...\n reshape (2*sin(y), [1, size(x)]), ...\n reshape (2*sin(x), [1, size(x)]), ...\n reshape (x .* y, [1, size(x)]));\nproblem_data.g = @(x, y, z, ind) test_maxwell_thick_ring_g_nmnn (x, y, z, ind);\nproblem_data.h = @(x, y, z, ind) cat(1, ...\n reshape (sin(y), [1, size(x)]), ...\n reshape (sin(x), [1, size(x)]), ...\n reshape (x .* y, [1, size(x)]));\n\n% Exact solution (optional)\nproblem_data.uex = @(x, y, z) cat(1, ...\n reshape (sin(y), [1, size(x)]), ...\n reshape (sin(x), [1, size(x)]), ...\n reshape (x .* y, [1, size(x)]));\nproblem_data.curluex = @(x, y, z) cat(1, ...\n reshape (x, [1, size(x)]), ...\n reshape (-y, [1, size(x)]), ...\n reshape (cos(x) - cos(y), [1, size(x)]));\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nclear method_data\nmethod_data.degree = [2 2 2]; % Degree of the bsplines\nmethod_data.regularity = [1 1 1]; % Regularity of the splines\nmethod_data.nsub = [3 3 3]; % Number of subdivisions\nmethod_data.nquad = [3 3 3]; % Points for the Gaussian quadrature rule\n\n% 3) CALL TO THE SOLVER\n[geometry, msh, space, u] = solve_maxwell_src (problem_data, method_data);\n\n% 4) POST-PROCESSING\n% 4.1) EXPORT TO PARAVIEW\noutput_file = 'maxwell_thick_ring_Deg2_Reg1_Sub3';\n\nvtk_pts = {linspace(0, 1, 15), linspace(0, 1, 15), linspace(0, 1, 15)};\nfprintf ('The result is saved in the file %s \\n \\n', output_file);\nsp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')\n\n% 4.2) Comparison with the exact solution\n[error_hcurl, error_l2] = ...\n sp_hcurl_error (space, msh, u, problem_data.uex, problem_data.curluex)\n\n%!demo\n%! ex_maxwell_src_thick_ring\n\n%!test\n%! problem_data.geo_name = 'geo_thick_ring.txt';\n%! problem_data.nmnn_sides = [1 2];\n%! problem_data.drchlt_sides = [3 4 5 6];\n%! problem_data.c_mass = @(x, y, z) ones(size(x));\n%! problem_data.c_stiff = @(x, y, z) ones(size(x));\n%! problem_data.f = @(x, y, z) cat(1, ...\n%! reshape (2*sin(y), [1, size(x)]), ...\n%! reshape (2*sin(x), [1, size(x)]), ...\n%! reshape (x .* y, [1, size(x)]));\n%! problem_data.g = @(x, y, z, ind) test_maxwell_thick_ring_g_nmnn (x, y, z, ind);\n%! problem_data.h = @(x, y, z, ind) cat(1, ...\n%! reshape (sin(y), [1, size(x)]), ...\n%! reshape (sin(x), [1, size(x)]), ...\n%! reshape (x .* y, [1, size(x)]));\n%! problem_data.uex = @(x, y, z) cat(1, ...\n%! reshape (sin(y), [1, size(x)]), ...\n%! reshape (sin(x), [1, size(x)]), ...\n%! reshape (x .* y, [1, size(x)]));\n%! problem_data.curluex = @(x, y, z) cat(1, ...\n%! reshape (x, [1, size(x)]), ...\n%! reshape (-y, [1, size(x)]), ...\n%! reshape (cos(x) - cos(y), [1, size(x)]));\n%! method_data.degree = [2 2 2]; % Degree of the bsplines\n%! method_data.regularity = [1 1 1]; % Regularity of the splines\n%! method_data.nsub = [3 3 3]; % Number of subdivisions\n%! method_data.nquad = [3 3 3]; % Points for the Gaussian quadrature rule\n%! [geometry, msh, space, u] = solve_maxwell_src (problem_data, method_data);\n%! [error_hcurl, error_l2] = sp_hcurl_error (space, msh, u, problem_data.uex, problem_data.curluex);\n%! assert (msh.nel, 27)\n%! assert (space.ndof, 300)\n%! assert (error_l2, 0.0643150154230899, 1e-14)\n%! assert (error_hcurl, 0.141137345617213, 1e-14)\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/examples/maxwell/ex_maxwell_src_thick_ring.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6374141122300582}} {"text": "function [M] = covar(x1,x2,k,n)\n%\n% this function calculates the lag k covariance matrice\n% for three time series. Each time series is a 1xn vector\n%\nif k == 0\n %\n % lag 0 covariance matrix\n %\n p1=find(x1~=0);\n p2=find(x2~=0);\n %p3=find(x3~=0);\n p12=find(x1~=0 & x2~=0);\n %p13=find(x1~=0 & x3~=0);\n %p23=find(x2~=0 & x3~=0);\n % m1=mean(x1(p1));\n % m2=mean(x2(p2));\n % m3=mean(x3(p3));\n m1=0; % x1, x2 and x3 are residuals characterized by N(0,1)\n m2=0;\n %m3=0;\n % M(1,1)=std(x1(p1));\n % M(2,2)=std(x2(p2));\n % M(3,3)=std(x3(p3));\n M(1,1)=1; % x1, x2 and x3 are residuals characterized by N(0,1)\n M(2,2)=1;\n %M(3,3)=1;\n M(1,2)=sum((x1(p12)-m1).*(x2(p12)-m2))/(length(p12)-1);\n M(2,1)=M(1,2);\n %M(1,3)=sum((x1(p13)-m1).*(x3(p13)-m3))/(length(p13)-1);\n %M(3,1)=M(1,3);\n %M(2,3)=sum((x2(p23)-m2).*(x3(p23)-m3))/(length(p23)-1);\n %M(3,2)=M(2,3);\nelse\n %\n % lag k covariance matrix\n %\n x1t=x1(1:n-k);\n x1tk=x1(k+1:n);\n x2t=x2(1:n-k);\n x2tk=x2(k+1:n);\n %x3t=x3(1:n-k);\n %x3tk=x3(k+1:n);\n p1t=find(x1t~=0);\n p2t=find(x2t~=0);\n %p3t=find(x3t~=0);\n p1tk=find(x1tk~=0);\n p2tk=find(x2tk~=0);\n %p3tk=find(x3tk~=0); \n % m1t=mean(x1t(p1t));\n % m1tk=mean(x1tk(p1tk));\n % m2t=mean(x2t(p2t));\n % m2tk=mean(x2tk(p2tk));\n % m3t=mean(x3t(p3t));\n % m3tk=mean(x3tk(p3tk));\n m1t=0; % x1, x2 and x3 are residuals characterized by N(0,1)\n m1tk=0;\n m2t=0;\n m2tk=0;\n %m3t=0;\n %m3tk=0;\n %\n p11=find(x1t~=0 & x1tk~=0);\n p22=find(x2t~=0 & x2tk~=0);\n %p33=find(x3t~=0 & x3tk~=0);\n p12=find(x1t~=0 & x2tk~=0);\n %p13=find(x1t~=0 & x3tk~=0);\n p21=find(x2t~=0 & x1tk~=0);\n %p23=find(x2t~=0 & x3tk~=0);\n %p31=find(x3t~=0 & x1tk~=0);\n %p32=find(x3t~=0 & x2tk~=0);\n %\n M(1,1)=sum((x1t(p11)-m1t).*(x1tk(p11)-m1tk))/(length(p11)-k-1);\n M(2,2)=sum((x2t(p22)-m2t).*(x2tk(p22)-m2tk))/(length(p22)-k-1);\n %M(3,3)=sum((x3t(p33)-m3t).*(x3tk(p33)-m3tk))/(length(p33)-k-1);\n M(1,2)=sum((x1t(p12)-m1t).*(x2tk(p12)-m2tk))/(length(p12)-k-1);\n M(2,1)=sum((x2t(p21)-m2t).*(x1tk(p21)-m1tk))/(length(p21)-k-1);\n %M(1,3)=sum((x1t(p13)-m1t).*(x3tk(p13)-m3tk))/(length(p13)-k-1);\n %M(3,1)=sum((x3t(p31)-m3t).*(x1tk(p31)-m1tk))/(length(p31)-k-1);\n %M(2,3)=sum((x2t(p23)-m2t).*(x3tk(p23)-m3tk))/(length(p23)-k-1);\n %M(3,2)=sum((x3t(p32)-m3t).*(x2tk(p32)-m2tk))/(length(p32)-k-1);\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29136-stochastic-weather-generator-weagets/WeaGETS/covar2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6374141026890655}} {"text": "%% This function will generate the simulation data of an ODE function.\n%You could determine the noise level by input variable \"Noise\". If you do\n%not want any noise, set noise to zero. Please indicate whether your ODE\n%function have control input, if the answer is yes, please set the\n%\"Control\" as 1.\n\n% Last Update: 2019/04/21\n% Coded By: K\n\nfunction [d_Data,Data]=Get_Sim_Data(ODE,state0,u,tspan,Noise,Control,Shuffle)\n%% Get the size of the state and control\n[N1,M1]=size(state0);\n[N2,M2]=size(u);\n\n%% Get simulation data by simulating the system using ODE113\n\n% Determine the left hand side derivative\nif Control==1\n y_list(1,:)=state0;\n d_y_list(1,:)=ODE(0,y_list(1,:),u(1,:));\n for i=2:length(u)\n [t_1,y_1] = ode15s(@(t_1,y_1)ODE(t_1,y_1,u(i-1,:)),tspan(1,i-1:i),state0);\n y_list(i,:)=y_1(end,:);\n d_y_list(i,:)=ODE(0,y_list(i,:),u(i,:));\n state0=y_list(i,:)';\n end\nelse\n %Simulate the system ODE\n [t,y]=ode15s(@(t,y)ODE(t,y),tspan,state0);\n y_list=y;\n % Get the derivative data\n d_y_list=ODE(0,y_list')';\nend\n\n%% Add some noise to the system\nfor i=1:N1\n Data(:,i)=y_list(:,i)+Noise*randn(size(y_list(:,i)));\nend\n%\nfor i=1:M2\n d_Data(:,i)=d_y_list(:,i)+Noise*randn(size(d_y_list(:,i)));\nend\n\n%% Shuffle the data\nif Shuffle==1\n Sequence=randperm(size(Data,1));\n Data=Data(Sequence,:);\n d_Data=d_Data(Sequence,:);\nend\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/NoiseSensitivity/Michaelis-Menten kinetics/Functions/Get_Sim_Data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6373029846431818}} {"text": "function [out,varargout] = runningExtreme(input,nSamples,type)\n% runningmin - Computes a running extreme of an input vector or matrix\n% Optional file header info (to give more details about the function than in the H1 line)\n% Syntax: out = runningmin(input,nSamples,type)\n% input - vector or matrix of data to return the running min or max from\n% nSamples - The size of the window to check for mins or maxes\n% type - 'min','max', or 'both' (default) which type of extremes to return\n% out - running minimum or maximum requested. If both minimum is returned\n% first, then maximum\n% Example\n% [runMin,runMax] = runningExtreme(data,31,'both')\n%\n% Subfunctions: vanherk\n% See also: min, max, sort\n%% AUTHOR : Dan Kominsky\n%%\n\nif nargin<2\n\terror('RunningExtreme:notEnoughInputs','Invalid Usage - must specify window size');\nelseif nargin ==2\n\ttype = 'both';\nend\n\nif ~mod(nSamples,2)\n\twarning('RunningExtreme:evenWindowSize','Running Min/Max is not meaningful for a windown with an even number of samples');\n\tnSamples = nSamples+1;\nend\n\n[input,dimShift]=shiftdim(input);\n\nswitch lower(type)\n\tcase 'min'\n\t\tout=vanherk(input,nSamples,'min');% Create output for minimum\n\tcase 'max'\n\t\tout=vanherk(input,nSamples,'max'); % Create output for maximum\n\totherwise\n\t\tout=vanherk(input,nSamples,'max');% Create output for maximum\n\t\tvarargout{1} = out; % Transfer to the second output\n\t\tout=vanherk(input,nSamples,'min');% Create output for minimum\nend\nif dimShift\n\tout = shiftdim(out,-dimShift);% if we transposed, undo to return the same shape as we got.\n\tif nargout>1\n\t\tvarargout{1} = shiftdim(varargout{1},-dimShift);\n\tend\nend\n\nend\n\nfunction Y = vanherk(X,N,TYPE)\n% VANHERK Fast max/min 1D filter\n%\n% Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row\n% vector X using a N-length filter.\n% The filtering type is defined by TYPE = 'max' or 'min'. This function\n% uses the van Herk algorithm for min/max filters that demands only 3\n% min/max calculations per element, independently of the filter size.\n%\n% If X is a 2D matrix, each column will be filtered separately.\n% X can be uint8 or double. If X is uint8 the processing is quite faster, so\n% dont't use X as double, unless it is really necessary.\n%\n\n% Initialization\n% if strcmp(direc,'col')\n% X = X';\n% end\nswitch lower(TYPE)\n\tcase 'max'\n\t\tmaxfilt = 1;\n\tcase 'min'\n\t\tmaxfilt = 0;\n\totherwise\n\t\terror([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.'])\nend\n\n% Correcting X size\nfixsize = 0;\naddel = 0;\nif mod(size(X,1),N) ~= 0\n\tfixsize = 1;\n\taddel = N-mod(size(X,1),N);\n\tif maxfilt\n\t\tf = [X; -Inf*ones(addel,size(X,2)) ]; % Change from adding zeros\n\telse\n\t\tf = [X; Inf*ones([addel size(X,2)])];\n\t\t% f = [X; repmat(X(end,:),addel,1)]; % Adds a replication of the end of the matrix\n\tend\nelse\n\tf = X;\nend\nlf = size(f,1); % # of elements in adjusted matrix\nlx = size(X,1); % # of elements in original matrix\nclear X\n\n% Declaring aux. mat.\ng = f;\nh = g;\n\n% Filling g & h (aux. mat.)\nig = (1:N:size(f,1)).'; % First element of each window\nih = ig + N - 1; % Last element of each window\n\nif maxfilt\n\tfor i = 2 : N\n\t\tigold = ig;\n\t\tihold = ih;\n\n\t\tig = ig + 1;\n\t\tih = ih - 1;\n\n\t\tg(ig,:) = max(f(ig,:),g(igold,:));\n\t\th(ih,:) = max(f(ih,:),h(ihold,:));\n\tend\nelse\n\tfor i = 2 : N\n\t\tigold = ig;\n\t\tihold = ih;\n\n\t\tig = ig + 1;\n\t\tih = ih - 1;\n\n\t\tg(ig,:) = min(f(ig,:),g(igold,:));\n\t\th(ih,:) = min(f(ih,:),h(ihold,:));\n\tend\nend\nclear f\n\n\nif fixsize % If we had to pad the data\n\tif addel > (N-1)/2 % If the padding is more than half a zone\n\t\tig = (N : 1 : lf - addel + floor((N-1)/2)).' ;\n\t\tih = ( 1 : 1 : lf-N+1 - addel + floor((N-1)/2)).';\n\t\tif maxfilt\n\t\t\tY = [ g(1+ceil((N-1)/2):N-1,:); max(g(ig,:), h(ih,:)) ];\n\t\telse\n\t\t\tY = [ g(1+ceil((N-1)/2):N-1,:); min(g(ig,:), h(ih,:)) ];\n\t\tend\n\telse\n\t\tig = ( N : 1 : lf ).';\n\t\tih = ( 1 : 1 : lf-N+1 ).';\n\t\tif maxfilt\n\t\t\tY = [ g(1+ceil((N-1)/2):N-1,:); max(g(ig,:), h(ih,:)); h(lf-N+2:lf-N+1+floor((N-1)/2)-addel,:) ];\n\t\telse\n\t\t\tY = [ g(1+ceil((N-1)/2):N-1,:); min(g(ig,:), h(ih,:)); h(lf-N+2:lf-N+1+floor((N-1)/2)-addel,:) ];\n\t\tend\n\tend\nelse % not fixsize (addel=0, lf=lx)\n\tig = ( N : 1 : lx ).';\n\tih = ( 1 : 1 : lx-N+1 ).';\n\tif maxfilt\n\t\tY = [ g(N-ceil((N-1)/2):N-1,:); max( g(ig,:), h(ih,:) ); h(lx-N+2:lx-N+1+floor((N-1)/2),:) ];\n\telse\n\t\tY = [ g(N-ceil((N-1)/2):N-1,:); min( g(ig,:), h(ih,:) ); h(lx-N+2:lx-N+1+floor((N-1)/2),:) ];\n\tend\nend\n\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18551-running-extrema/runningExtreme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6373029625005037}} {"text": "% Data File DTXY1\n% Dynamics of a particle, thrown\n% with initial velocity v0 under \n% angle \"alfa' to the Horizon\n m = 'm'; % mass of the particle\n Fx = '-k*xt'; % Projections of forces \n Fy = '-k*yt - m*9.81'; % on axis x and y\n x0 = '0'; % Initial\n y0 = '0'; % coordinates\n v0 = 'v0'; % Initial velocity\n alfa = 'alfa'; % angle between v0 and horizon\n Tend = 20; % upper bound of integration\n eps = 1e-10; % desirable accuracy\n np = 2; % number of parameters\n P{1} = 'm'; % mass of the particle\n P{2} = 'k'; % coefiicient of resistance", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/DATA Files/DTXY1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6372978598727329}} {"text": "% Fig. 5.24 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n% script for Figure 5.24, Lead design.\nnp=1;\ndp=[1 1 0];\nnc=[1 2];\ndc=[1 10];\nnol=conv(np,nc);\ndol=conv(dp,dc);\nrlocus(nol,dol)\naxis([-19 1 -7.5 7.5])\ntitle('Figure 5.24 Root locus for lead design')\nhold on\nr=roots([1 11 80 140]);\nplot(r,'*')\nz=0:.1:.9;\n wn=2:2:19;\n sgrid(z, wn)\n hold off", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig5_24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6372673699803726}} {"text": "%This Matlab script can be used to reproduce Figure 7.3 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.01 (Last edited: 2019-03-27)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Number of BSs\nL = 16;\n\n%Number of UEs per BS\nK = 10;\n\n%Number of BS antennas\nM = 100;\n\n%Define the pilot reuse factor\nf = 2;\n\n%Select the number of setups with random UE locations\nnbrOfSetups = 100;\n\n%Select the number of channel realizations per setup\nnbrOfRealizations = 200;\n\n\n%% Propagation parameters\n\n%Communication bandwidth\nB = 20e6;\n\n%Total uplink transmit power per UE (mW)\np = 100;\n\n%Define noise figure at BS (in dB)\nnoiseFigure = 7;\n\n%Compute noise power\nnoiseVariancedBm = -174 + 10*log10(B) + noiseFigure;\n\n%Select length of coherence block\ntau_c = 200;\n\n%Use the approximation of the Gaussian local scattering model\naccuracy = 2;\n\n%Angular standard deviation in the local scattering model (in degrees)\nASDdeg = 10;\n\n%Set the range of Delta values in the power control policy of (7.10)\nDeltadB = 0:10:20;\n\n%Generate uncorrelated covariance matrices\nRuncorr = repmat(eye(M),[1 1 K L L]);\n\n\n%Prepare to save simulation results\nsumSE_MR = zeros(L*K*nbrOfSetups,length(DeltadB));\nsumSE_ZF = zeros(L*K*nbrOfSetups,length(DeltadB));\nsumSE_SMMSE = zeros(L*K*nbrOfSetups,length(DeltadB));\nsumSE_RZF = zeros(L*K*nbrOfSetups,length(DeltadB));\nsumSE_MMMSE = zeros(L*K*nbrOfSetups,length(DeltadB));\n\n\n%% Go through all setups\nfor n = 1:nbrOfSetups\n \n %Output simulation progress\n disp([num2str(n) ' setups out of ' num2str(nbrOfSetups)]);\n \n %Compute channel statistics for one setup\n [R,channelGaindB] = functionExampleSetup(L,K,M,accuracy,ASDdeg);\n \n %Compute the normalized average channel gain, where the normalization\n %is based on the noise power\n channelGainOverNoiseOriginal = channelGaindB - noiseVariancedBm;\n \n \n %Go through all values of Delta \n for s = 1:length(DeltadB)\n \n %Extract the average channel gains before power control\n channelGainOverNoise = channelGainOverNoiseOriginal;\n \n %Go through all cells\n for j = 1:L\n \n %Compute beta_j,min in the power control policy of (7.10)\n betajMin = min(channelGainOverNoiseOriginal(:,j,j));\n \n %Scale the average channel gains by applying the power control\n %policy of (7.10). Note that we are including this power\n %control here so that we can then view it as if all UEs of \n %transmitting at maximum power\n differenceSNR = channelGainOverNoiseOriginal(:,j,j)-betajMin;\n backoff = differenceSNR-DeltadB(s);\n backoff(backoff<0) = 0;\n \n channelGainOverNoise(:,j,:) = channelGainOverNoiseOriginal(:,j,:)-repmat(backoff,[1 1 L]);\n \n end\n\n \n %Generate channel realizations with estimates and estimation\n %error correlation matrices\n [Hhat,C,tau_p,Rscaled] = functionChannelEstimates(R,channelGainOverNoise,nbrOfRealizations,M,K,L,p,f);\n \n %Compute SEs using Theorem 4.1\n [SE_MR,SE_ZF,SE_SMMSE,SE_RZF,SE_MMMSE] = functionComputeSE_UL(Hhat,C,Rscaled,tau_c,tau_p,nbrOfRealizations,M,K,L,p);\n \n %Save results\n sumSE_MR(1+(n-1)*K*L:n*K*L,s) = SE_MR(:);\n sumSE_ZF(1+(n-1)*K*L:n*K*L,s) = SE_ZF(:);\n sumSE_SMMSE(1+(n-1)*K*L:n*K*L,s) = SE_SMMSE(:);\n sumSE_RZF(1+(n-1)*K*L:n*K*L,s) = SE_RZF(:);\n sumSE_MMMSE(1+(n-1)*K*L:n*K*L,s) = SE_MMMSE(:);\n \n %Delete large matrices\n clear Hhat C Rscaled;\n \n end\n \n %Delete large matrices\n clear R;\n \nend\n\n\n%% Plot the simulation results\n\nfigure;\nhold on; box on;\n\nplot(sort(sumSE_MR(:,1)),linspace(0,1,K*L*nbrOfSetups),'k-','LineWidth',1);\nplot(sort(sumSE_MR(:,2)),linspace(0,1,K*L*nbrOfSetups),'b-.','LineWidth',1);\nplot(sort(sumSE_MR(:,3)),linspace(0,1,K*L*nbrOfSetups),'r--','LineWidth',1);\nxlabel('SE per UE [bit/s/Hz]');\nylabel('CDF');\nlegend('\\Delta=0 dB','\\Delta=10 dB','\\Delta=20 dB','Location','SouthEast');\nxlim([0 8]);\n\nfigure;\nhold on; box on;\n\nplot(sort(sumSE_RZF(:,1)),linspace(0,1,K*L*nbrOfSetups),'k-','LineWidth',1);\nplot(sort(sumSE_RZF(:,2)),linspace(0,1,K*L*nbrOfSetups),'b-.','LineWidth',1);\nplot(sort(sumSE_RZF(:,3)),linspace(0,1,K*L*nbrOfSetups),'r--','LineWidth',1);\nxlabel('SE per UE [bit/s/Hz]');\nylabel('CDF');\nlegend('\\Delta=0 dB','\\Delta=10 dB','\\Delta=20 dB','Location','SouthEast');\nxlim([0 8]);\n\nfigure;\nhold on; box on;\n\nplot(sort(sumSE_MMMSE(:,1)),linspace(0,1,K*L*nbrOfSetups),'k-','LineWidth',1);\nplot(sort(sumSE_MMMSE(:,2)),linspace(0,1,K*L*nbrOfSetups),'b-.','LineWidth',1);\nplot(sort(sumSE_MMMSE(:,3)),linspace(0,1,K*L*nbrOfSetups),'r--','LineWidth',1);\nxlabel('SE per UE [bit/s/Hz]');\nylabel('CDF');\nlegend('\\Delta=0 dB','\\Delta=10 dB','\\Delta=20 dB','Location','SouthEast');\nxlim([0 8]);\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section7_figure3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6372673618250693}} {"text": "function [data, Ht] = bekk_simulate(T,k,parameters,p,o,q,type)\n% Simulation of symmetric and asymmetric BEKK(p,o,q) multivariate volatility models\n%\n% USAGE:\n% [DATA,HT] = bekk_simulate(T,K,PARAMETERS,P,O,Q,TYPE)\n%\n% INPUTS:\n% T - Either a scalar containing the length of the series to simulate, or a T by K matrix \n% of simulated random variables. The default is to use standard normals. Providing \n% a T by K matrix allows other distributions to be used.\n% PARAMETERS - Vector of parameters. The form of the parameters depends on the TYPE. \n% 'Scalar':\n% [CC' a(1) ... a(p) g(1) ... g(o) b(1) ... b(q)]' (all scalars)\n% 'Diagonal' \n% [CC' diag(A(:,:,1))' ... diag(A(:,:,p))' diag(G(:,:,1))' ... diag(G(:,:,o))' diag(B(:,:,1))' ... diag(B(:,:,p))']'\n% 'Full' \n% [CC' f(A(:,:,1)) ... f(A(:,:,p)) f(G(:,:,1)) ... f(G(:,:,o)) f(B(:,:,1)) ... f(B(:,:,q))]'\n% where CC = chol2vec(C')' and f(M) = M(:)'\n% P - Positive, scalar integer representing the number of symmetric innovations\n% O - Non-negative, scalar integer representing the number of asymmetric innovations\n% Q - Non-negative, scalar integer representing the number of conditional covariance lags\n% TYPE - String, one of :\n% 'Scalar' (Default) \n% 'Diagonal'\n% 'Full'\n%\n% OUTPUTS:\n% DATA - A T by K matrix of simulated data\n% HT - A [K K T] dimension matrix of conditional covariances\n%\n% COMMENTS:\n% The dynamics of a BEKK are given by \n% \n% H(:,:,t) = C*C' +\n% A(:,:,1)'*OP(:,:,t-1)*A(:,:,1) + ... + A(:,:,p)'*OP(:,:,t-1)*A(:,:,p) +\n% G(:,:,1)'*OPA(:,:,t-1)*G(:,:,1) + ... + G(:,:,o)'*OPA(:,:,t-1)*G(:,:,o) +\n% B(:,:,1)'*G(:,:,t-1)*B(:,:,1) + ... + B(:,:,q)'*OP(:,:,t-1)*B(:,:,q)\n%\n% where in the scalar model A(:,:,i) = a(i)*eye(K) (similarly for G and B).\n%\n% EXAMPLES:\n% % Scalar with A.^2=.05, G.^2=.1 and B.^2=.88\n% CCp = [1 .5;.5 4];\n% parameters = [chol2vec(chol(CCp)');sqrt([.05,.10,.88])']\n% [data,Ht] = bekk_simulate(1000,2,parameters,1,1,1,'Scalar')\n% % Diagonal \n% parameters = [chol2vec(chol(CCp)');sqrt([.05 .07 .93 .88])']\n% [data,Ht] = bekk_simulate(1000,2,parameters,1,0,1,'Diagonal')\n%\n% See also BEKK\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif isscalar(T)\n e = randn(2*T,k);\nelse\n e = T;\n if size(e,2)~=k\n error('T must have K columns when providing simulated random numbers.')\n end\n T = size(e,1);\n e = [e(ceil(rand(T,1)*T),:);e];\nend\n\nif strcmpi(type,'Scalar')\n type = 1;\nelseif strcmpi(type,'Diagonal')\n type = 2;\nelseif strcmpi(type,'Full')\n type = 3;\nelse\n error('TYPE must be ''Scalar'', ''Diagonal'' or ''Full''.')\nend\n\nif p<=0 || floor(p)~=p\n error('P must be a positive scalar integer.')\nend\nif o<0 || floor(o)~=o\n error('O must be a positive scalar integer.')\nend\nif q<0 || floor(q)~=q\n error('Q must be a positive scalar integer.')\nend\n\nk2 = k*(k+1)/2;\nswitch type\n case 1\n count = p+o+q;\n case 2\n count = (p+o+q)*k;\n case 3\n count = (p+o+q)*k*k;\nend\ncount = count + k2;\nif length(parameters)~=count\n error('PARAMETERS does not have the expected number of elements.')\nend\n[C,A,G,B] = bekk_parameter_transform(parameters,p,o,q,k,type);\nm = zeros(k*k);\nfor i=1:p\n m = m + kron(A(:,:,i),A(:,:,i));\nend\nfor i=1:o\n m = m + 0.5*kron(G(:,:,i),G(:,:,i));\nend\nfor i=1:q\n m = m + kron(B(:,:,i),B(:,:,i));\nend\n\nif max(eigs(m))>1\n backCast = C/.001;\n warning('MFE:nonstationary','The parameters do not correspond to the stationary region.')\nelse\n backCast = ((eye(k*k)-m)\\eye(k*k))*C(:);\n backCast = reshape(backCast,k,k);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nHt = repmat(eye(k),[1 1 2*T]);\neta = zeros(size(e));\nfor i=1:(2*T)\n Ht(:,:,i) = C;\n for j=1:p\n if (i-j)<=0\n Ht(:,:,i) = Ht(:,:,i) + A(:,:,j)'*backCast*A(:,:,j);\n else\n Ht(:,:,i) = Ht(:,:,i) + A(:,:,j)'*(e(i-j,:)'*e(i-j,:))*A(:,:,j);\n end\n end\n for j=1:o\n if (i-j)<=0\n Ht(:,:,i) = Ht(:,:,i) + G(:,:,j)'*backCast*G(:,:,j);\n else\n Ht(:,:,i) = Ht(:,:,i) + G(:,:,j)'*(eta(i-j,:)'*eta(i-j,:))*G(:,:,j);\n end\n end \n for j=1:q\n if (i-j)<=0\n Ht(:,:,i) = Ht(:,:,i) + B(:,:,j)'*backCast*B(:,:,j);\n else\n Ht(:,:,i) = Ht(:,:,i) + B(:,:,j)'*Ht(:,:,i-j)*B(:,:,j);\n end\n end\n Ht12 = Ht(:,:,i)^(0.5);\n e(i,:) = e(i,:)*Ht12;\n eta(i,:) = e(i,:).*(e(i,:)<0);\nend\n\ndata = e(T+1:2*T,:);\nHt = Ht(:,:,T+1:2*T);", "meta": {"author": "bashtage", "repo": "mfe-toolbox", "sha": "9622b6c546bc6d649fd9bf0a36a7fcd53872e04a", "save_path": "github-repos/MATLAB/bashtage-mfe-toolbox", "path": "github-repos/MATLAB/bashtage-mfe-toolbox/mfe-toolbox-9622b6c546bc6d649fd9bf0a36a7fcd53872e04a/multivariate/bekk_simulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6372673588950423}} {"text": "classdef CEC2017_F22 < PROBLEM\n% \n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n O; % Optimal decision vector\n Mat;\t% Rotation matrix\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n CallStack = dbstack('-completenames');\n load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n obj.O = Data{12}.o;\n obj.M = 1;\n if isempty(obj.D) || obj.D < 30\n obj.D = 10;\n obj.Mat = Data{12}.M_10;\n elseif obj.D < 50\n obj.D = 30;\n obj.Mat = Data{12}.M_30;\n elseif obj.D < 100\n obj.D = 50;\n obj.Mat = Data{12}.M_50;\n else\n obj.D = 100;\n obj.Mat = Data{12}.M_100;\n end\n obj.lower = zeros(1,obj.D) - 100;\n obj.upper = zeros(1,obj.D) + 100;\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n Z = Z*obj.Mat';\n PopObj = sum(100*(Z(:,1:end-1).^2-Z(:,2:end)).^2+(Z(:,1:end-1)-1).^2,2);\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n Z = Z*obj.Mat';\n PopCon(:,1) = sum(Z.^2-10*cos(2*pi*Z)+10,2) - 100;\n PopCon(:,2) = sum(Z,2) - 2*size(Z,2);\n PopCon(:,3) = 5 - sum(Z,2);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Single-objective optimization/CEC 2017/CEC2017_F22.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6372673520092919}} {"text": "% first casadi test for mpc fpr mobile robots\nclear all\nclose all\nclc\n\n% CasADi v3.4.5\n% addpath('C:\\Users\\mehre\\OneDrive\\Desktop\\CasADi\\casadi-windows-matlabR2016a-v3.4.5')\n% CasADi v3.5.5\naddpath('C:\\Users\\mehre\\OneDrive\\Desktop\\CasADi\\casadi-windows-matlabR2016a-v3.5.5')\n\nimport casadi.*\n\nT = 0.2; %[s]\nN = 10; % prediction horizon\nrob_diam = 0.3;\n\nv_max = 0.6; v_min = -v_max;\nomega_max = pi/4; omega_min = -omega_max;\n\nx = SX.sym('x'); y = SX.sym('y'); theta = SX.sym('theta');\nstates = [x;y;theta]; n_states = length(states);\n\nv = SX.sym('v'); omega = SX.sym('omega');\ncontrols = [v;omega]; n_controls = length(controls);\nrhs = [v*cos(theta);v*sin(theta);omega]; % system r.h.s\n\nf = Function('f',{states,controls},{rhs}); % nonlinear mapping function f(x,u)\nU = SX.sym('U',n_controls,N); % Decision variables (controls)\nP = SX.sym('P',n_states + n_states);\n% parameters (which include the initial state and the reference state)\n\nX = SX.sym('X',n_states,(N+1));\n% A vector that represents the states over the optimization problem.\n\nobj = 0; % Objective function\ng = []; % constraints vector\n\nQ = zeros(3,3); Q(1,1) = 1;Q(2,2) = 5;Q(3,3) = 0.1; % weighing matrices (states)\nR = zeros(2,2); R(1,1) = 0.5; R(2,2) = 0.05; % weighing matrices (controls)\n\nst = X(:,1); % initial state\ng = [g;st-P(1:3)]; % initial condition constraints\nfor k = 1:N\n st = X(:,k); con = U(:,k);\n obj = obj+(st-P(4:6))'*Q*(st-P(4:6)) + con'*R*con; % calculate obj\n st_next = X(:,k+1);\n f_value = f(st,con);\n st_next_euler = st+ (T*f_value);\n g = [g;st_next-st_next_euler]; % compute constraints\nend\n% make the decision variable one column vector\nOPT_variables = [reshape(X,3*(N+1),1);reshape(U,2*N,1)];\n\nnlp_prob = struct('f', obj, 'x', OPT_variables, 'g', g, 'p', P);\n\nopts = struct;\nopts.ipopt.max_iter = 2000;\nopts.ipopt.print_level =0;%0,3\nopts.print_time = 0;\nopts.ipopt.acceptable_tol =1e-8;\nopts.ipopt.acceptable_obj_change_tol = 1e-6;\n\nsolver = nlpsol('solver', 'ipopt', nlp_prob,opts);\n\nargs = struct;\n\nargs.lbg(1:3*(N+1)) = 0; % -1e-20 % Equality constraints\nargs.ubg(1:3*(N+1)) = 0; % 1e-20 % Equality constraints\n\nargs.lbx(1:3:3*(N+1),1) = -2; %state x lower bound\nargs.ubx(1:3:3*(N+1),1) = 2; %state x upper bound\nargs.lbx(2:3:3*(N+1),1) = -2; %state y lower bound\nargs.ubx(2:3:3*(N+1),1) = 2; %state y upper bound\nargs.lbx(3:3:3*(N+1),1) = -inf; %state theta lower bound\nargs.ubx(3:3:3*(N+1),1) = inf; %state theta upper bound\n\nargs.lbx(3*(N+1)+1:2:3*(N+1)+2*N,1) = v_min; %v lower bound\nargs.ubx(3*(N+1)+1:2:3*(N+1)+2*N,1) = v_max; %v upper bound\nargs.lbx(3*(N+1)+2:2:3*(N+1)+2*N,1) = omega_min; %omega lower bound\nargs.ubx(3*(N+1)+2:2:3*(N+1)+2*N,1) = omega_max; %omega upper bound\n%----------------------------------------------\n% ALL OF THE ABOVE IS JUST A PROBLEM SET UP\n\n\n% THE SIMULATION LOOP SHOULD START FROM HERE\n%-------------------------------------------\nt0 = 0;\nx0 = [0 ; 0 ; 0.0]; % initial condition.\nxs = [1.5 ; 1.5 ; 0.0]; % Reference posture.\n\nxx(:,1) = x0; % xx contains the history of states\nt(1) = t0;\n\nu0 = zeros(N,2); % two control inputs for each robot\nX0 = repmat(x0,1,N+1)'; % initialization of the states decision variables\n\nsim_tim = 20; % Maximum simulation time\n\n% Start MPC\nmpciter = 0;\nxx1 = [];\nu_cl=[];\n\n% the main simulaton loop... it works as long as the error is greater\n% than 10^-6 and the number of mpc steps is less than its maximum\n% value.\ntic\nwhile(norm((x0-xs),2) > 1e-2 && mpciter < sim_tim / T)\n args.p = [x0;xs]; % set the values of the parameters vector\n % initial value of the optimization variables\n args.x0 = [reshape(X0',3*(N+1),1);reshape(u0',2*N,1)];\n sol = solver('x0', args.x0, 'lbx', args.lbx, 'ubx', args.ubx,...\n 'lbg', args.lbg, 'ubg', args.ubg,'p',args.p);\n u = reshape(full(sol.x(3*(N+1)+1:end))',2,N)'; % get controls only from the solution\n xx1(:,1:3,mpciter+1)= reshape(full(sol.x(1:3*(N+1)))',3,N+1)'; % get solution TRAJECTORY\n u_cl= [u_cl ; u(1,:)];\n t(mpciter+1) = t0;\n % Apply the control and shift the solution\n [t0, x0, u0] = shift(T, t0, x0, u,f);\n xx(:,mpciter+2) = x0;\n X0 = reshape(full(sol.x(1:3*(N+1)))',3,N+1)'; % get solution TRAJECTORY\n % Shift trajectory to initialize the next step\n X0 = [X0(2:end,:);X0(end,:)];\n mpciter\n mpciter = mpciter + 1;\nend;\ntoc\n\nss_error = norm((x0-xs),2)\nDraw_MPC_point_stabilization_v1 (t,xx,xx1,u_cl,xs,N,rob_diam)\n\n\n", "meta": {"author": "MMehrez", "repo": "MPC-and-MHE-implementation-in-MATLAB-using-Casadi", "sha": "8937ba42c932e1935bcf394e0566bcf981bc6d33", "save_path": "github-repos/MATLAB/MMehrez-MPC-and-MHE-implementation-in-MATLAB-using-Casadi", "path": "github-repos/MATLAB/MMehrez-MPC-and-MHE-implementation-in-MATLAB-using-Casadi/MPC-and-MHE-implementation-in-MATLAB-using-Casadi-8937ba42c932e1935bcf394e0566bcf981bc6d33/workshop_github/Codes_casadi_v3_5_5/MPC_code/Sim_2_MPC_Robot_PS_mul_shooting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.6371464570858614}} {"text": "function [x,y]=als_prec(mat,rhs,y,niter)\n%Computes an approximate rank-1 solution to the linear system\n% [Y]=ALS_PREC(MAT,RHS,X) Computes (approximate) rank-1 solution to the\n% problems MAT*P = RHS, where A is a low-Kronecker rank matrix\n% P=X x Y, RHS is a low-Kronecker rank matrix\n% B is given as a two-2d cell array, the same is for X\n%\n%\n% TT-Toolbox 2.2, 2009-2012\n%\n%This is TT Toolbox, written by Ivan Oseledets et al.\n%Institute of Numerical Mathematics, Moscow, Russia\n%webpage: http://spring.inm.ras.ru/osel\n%\n%For all questions, bugs and suggestions please mail\n%ivan.oseledets@gmail.com\n%---------------------------\n\n\na=mat{1}; %The first cell\nb=mat{2}; \nR=size(a,3); %The rank\nn=size(a,1);\nm=size(b,1);\na1=permute(a,[1,3,2]); a1=reshape(a1,[n*R,n]);\nb1=permute(b,[1,3,2]); b1=reshape(b1,[m*R,m]);\nrhs1=rhs;\nif ( nargin < 5 )\n niter=10;\nend\nu=rhs{1}; \nv=rhs{2}; \nrr=size(u,3);\nu1=reshape(u,[n*n,rr]);\nv1=reshape(v,[m*m,rr]);\n\nfor i=1:niter\n %fprintf('i=%d \\n',i);\n %at=a1*x;\n %bt=b1*y; \n %Iterate over x\n bt=b1*y;\n %bt is n*R*n, scalar product of \n bt1=reshape(bt,[m,R,m]); bt1=permute(bt1,[1,3,2]); bt1=reshape(bt1,[m*m,R]);\n p=bt1'*bt1; %p matrix is ready\n %Compute the local matrix sum_{a,b} p_{ab} A^{\\top}_b A_a,\n %it is A(k,i,b)*A(k,j,a)*p(a,b)\n a2=reshape(a,[n*n,R]); a2=a2*p; %a2 is (k,j,b), sum over (k,b) with (k,i,b)\n a3=reshape(a,[n,n,R]); a3=permute(a3,[2,1,3]); a3=reshape(a3,[n,n*R]);\n a2=reshape(a2,[n,n,R]); a2=permute(a2,[2,1,3]); a2=reshape(a2,[n,n*R]);\n loc_mat=a3*a2'; %Should be valid even for complex numbers\n %For the right hand side\n %Compute the q matrix = b is m x m x R, V is m x m x rr\n %the result is R x rr\n q=bt1'*v1; %q is R x rr\n %Now compute right-hand side as\n %q(R,rr)*U(i,k,rr)*A(j,k,R)\n \n u2=u1*q'; % u2 is (i,k,R)\n u2=reshape(u2,[n,n*R]);\n a2=reshape(a,[n,n*R]);\n rhs=u2*a2';\n x= loc_mat \\ rhs;\n %cond(loc_mat)\n %Iterate over y\n at=a1*x;\n %bt is n*R*n, scalar product of \n at1=reshape(at,[n,R,n]); at1=permute(at1,[1,3,2]); at1=reshape(at1,[n*n,R]);\n p=at1'*at1; %p matrix is ready\n %Compute the local matrix sum_{a,b} p_{ab} A^{\\top}_b A_a,\n %or the summation: \\sum_{a,b,k} p(a,b) A(i,k,a)*A(j,k,b)\n b2=reshape(b,[m*m,R]); b2=b2*p; %a2 is (k,j,b), sum over (k,b) with (k,i,b)\n b3=reshape(b,[m,m,R]); b3=permute(b3,[2,1,3]); b3=reshape(b3,[m,m*R]);\n b2=reshape(b2,[m,m,R]); b2=permute(b2,[2,1,3]); b2=reshape(b2,[m,m*R]);\n loc_mat=b3*b2'; %Should be valid even for complex numbers\n %For the right hand side\n %Compute the q matrix = b is m x m x R, V is m x m x rr\n %the result is R x rr\n q=at1'*u1; %q is R x rr\n %Now compute right-hand side as\n %q(R,rr)*U(i,k,rr)*A(j,k,R)\n \n v2=v1*q'; % u2 is (i,k,R)\n v2=reshape(v2,[m,m*R]);\n b2=reshape(b,[m,m*R]);\n rhs=v2*b2';\n y= loc_mat \\ rhs;\n % norm(tt_matrix(mat)*kron(tt_matrix(x,1e-10),tt_matrix(y,1e-10))-tt_matrix(rhs1))\n %keyboard;\n %norm(tt_matrix(mat)*kron(tt_matrix(x,1e-10),tt_matrix(y,1e-10))-tt_mat\n %rix(rhs1))\nend\nreturn\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/solve/als_prec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6371464446289349}} {"text": "%WAVELET 1D Wavelet transform with optional singificance testing\n%\n% [WAVE,PERIOD,SCALE,COI] = wavelet(Y,DT,PAD,DJ,S0,J1,MOTHER,PARAM)\n%\n% Computes the wavelet transform of the vector Y (length N),\n% with sampling rate DT.\n%\n% By default, the Morlet wavelet (k0=6) is used.\n% The wavelet basis is normalized to have total energy=1 at all scales.\n%\n%\n% INPUTS:\n%\n% Y = the time series of length N.\n% DT = amount of time between each Y value, i.e. the sampling time.\n%\n% OUTPUTS:\n%\n% WAVE is the WAVELET transform of Y. This is a complex array\n% of dimensions (N,J1+1). FLOAT(WAVE) gives the WAVELET amplitude,\n% ATAN(IMAGINARY(WAVE),FLOAT(WAVE) gives the WAVELET phase.\n% The WAVELET power spectrum is ABS(WAVE)^2.\n% Its units are sigma^2 (the time series variance).\n%\n%\n% OPTIONAL INPUTS:\n% \n% *** Note *** setting any of the following to -1 will cause the default\n% value to be used.\n%\n% PAD = if set to 1 (default is 0), pad time series with enough zeroes to get\n% N up to the next higher power of 2. This prevents wraparound\n% from the end of the time series to the beginning, and also\n% speeds up the FFT's used to do the wavelet transform.\n% This will not eliminate all edge effects (see COI below).\n%\n% DJ = the spacing between discrete scales. Default is 0.25.\n% A smaller # will give better scale resolution, but be slower to plot.\n%\n% S0 = the smallest scale of the wavelet. Default is 2*DT.\n%\n% J1 = the # of scales minus one. Scales range from S0 up to S0*2^(J1*DJ),\n% to give a total of (J1+1) scales. Default is J1 = (LOG2(N DT/S0))/DJ.\n%\n% MOTHER = the mother wavelet function.\n% The choices are 'MORLET', 'PAUL', or 'DOG'\n%\n% PARAM = the mother wavelet parameter.\n% For 'MORLET' this is k0 (wavenumber), default is 6.\n% For 'PAUL' this is m (order), default is 4.\n% For 'DOG' this is m (m-th derivative), default is 2.\n%\n%\n% OPTIONAL OUTPUTS:\n%\n% PERIOD = the vector of \"Fourier\" periods (in time units) that corresponds\n% to the SCALEs.\n%\n% SCALE = the vector of scale indices, given by S0*2^(j*DJ), j=0...J1\n% where J1+1 is the total # of scales.\n%\n% COI = if specified, then return the Cone-of-Influence, which is a vector\n% of N points that contains the maximum period of useful information\n% at that particular time.\n% Periods greater than this are subject to edge effects.\n% This can be used to plot COI lines on a contour plot by doing:\n%\n% contour(time,log(period),log(power))\n% plot(time,log(coi),'k')\n%\n%----------------------------------------------------------------------------\n% Copyright (C) 1995-2004, Christopher Torrence and Gilbert P. Compo\n%\n% This software may be used, copied, or redistributed as long as it is not\n% sold and this copyright notice is reproduced on each copy made. This\n% routine is provided as is without any express or implied warranties\n% whatsoever.\n%\n% Notice: Please acknowledge the use of the above software in any publications:\n% ``Wavelet software was provided by C. Torrence and G. Compo,\n% and is available at URL: http://paos.colorado.edu/research/wavelets/''.\n%\n% Reference: Torrence, C. and G. P. Compo, 1998: A Practical Guide to\n% Wavelet Analysis. Bull. Amer. Meteor. Soc., 79, 61-78.\n%\n% Please send a copy of such publications to either C. Torrence or G. Compo:\n% Dr. Christopher Torrence Dr. Gilbert P. Compo\n% Research Systems, Inc. Climate Diagnostics Center\n% 4990 Pearl East Circle 325 Broadway R/CDC1\n% Boulder, CO 80301, USA Boulder, CO 80305-3328, USA\n% E-mail: chris[AT]rsinc[DOT]com E-mail: compo[AT]colorado[DOT]edu\n%----------------------------------------------------------------------------\nfunction [wave,period,scale,coi] = ...\n\twavelet(Y,dt,pad,dj,s0,J1,mother,param);\n\nif (nargin < 8), param = -1;, end\nif (nargin < 7), mother = -1;, end\nif (nargin < 6), J1 = -1;, end\nif (nargin < 5), s0 = -1;, end\nif (nargin < 4), dj = -1;, end\nif (nargin < 3), pad = 0;, end\nif (nargin < 2)\n\terror('Must input a vector Y and sampling time DT')\nend\n\nn1 = length(Y);\n\nif (s0 == -1), s0=2*dt;, end\nif (dj == -1), dj = 1./4.;, end\nif (J1 == -1), J1=fix((log(n1*dt/s0)/log(2))/dj);, end\nif (mother == -1), mother = 'MORLET';, end\n\n%....construct time series to analyze, pad if necessary\nx(1:n1) = Y - mean(Y);\nif (pad == 1)\n\tbase2 = fix(log(n1)/log(2) + 0.4999); % power of 2 nearest to N\n\tx = [x,zeros(1,2^(base2+1)-n1)];\nend\nn = length(x);\n\n%....construct wavenumber array used in transform [Eqn(5)]\nk = [1:fix(n/2)];\nk = k.*((2.*pi)/(n*dt));\nk = [0., k, -k(fix((n-1)/2):-1:1)];\n\n%....compute FFT of the (padded) time series\nf = fft(x); % [Eqn(3)]\n\n%....construct SCALE array & empty PERIOD & WAVE arrays\nscale = s0*2.^((0:J1)*dj);\nperiod = scale;\nwave = zeros(J1+1,n); % define the wavelet array\nwave = wave + i*wave; % make it complex\n\n% loop through all scales and compute transform\nfor a1 = 1:J1+1\n\t[daughter,fourier_factor,coi,dofmin]=wave_bases(mother,k,scale(a1),param);\t\n\twave(a1,:) = ifft(f.*daughter); % wavelet transform[Eqn(4)]\nend\n\nperiod = fourier_factor*scale;\ncoi = coi*dt*[1E-5,1:((n1+1)/2-1),fliplr((1:(n1/2-1))),1E-5]; % COI [Sec.3g]\nwave = wave(:,1:n1); % get rid of padding before returning\n\nreturn\n\n%WAVE_BASES 1D Wavelet functions Morlet, Paul, or DOG\n%\n% [DAUGHTER,FOURIER_FACTOR,COI,DOFMIN] = ...\n% wave_bases(MOTHER,K,SCALE,PARAM);\n%\n% Computes the wavelet function as a function of Fourier frequency,\n% used for the wavelet transform in Fourier space.\n% (This program is called automatically by WAVELET)\n%\n% INPUTS:\n%\n% MOTHER = a string, equal to 'MORLET' or 'PAUL' or 'DOG'\n% K = a vector, the Fourier frequencies at which to calculate the wavelet\n% SCALE = a number, the wavelet scale\n% PARAM = the nondimensional parameter for the wavelet function\n%\n% OUTPUTS:\n%\n% DAUGHTER = a vector, the wavelet function\n% FOURIER_FACTOR = the ratio of Fourier period to scale\n% COI = a number, the cone-of-influence size at the scale\n% DOFMIN = a number, degrees of freedom for each point in the wavelet power\n% (either 2 for Morlet and Paul, or 1 for the DOG)\n%\n%----------------------------------------------------------------------------\n% Copyright (C) 1995-1998, Christopher Torrence and Gilbert P. Compo\n% University of Colorado, Program in Atmospheric and Oceanic Sciences.\n% This software may be used, copied, or redistributed as long as it is not\n% sold and this copyright notice is reproduced on each copy made. This\n% routine is provided as is without any express or implied warranties\n% whatsoever.\n%----------------------------------------------------------------------------\nfunction [daughter,fourier_factor,coi,dofmin] = ...\n\twave_bases(mother,k,scale,param);\n\nmother = upper(mother);\nn = length(k);\n\nif (strcmp(mother,'MORLET')) %----------------------------------- Morlet\n\tif (param == -1), param = 6.; end\n\tk0 = param;\n\texpnt = -(scale.*k - k0).^2/2.*(k > 0.);\n\tnorm = sqrt(scale*k(2))*(pi^(-0.25))*sqrt(n); % total energy=N [Eqn(7)]\n\tdaughter = norm*exp(expnt);\n\tdaughter = daughter.*(k > 0.); % Heaviside step function\n\tfourier_factor = (4*pi)/(k0 + sqrt(2 + k0^2)); % Scale-->Fourier [Sec.3h]\n\tcoi = fourier_factor/sqrt(2); % Cone-of-influence [Sec.3g]\n\tdofmin = 2; % Degrees of freedom\nelseif (strcmp(mother,'PAUL')) %-------------------------------- Paul\n\tif (param == -1), param = 4.; end\n\tm = param;\n\texpnt = -(scale.*k).*(k > 0.);\n\tnorm = sqrt(scale*k(2))*(2^m/sqrt(m*prod(2:(2*m-1))))*sqrt(n);\n\tdaughter = norm*((scale.*k).^m).*exp(expnt);\n\tdaughter = daughter.*(k > 0.); % Heaviside step function\n\tfourier_factor = 4*pi/(2*m+1);\n\tcoi = fourier_factor*sqrt(2);\n\tdofmin = 2;\nelseif (strcmp(mother,'DOG')) %-------------------------------- DOG\n\tif (param == -1), param = 2.;, end\n\tm = param;\n\texpnt = -(scale.*k).^2 ./ 2.0;\n\tnorm = sqrt(scale*k(2)/gamma(m+0.5))*sqrt(n);\n\tdaughter = -norm*(i^m)*((scale.*k).^m).*exp(expnt);\n\tfourier_factor = 2*pi*sqrt(2./(2*m+1));\n\tcoi = fourier_factor/sqrt(2);\n\tdofmin = 1;\nelse\n\terror('Mother must be one of MORLET,PAUL,DOG')\nend\n\nreturn\n\n% end of code\n\n", "meta": {"author": "jramshur", "repo": "HRVAS", "sha": "ffe2465a0b8f8bf21bc78db474e5da4890761a44", "save_path": "github-repos/MATLAB/jramshur-HRVAS", "path": "github-repos/MATLAB/jramshur-HRVAS/HRVAS-ffe2465a0b8f8bf21bc78db474e5da4890761a44/wavelet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937771, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6371361719652788}} {"text": "function plotbernstein(B,a,b)\n%PLOTBERNSTEIN Plots Berstein points with connecting lines\n%\n%For univariate Bernstein points, \n%\n% plotbernstein(B)\n%\n%plots Bernstein points in default interval [0,1]. Correspondingly, \n%\n% plotbernstein(B,a,b)\n%\n%plots Bernstein points in the interval [a,b]. \n%\n%For given polynomial P and an interval [a,b], a typical call for plotting P together with \n%its Bernstein points is\n%\n% B = bernsteincoeff(ptrans(P,a,b,0,1)); \n% plotpoly(P,a,b), hold on, plotbernstein(B,a,b), hold off\n%\n\n% written 12/25/02 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 11/20/05 S.M. Rump fast check for rounding to nearest\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 if ~isreal(B.c)\n error('polynomial must be real (point or interval)')\n end\n \n if size(B.e,2)==1 % univariate polynomial\n \n if nargin==1\n a = 0;\n b = 1;\n end\n n = length(B.c);\n X = linspace(a,b,n);\n \n if isa(B.c,'intval')\n \n Bc = fliplr([B.c.inf B.c.sup]);\n XX = [X X];\n if n>1\n index = convhull(XX,Bc);\n else\n index = 1:2;\n end\n plot(XX,Bc,'o',XX(index),Bc(index),'-o')\n \n else\n \n Bc = fliplr(B.c);\n if n>2\n index = convhull(X,Bc);\n else\n index = 1:length(Bc);\n end\n plot(X,Bc,'o',X(index),Bc(index),'-o')\n \n end\n \n elseif size(B.e,2)==2 % multivariate polynomial in two unknowns\n error('not yet implemented')\n else\n error('Bernstein plot only for polynomials in one or two unknowns')\n end\n \n setround(rndold)\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/polynom/@polynom/plotbernstein.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.637102137906138}} {"text": "function [ x, seed ] = r8vec_uniform_ab ( n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% R8VEC_UNIFORM_AB returns a scaled pseudorandom R8VEC.\n%\n% Discussion:\n%\n% Each dimension ranges from A to B.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Springer Verlag, pages 201-202, 1983.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, pages 362-376, 1986.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, pages 136-143, 1969.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A, B, the range of the pseudorandom values.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N,1), the vector of pseudorandom values.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_UNIFORM_AB - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8VEC_UNIFORM_AB - Fatal error!' );\n end\n\n x = zeros ( n, 1 );\n\n for i = 1 : n\n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + 2147483647;\n end\n\n x(i) = a + ( b - a ) * seed * 4.656612875E-10;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_least_squares/r8vec_uniform_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919830720203, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.6370770600470267}} {"text": "function [rhsu] = AdvecRHS3D(u,time)\n\n% function [rhsu] = AdvecRHS3D(u,time)\n% Purpose : Evaluate RHS flux in 3D advection\n\nGlobals3D;\n\n% form field differences at faces\nalpha=1; du = zeros(Nfp*Nfaces,K); \ndu(:) = 0.5*(u(vmapM)-u(vmapP)).*(nx(:) - alpha*abs(nx(:)));\n\n% impose boundary condition at x=0\nubc = exp(-1*( (Fx(mapB)-time).^2 + Fy(mapB).^2 + Fz(mapB).^2));\ndu(mapB) = 0.5*(u(vmapB)-ubc).*(nx(mapB)-alpha*abs(nx(mapB)));\n\n% compute right hand sides of the semi-discrete PDE\nrhsu = -(rx.*(Dr*u)+sx.*(Ds*u)+tx.*(Dt*u)) + LIFT*(Fscale.*(du));\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/AdvecRHS3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6369830324047884}} {"text": "function y = atan_pos(x,rnd)\n% Rigorous atan(x) for nonnegative double vector x, rounding corresponding\n% to rnd\n% For internal use in atan, asin, acos, asec, acsc\n\n% written 12/30/98 S.M. Rump\n% modified 08/31/99 S.M. Rump extreme input, improved speed and accuracy\n% modified 08/26/12 S.M. Rump global variables removed\n% modified 10/13/12 S.M. Rump INTLAB_INTVAL_STDFCTS\n%\n\n INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');\n\n y = x;\n\n % transformation of large arguments\n index = ( x>=4 );\n if any(index(:))\n setround(-rnd)\n xx = x(index);\n xx = (-2) ./ ( 1./xx - xx ); % with correct rounding -rnd\n yy = atan_pos_small(xx,-rnd);\n setround(rnd)\n if rnd==-1\n y(index) = INTLAB_STDFCTS_PI.PI2INF - yy/2;\n else\n y(index) = INTLAB_STDFCTS_PI.PI2SUP - yy/2;\n end\n end\n\n index = ~index;\n if any(index(:))\n y(index) = atan_pos_small(x(index),rnd);\n end\n\n\n\n\nfunction y = atan_pos_small(x,rnd)\n% Rigorous atan(x) for nonnegative double vector x with 0 <= x < 4\n% rounding corresponding to rnd\n\n INTLAB_STDFCTS_ATAN = getappdata(0,'INTLAB_STDFCTS_ATAN');\n\n setround(0) % maximum first 15 bits, no bit\n xs = pow2( floor(pow2(x,13)) , -13 ); % below 2^-13\n d = x - xs; % 0 <= d < 2^-15*x\n atanxs = atan(xs);\n\n % atan(xs+d) = atan(xs) + atan(d/(1+x*xs))\n setround(-rnd)\n E = 1 + x.*xs;\n setround(rnd)\n E = d./E; % 0 <= E < d/(1+x*xs) < 2^-13\n\n if rnd==-1 % 0 <= err <= E^5/5 <= d^4/5*d < 5e-17*d\n % atanE <= atan(E)\n atanE = E + (((-E).*E).*E)/3;\n y = atanxs + ( atanE + (-INTLAB_STDFCTS_ATAN.EPS)*atanxs );\n else\n % atanE >= atan(E)\n atanE = ((( E.*E/5 + (-1)/3 ).*E).*E).*E + E;\n y = atanxs + ( atanE + INTLAB_STDFCTS_ATAN.EPS*atanxs );\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/intval/@intval/private/atan_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6369378643244432}} {"text": "classdef Gumbel2C\n%%GUMBEL2C A collection of functions for the bivariate Gumbel copulae.\n% Implemented functions include: PDF, CDF, tau.\n%\n%REFERENCES:\n%[1] H. Joe and D. Kurowicka, Dependence Modeling: Vine Copula Handbook.\n% World Scientific, 2011.\n%[2] C. Brechmann and U. Schepsmeier, \"Dependence modeling with c- and\n% d-vine copulas: The r-package cdvine,\" Jan. 2011.\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n methods(Static)\n function jprob = PDF(u,theta,rot)\n %PDF Generates a joint probability for column vector u or\n % a row vector of joint probabilities for matrix u\n % with each column as the input vector.\n %\n %INPUTS: \n % u: A 2-by-n matrix where each column represents a\n % 2-dimensional random vector and n is the number of\n % random vectors. Entries must be in [0,1].\n % theta: A scalar coupling parameter in the interval\n % [1,inf).\n % rot: A scalar specifying one of four rotations of the\n % standard bivariate Gumbel copula. Allowed values are 0,\n % 90, 180, and 270. Default is 0.\n %\n %OUTPUTS: jprob: A 1-by-n vector of joint probabilities.\n %\n %EXAMPLE 1: Make a contour plot of the density.\n %x = linspace(0,1,1e2);\n %[X,Y] = meshgrid(x);\n %Z = zeros(length(X),length(Y));\n %for idx = 1:length(X)\n % for iidx = 1:length(Y)\n % Z(idx,iidx) = Gumbel2C.PDF([X(idx,iidx);Y(idx,iidx)],3);\n % end\n %end\n %contourf(X,Y,Z)\n %\n %EXAMPLE 2: Generate an exact joint density plot.\n % x = linspace(0,1,1e2);\n % [X,Y] = meshgrid(x);\n % Z = zeros(length(X),length(Y));\n % for idx = 1:length(X)\n % for iidx = 1:length(Y)\n % Z(idx,iidx) = Gumbel2C.PDF([X(idx,iidx);Y(idx,iidx)],3);\n % X(idx,iidx) = GumbelD.invCDF(X(idx,iidx),1,2);\n % Y(idx,iidx) = GaussianD.invCDF(Y(idx,iidx));\n % Z(idx,iidx) = Z(idx,iidx).*GumbelD.PDF(X(idx,iidx),1,2).*GaussianD.PDF(Y(idx,iidx));\n % end\n % end\n % surf(X,Y,Z)\n %\n %October 2020 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n %\n if ~exist('u','var') || isempty(u)\n jprob = [];\n return\n end\n if ~exist('theta','var') || isempty(theta)\n theta = 1;\n elseif theta < 1\n error('Theta parameter cannot be less than 1.')\n end\n if ~exist('rot','var') || isempty(rot)\n rot = 0;\n end\n \n if rot==0\n %No modifications necessary.\n elseif rot==90\n u(1,:) = 1-u(1,:);\n elseif rot==180\n u(1,:) = 1-u(1,:);\n u(2,:) = 1-u(2,:);\n elseif rot==270\n u(2,:) = 1-u(2,:);\n else\n error('Invalid rotation. Allowed values are 0, 90, 180, and 270.')\n end\n \n a = -log(u(1,:));\n b = -log(u(2,:));\n \n jprob = Gumbel2C.CDF(u,theta).*(a.*b).^(theta-1)...\n .*((a.^theta+b.^theta).^(1/theta)+theta-1)...\n ./(u(1,:).*u(2,:).*(a.^theta+b.^theta).^(2-(1/theta)));\n \n %NaN results from 0*inf in the calculation.\n %These should be 0s.\n nanIdxs = isnan(jprob);\n jprob(nanIdxs) = 0;\n \n end\n \n function jdist = CDF(u,theta,rot)\n %CDF Generates a joint distribution for column vector u or\n % a row vector of joint probabilities for matrix u\n % with each column as the input vector.\n %\n %INPUTS: \n % u: A 2-by-n matrix where each column represents a\n % 2-dimensional random vector and n is the number of\n % random vectors. Entries must be in [0,1].\n % theta: A scalar coupling parameter in the interval\n % [1,inf).\n % rot: A scalar specifying one of four rotations of the\n % standard bivariate Gumbel copula. Allowed values are 0,\n % 90, 180, and 270. Default is 0.\n %\n %OUTPUTS: jprob: A 1-by-n vector of joint distribution values.\n %\n %EXAMPLE 1: Make a contour plot of the distribution.\n %x = linspace(0,1,1e2);\n %[X,Y] = meshgrid(x);\n %Z = zeros(length(X),length(Y));\n %for idx = 1:length(X)\n % for iidx = 1:length(Y)\n % Z(idx,iidx) = Gumbel2C.CDF([X(idx,iidx);Y(idx,iidx)],3);\n % end\n %end\n %contourf(X,Y,Z)\n %\n %EXAMPLE 2: Generate an exact joint distribution plot.\n % x = linspace(0,1,1e2);\n % [X,Y] = meshgrid(x);\n % Z = zeros(length(X),length(Y));\n % for idx = 1:length(X)\n % for iidx = 1:length(Y)\n % Z(idx,iidx) = Gumbel2C.CDF([X(idx,iidx);Y(idx,iidx)],3);\n % X(idx,iidx) = GumbelD.invCDF(X(idx,iidx),1,2);\n % Y(idx,iidx) = GaussianD.invCDF(Y(idx,iidx));\n % Z(idx,iidx) = Z(idx,iidx);\n % end\n % end\n % surf(X,Y,Z)\n %\n %October 2020 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n %\n if ~exist('u','var') || isempty(u)\n jdist = [];\n return\n end\n if ~exist('theta','var') || isempty(theta)\n theta = 1;\n elseif theta < 1\n error('Theta parameter cannot be less than 1.')\n end\n if ~exist('rot','var') || isempty(rot)\n rot = 0;\n end\n \n if rot==0\n %No modifications necessary.\n a = -log(u(1,:));\n b = -log(u(2,:));\n \n jdist = exp(-(a.^theta+b.^theta).^(1/theta));\n elseif rot==90\n a = -log(1-u(1,:));\n b = -log(u(2,:));\n \n jdist = u(2,:)-exp(-(a.^theta+b.^theta).^(1/theta));\n elseif rot==180\n a = -log(1-u(1,:));\n b = -log(1-u(2,:));\n \n jdist = u(1,:)+u(2,:)-1+exp(-(a.^theta+b.^theta).^(1/theta));\n elseif rot==270\n a = -log(u(1,:));\n b = -log(1-u(2,:));\n \n jdist = u(1,:)-exp(-(a.^theta+b.^theta).^(1/theta));\n else\n error('Invalid rotation. Allowed values are 0, 90, 180, and 270.')\n end\n \n end\n \n function t = tau(theta)\n %%TAU Compute Kendall's tau for the copula.\n %\n %INPUTS:\n % theta: A scalar coupling parameter in the interval\n % [1,inf).\n %\n %OUTPUTS:\n % t: The scalar value of Kendall's tau.\n %\n %October 2020 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n %\n if ~exist('theta','var') || isempty(theta)\n theta = 1;\n elseif theta < 1\n error('Theta parameter cannot be less than 1.')\n end\n \n t = 1-1/theta;\n end\n end\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Bivariate_Copulae/Gumbel2C.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6369378518296835}} {"text": "function stress=outputResult(displacements,numberElements,...\n elementNodes,nodeCoordinates,D)\nstress=zeros(3,1); \nfor e=1:numberElements \n numNodePerElement = length(elementNodes(e,:));\n numEDOF = 2*numNodePerElement;\n elementDof=zeros(1,numEDOF);\n for i = 1:numNodePerElement\n elementDof(2*i-1)=2*elementNodes(e,i)-1;\n elementDof(2*i)=2*elementNodes(e,i); \n end\n \n % B matrix\n x1 = nodeCoordinates(elementNodes(e,1),1);\n y1 = nodeCoordinates(elementNodes(e,1),2);\n x2 = nodeCoordinates(elementNodes(e,2),1);\n y2 = nodeCoordinates(elementNodes(e,2),2);\n x3 = nodeCoordinates(elementNodes(e,3),1);\n y3 = nodeCoordinates(elementNodes(e,3),2);\n A = 1/2*det([1 x1 y1; 1 x2 y2; 1 x3 y3]);\n B = 1/(2*A).*[y2-y3 0 y3-y1 0 y1-y2 0;\n 0 x3-x2 0 x1-x3 0 x2-x1;\n x3-x2 y2-y3 x1-x3 y3-y1 x2-x1 y1-y2];\n \n stress(e,:)=stress+D*B*displacements(elementDof)/2;\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/FEM/Abaqus2Matlab/MATLAB ABAQUS Parser T3/outputResult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145364, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6369126795005352}} {"text": "function [coeffs, poles, k] = residue(u, v, k)\n%RESIDUE Partial-fraction expansion (residues).\n% [R, P, K] = RESIDUE(B, A) finds the residues, poles and direct term of a\n% partial fraction expansion of the ratio of two CHEBFUN objects B(s)/A(s).\n% If there are no multiple roots,\n% B(s) R(1) R(2) R(n)\n% ---- = -------- + -------- + ... + -------- + K(s)\n% A(s) s - P(1) s - P(2) s - P(n)\n% B and A are CHEBFUN objects consisting of a single fun. The residues are\n% returned in the column vector R, the pole locations in column vector P, and\n% the direct terms in the CHEBFUN K. The number of poles is n = length(A) - 1\n% = length(R) = length(P). The direct term CHEBFUN is zero if length(B) <\n% length(A), otherwise length(K) = length(B) - length(A) + 1.\n%\n% If P(j) = ... = P(j+m-1) is a pole of multiplicity m, then the expansion\n% includes terms of the form\n% R(j) R(j+1) R(j+m-1)\n% -------- + ------------ + ... + ------------\n% s - P(j) (s - P(j))^2 (s - P(j))^m\n%\n% [B, A] = RESIDUE(R, P, K), with 3 input arguments and 2 output arguments,\n% converts the partial fraction expansion back to the polynomials with CHEBFUN\n% representation in B and A.\n%\n% Warning: Numerically, the partial fraction expansion of a ratio of\n% polynomials represents an ill-posed problem. If the denominator polynomial,\n% A(s), is near a polynomial with multiple roots, then small changes in the\n% data, including roundoff errors, can make arbitrarily large changes in the\n% resulting poles and residues. Problem formulations making use of state-space\n% or zero-pole representations are preferable.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( min(size(u)) > 1 || min(size(v)) > 1 )\n error('CHEBFUN:CHEBFUN:residue:quasi', ...\n 'Residue does not support CHEBFUN objects with multiple columns.');\nend\n\nif ( nargin == 2 )\n \n if ( (numel(u.funs) > 1) || (numel(v.funs) > 1) )\n error('CHEBFUN:CHEBFUN:residue:multipleFuns', ...\n 'Residue does not support CHEBFUNs consisting of multiple FUNs.');\n end\n if ( ~isfinite(u) || ~isfinite(v) )\n error('CHEBFUN:CHEBFUN:residue:inf', ...\n 'Residue does not support functions with nonzero exponents.');\n end\n \n b = poly(u);\n a = poly(v);\n [coeffs, poles, k] = residue(b, a);\n k = chebfun(@(x) polyval(k, x), max(length(k), 1), 'vectorize');\n \nelseif ( nargin == 3 )\n \n % Interpret an empty CHEBFUN as a zero CHEBFUN for the user's convenience.\n if ( isempty(k) )\n k = 0;\n else\n if ( numel(k.funs) > 1 )\n error('CHEBFUN:CHEBFUN:residue:multipleFuns', ...\n 'RESIDUE does not support CHEBFUNs with multiple FUNS.');\n end\n\n if ( ~isfinite(k) )\n error('CHEBFUN:CHEBFUN:residue:inf', ...\n 'RESIDUE does not support functions which are unbounded.');\n end\n\n k = poly(k);\n end\n\n [b, a] = residue(u, v, k);\n coeffs = chebfun(@(x) polyval(b, x), max(length(b), 1), 'vectorize');\n poles = chebfun(@(x) polyval(a, x), max(length(a), 1), 'vectorize');\n \nelse\n \n error('CHEBFUN:CHEBFUN:residue:args', ...\n 'Residue requires either 2 or 3 arguments.');\n \nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/residue.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6368996187867382}} {"text": "function [V,D,Ann] = eign(A1, A2,A3, args)\n% Find the principal eigenvalues and eigenvectors of a matrix with Nystr�m's low rank approximation method\n% \n% >> D = eign(A, nb)\n% >> [V, D] = eign(A, nb)\n% \n% In the case of using this method for low rank approximation and\n% decomposing the kernel matrix, one can call the function without\n% explicit construction of the matrix A.\n% \n% >> D = eign(X, kernel, kernel_par, nb)\n% >> [V, D] = eign(X, kernel, kernel_par, nb)\n% \n%\n% Full syntax\n% (We denote the size of positive definite matrix A with a*a.)\n%\n% 1. Given the full matrix:\n% \n% >> D = eign(A,nb)\n% >> [V,D] = eign(A,nb)\n% \n% \n% Outputs \n% V(*) : a x nb matrix with estimated principal eigenvectors of A\n% D : nb x 1 vector with principal estimated eigenvalues of A\n% Inputs \n% A : a*a positive definite symmetric matrix\n% nb(*) : Number of approximated principal eigenvalues/eigenvectors\n% \n%\n% 2. Given the function to calculate the matrix elements:\n% \n% >> D = eign(X, kernel, kernel_par, nb)\n% >> [V,D] = eign(X, kernel, kernel_par, nb)\n% \n% Outputs \n% V(*) : a x nb matrix with estimated principal eigenvectors of A\n% D : nb x 1 vector with estimated principal eigenvalues of A\n% Inputs \n% X : N x d matrix with the training data\n% kernel : Kernel type (e.g. 'RBF_kernel')\n% kernel_par : Kernel parameter (bandwidth in the case of the 'RBF_kernel')\n% nb(*) : Number of eigenvalues/eigenvectors used in the eigenvalue decomposition approximation\n% \n% See also:\n% eig, eigs, kpca, bay_lssvm\n\n% Copyright (c) 2011, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\n% AFUN?\n if nargin~=2\n X = A1;\n kernel = A2;\n kernel_par = A3;\n N = size(X,1);\n \n %eval(['if args<1, error(''strict positive number of eigenvalues required;'');else n = args; end;'],...\n %'n=min(6,ceil(N*.75));');\n if args<1\n error('Strict positive number of eigenvalues required');\n else\n n = args;\n end;\n \n % random sampling\n s = randperm(N); sr=s(n+1:end); s=s(1:n); \n %s = ceil(1:(N-1)/(n-1):N); s = s(1:n);\n \n ANn = zeros(n,N);\n ANn = kernel_matrix(X,kernel,kernel_par,X(s,:));\n Ann = ANn(s,:);\n\n % centering of matrix\n Zc = eye(n) - 1/n;\n %ZC = eye(N) - 1/N;\n Ann = Zc*Ann*Zc;\n %ANn = ZC*ANn*Zc;\n ANn = (Zc*(ANn*Zc)')';\nelse\n A = A1;\n N = size(A,1);\n \n %eval(['if args<1, error(''strict positive number of eigenvalues required;'');else n = args; end;'],...\n %'n=min(6,ceil(N*.75));');\n \n if A2<1\n error('Strict positive number of eigenvalues required');\n else\n n = A2;\n end;\n \n % random sampling\n s = randperm(N); sr=s(n+1:end); s=s(1:n); \n %s = ceil(1:(N-1)/(n-1):N); s = s(1:n);\n\n \n ANn = A(:,s);\n Ann = A(s,s);\nend\n\n\n\n\n%\n% compute eigenvalues en vectors of low rank approximation\n%\n[Vn,Dn] = eig(Ann);Dn = diag(Dn);\n\n\n%\n% select only relevant eigenvalues and sort\n% (only largest eigenvectors are orthogonal)\n%\n[Dn,peff] = sort(Dn(find(Dn>1000*eps)));\nDn = Dn(end:-1:1); peff = peff(end:-1:1);\nVn = Vn(:,peff);\n\n%\n% Nystrom correction\n%\nD = (N/n).*Dn;\n\n\n%\n% eigenvectoren correctie\n%\nif nargout>1,\n %V = zeros(n,length(peff));\n for i=1:length(peff),\n V(:,i) = (sqrt(n/N)/Dn(peff(i)))*ANn*Vn(:,peff(i)); \n end\n \n %\n % correction of found eigenvectors:\n % orthogonal and unit length\n %\n\n % svd\n %[V,D2,ff] = svd(V*diag(D.^.5)); V = V(:,1:length(peff));\n \n % gram schmidt\n %[V,r] = gramschmidt2(V);\n %D = D.*r;\n\n %D = diag(D.^2);\nelse\n V=D;\nend\n\n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/eign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6368863371506268}} {"text": "function [u,eqn,info,node,elem,Neumann] = fracLap1d(square,h,pde,option)\n\nglobal s\nalpha = 1-2*s;\nif s == 0.5\n gamma = 1;\nelse\n gamma = 3/(2*s)+0.1;\nend\n\ntic;\n%% Mesh\nif option.gradmesh\n [node,elem,y] = squaregradmeshquad(square,h,gamma); \nelse\n [node,elem] = squarequadmesh(square,h);\n y0 = square(3); y1 = square(4);\n y = (y0:h:y1)';\nend\nN = size(node,1); NT = size(elem,1); Ndof = N;\n% x0 = square(1); x1 = square(2); \n\n%% Compute Local matrix\nhy = diff(y);\nNTy = length(hy);\nNTx = NT/NTy;\n% stiffness matrix in y direction\nAy = zeros(NTy,3);\nintyalpha = diff(y.^(alpha+1)/(alpha+1));\nAy(:,1) = intyalpha./hy.^2; % Ay(1,1)\nAy(:,2) = -Ay(:,1); % Ay(1,2) and Ay(2,1)\nAy(:,3) = Ay(:,1); % Ay(2,2)\n% mass matrix in y direction\nMy = zeros(NTy,3);\na3 = diff(y.^(alpha+3)/(alpha+3));\na2 = diff(y.^(alpha+2)/(alpha+2));\na1 = diff(y.^(alpha+1)/(alpha+1));\nyleft = y(1:end-1);\nyright = y(2:end);\nMy(:,1) = (a3 - 2*yleft.*a2 + yleft.^2.*a1)./hy.^2; % My(1,1)\nMy(:,2) = (-a3 + (yleft+yright).*a2 - yleft.*yright.*a1)./hy.^2; % My(1,2) and My(2,1)\nMy(:,3) = (a3 - 2*yright.*a2 + yright.^2.*a1)./hy.^2; % My(2,2)\n% stiffness matrix in x direction\nhx = h;\nAx = 1/hx*[1 -1; -1 1];\nMx = hx/6*[2 1; 1 2];\n\n%% Assemble stiffness matrix\n% index map \nixiy = [1 1; 2 1; 2 2; 1 2];\nij2k(1,1) = 1; ij2k(1,2) = 2; ij2k(2,1) = 2; ij2k(2,2) = 3;\n% generate sparse pattern\nii = zeros(10*NT,1); jj = zeros(10*NT,1); \nindex = 0;\nfor i = 1:4\n for j = i:4\n ii(index+1:index+NT) = double(elem(:,i)); \n jj(index+1:index+NT) = double(elem(:,j)); \n index = index + NT;\n end\nend\n% compute non-zeros\nsA = zeros(10*NT,1);\nindex = 0;\nfor i = 1:4\n for j = i:4\n ix = ixiy(i,1); iy = ixiy(i,2);\n jx = ixiy(j,1); jy = ixiy(j,2); \n Aij = Ax(ix,jx)*My(:,ij2k(iy,jy)) + Mx(ix,jx)*Ay(:,ij2k(iy,jy));\n sA(index+1:index+NT,1) = repmat(Aij,NTx,1);\n index = index + NT;\n end\nend \n\n% assemble the matrix\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nA = A + AU + AU';\nclear Aij ii jj AU\n\n%% Right hand side \n% f = 0\nb = zeros(Ndof,1);\n\n%% Set up boundary conditions\n% find boundary nodes and Neumann edges\nnx = NTx + 1;\nny = NTy + 1;\nfixedNode = [1:ny (2:nx-1)*ny (nx-1)*ny+(1:ny)];\nbottom = transpose(1:ny:(nx-1)*ny+1);\nNeumann = [bottom(1:end-1) bottom(2:end)];\nisBdNode = false(N,1);\nisBdNode(fixedNode) = true;\nfreeNode = find(~isBdNode);\n\n% \n% bdFlag = setboundary(node,elem,'Dirichlet','abs(y)>eps','Neumann','abs(y)<=eps');\n% [fixedNode,Neumann,isBdNode] = findboundary(elem,bdFlag);\n\n% Modify the matrix to include the Dirichlet boundary condition\nbdidx = zeros(Ndof,1); \nbdidx(fixedNode) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nA = T*A*T + Tbd;\n\n% Neumann boundary condition\nel = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\nif ~isfield(option,'gNquadorder')\n option.gNquadorder = 4; % default order exact for linear gN\nend\n[lambdagN,weightgN] = quadpts1(option.gNquadorder);\nphigN = lambdagN; % linear bases\nnQuadgN = size(lambdagN,1);\nge = zeros(size(Neumann,1),2);\nfor pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNp = pde.g_N(ppxy);\n for igN = 1:2\n ge(:,igN) = ge(:,igN) + weightgN(pp)*phigN(pp,igN)*gNp;\n end\nend\nge = ge.*repmat(el,1,2);\nb = b + accumarray(Neumann(:), ge(:),[Ndof,1]); \n\n% Modify right handside for Dirichlet boundary condition\n% Neumann edges are considered as open set. So the corner points should be\n% set as Dirichlet boundary condition!\nb(fixedNode) = 0;\n\neqn = struct('A',A,'b',b,'freeNode',freeNode);\n\n%% Record assembling time\nassembleTime = toc;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve\nu = zeros(Ndof,1);\nswitch option.solver\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n return\n case 'direct'\n u(freeNode) = A(freeNode,freeNode)\\b(freeNode);\n residual = norm(b - A*u);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual); \n case 'amg'\n option.solver = 'CG';\n [u(freeNode),info] = amg(A(freeNode,freeNode),b(freeNode),option); \nend\ninfo.assembleTime = assembleTime;\n\n%% Compute error using boundary integral\n[lambdagN,weightgN] = quadpts1(option.gNquadorder);\nphigN = lambdagN; % linear bases\nnQuadgN = size(lambdagN,1);\nerr = zeros(size(Neumann,1),1);\nfor pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n uhp = u(Neumann(:,1))*phigN(pp,1) + u(Neumann(:,2))*phigN(pp,2);\n up = pde.exactu(ppxy);\n gNp = pde.g_N(ppxy);\n err = err + weightgN(pp)*gNp.*(up - 2*uhp);\nend\nerr = sum(err.*el) + u'*A*u;\nerrH1 = sqrt(abs(err));\ninfo.errH1 = errH1;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/fracLap1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.636886317661213}} {"text": "function [W,H] = nmfsc( V, rdim, sW, sH, fname, showflag )\n% nmfsc - non-negative matrix factorization with sparseness constraints\n% \n% SYNTAX:\n% [W,H] = nmfsc( V, rdim, sW, sH, fname, showflag );\n%\n% INPUTS:\n% V - data matrix \n% rdim - number of components (inner dimension of factorization)\n% sW - sparseness of W, in [0,1]. (give [] if no constraint)\n% sH - sparseness of H, in [0,1]. (give [] if no constraint)\n% fname - name of file to write results into\n% showflag - binary flag. if set then graphically show progress\n% \n% Note: Sparseness is measured on the scale [0,1] where 0 means\n% completely distributed and 1 means ultimate sparseness.\n% \n% NOTE: There is NO CONVERGENCE CRITERION. The estimation never ends,\n% but rather has to be terminated manually. See README file of code \n% package for details. \n%\n \n% Check that we have non-negative data\nif min(V(:))<0, error('Negative values in data!'); end\n \n% Globally rescale data to avoid potential overflow/underflow\nV = V/max(V(:));\n\n% Data dimensions\nvdim = size(V,1);\nsamples = size(V,2);\n \n% Create initial matrices\nW = abs(randn(vdim,rdim)); \nH = abs(randn(rdim,samples));\nH = H./(sqrt(sum(H.^2,2))*ones(1,samples));\n\n% Make initial matrices have correct sparseness\nif ~isempty(sW), \n L1a = sqrt(vdim)-(sqrt(vdim)-1)*sW; \n for i=1:rdim, W(:,i) = projfunc(W(:,i),L1a,1,1); end\nend\nif ~isempty(sH), \n L1s = sqrt(samples)-(sqrt(samples)-1)*sH; \n for i=1:rdim, H(i,:) = (projfunc(H(i,:)',L1s,1,1))'; end\nend\n\n% Initialize displays\nif showflag,\n figure(1); clf; % this will show the energies and sparsenesses\n figure(2); clf; % this will show the objective function\n drawnow;\nend\n\n% Calculate initial objective\nobjhistory = 0.5*sum(sum((V-W*H).^2));\n\n% Initial stepsizes\nstepsizeW = 1;\nstepsizeH = 1;\n\ntimestarted = clock;\n\n% Start iteration\niter = 0;\nwhile 1,\n\n % Show progress\n fprintf('[%d]: %.5f\\n',iter,objhistory(end)); \n\n % Save every once in a while\n if rem(iter,5)==0,\n\telapsed = etime(clock,timestarted);\n\tfprintf('Saving...');\n\tsave(fname,'W','H','sW','sH','iter','objhistory','elapsed');\n\tfprintf('Done!\\n');\n end\n\t\n % Show stats\n if showflag & (rem(iter,5)==0),\n\tfigure(1);\n\tsubplot(3,1,1); bar(sqrt(sum(W.^2)).*sqrt(sum(H'.^2)));\n\tcursW = (sqrt(vdim)-(sum(abs(W))./sqrt(sum(W.^2))))/(sqrt(vdim)-1);\n\tsubplot(3,1,2); bar(cursW);\n\tcursH = (sqrt(samples)-(sum(abs(H'))./sqrt(sum(H'.^2)))) ...\n\t\t/(sqrt(samples)-1);\n\tsubplot(3,1,3); bar(cursH);\n\tif iter>1,\n\t figure(2);\n\t plot(objhistory(2:end));\n end\n % added for now\n figure(100); imstiled(reshape(W,15,15,43),[],'gray')\n\tdrawnow;\n end\n \n % Update iteration count\n iter = iter+1; \n \n % Save old values\n Wold = W;\n Hold = H;\n \n % ----- Update H ---------------------------------------\n \n if ~isempty(sH),\n \n\t% Gradient for H\n\tdH = W'*(W*H-V);\n\tbegobj = objhistory(end);\n \n\t% Make sure we decrease the objective!\n\twhile 1,\n\t \n\t % Take step in direction of negative gradient, and project\n\t Hnew = H - stepsizeH*dH;\n\t for i=1:rdim, Hnew(i,:) = (projfunc(Hnew(i,:)',L1s,1,1))'; end\n\t \n\t % Calculate new objective\n\t newobj = 0.5*sum(sum((V-W*Hnew).^2));\n\t \n\t % If the objective decreased, we can continue...\n\t if newobj<=begobj,\n\t\tbreak;\n\t end\n\t \n\t % ...else decrease stepsize and try again\n\t stepsizeH = stepsizeH/2;\n\t fprintf('.');\n\t if stepsizeH<1e-200, \n\t\tfprintf('Algorithm converged.\\n');\n\t\treturn; \n\t end\n\t\n\tend\n\t\n\t% Slightly increase the stepsize\n\tstepsizeH = stepsizeH*1.2;\n\tH = Hnew;\n\n else\n\t\n\t% Update using standard NMF multiplicative update rule\n\tH = H.*(W'*V)./(W'*W*H + 1e-9);\n\n\t% Renormalize so rows of H have constant energy\n\tnorms = sqrt(sum(H'.^2));\n\tH = H./(norms'*ones(1,samples));\n\tW = W.*(ones(vdim,1)*norms);\n\t\n end\n \n \n % ----- Update W ---------------------------------------\n\n if ~isempty(sW), \n \n\t% Gradient for W\n\tdW = (W*H-V)*H';\n\tbegobj = 0.5*sum(sum((V-W*H).^2));\n\t\n\t% Make sure we decrease the objective!\n\twhile 1,\n\t \n\t % Take step in direction of negative gradient, and project\n\t Wnew = W - stepsizeW*dW;\n\t norms = sqrt(sum(Wnew.^2));\n\t for i=1:rdim, \n\t\tWnew(:,i) = projfunc(Wnew(:,i),L1a*norms(i),(norms(i)^2),1); \n\t end\n\t\n\t % Calculate new objective\n\t newobj = 0.5*sum(sum((V-Wnew*H).^2));\n\t \n\t % If the objective decreased, we can continue...\n\t if newobj<=begobj,\n\t\tbreak;\n\t end\n\t \n\t % ...else decrease stepsize and try again\n\t stepsizeW = stepsizeW/2;\n\t fprintf(',');\n\t if stepsizeW<1e-200, \n\t\tfprintf('Algorithm converged.\\n');\n\t\treturn; \n\t end\n\t\n\tend\n\t\n\t% Slightly increase the stepsize\n\tstepsizeW = stepsizeW*1.2;\n\tW = Wnew;\n\n else\n\n\t% Update using standard NMF multiplicative update rule\t\n\tW = W.*(V*H')./(W*H*H' + 1e-9);\t\n\t\n end\n \n % Calculate objective\n newobj = 0.5*sum(sum((V-W*H).^2));\n objhistory = [objhistory newobj];\n \n \nend\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/nmfpack/code/nmfsc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6368863137930011}} {"text": "echo on\n\n% Script to demonstrate use of the lp_solve toolkit\n\nclc;\nlp=mxlpsolve('make_lp',0,4);\nmxlpsolve('add_constraint',lp,[3, 2, 2, 1],3,4);\nmxlpsolve('add_constraint',lp,[0, 4, 3, 1],2,3);\nmxlpsolve('set_obj_fn',lp,[2, 3, -2, 3]);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\npause;\n\n% Change a single element, and maximize\n\nclc;\nmxlpsolve('set_mat',lp,2,1,0.5);\nmxlpsolve('set_maxim',lp);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\npause;\n\n% Change RHS\n\nclc;\nmxlpsolve('set_rh',lp,1,7.45);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\npause;\n\n% Set var 4 to an integer\n\nclc;\nmxlpsolve('set_int',lp,4,1)\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\npause;\n\n% Put in lower and upper bounds\n\nclc;\nmxlpsolve('set_lowbo',lp,2,2);\nmxlpsolve('set_upbo',lp,4,5.3);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\npause;\n\n% Delete a constraint\n\nclc;\nmxlpsolve('del_constraint',lp,1);\nmxlpsolve('add_constraint',lp,[1, 2, 1, 4],3,8);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp',lp)\npause;\n\n%%%%%%%%%%%%%\n\n% More examples\n\n% ex1.lp from the lp_solve distribution\n\nclc;\nlp=mxlpsolve('make_lp',2,2);\nmxlpsolve('set_mat',lp,[2, 1;-4, 4]);\nmxlpsolve('set_obj_fn',lp,[-1, 2]);\nmxlpsolve('set_int',lp,[1,1]);\nmxlpsolve('set_rh_vec',lp,[5, 5]);\nmxlpsolve('set_maxim',lp);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp',lp);\npause;\n\n% Example 2\n\nclc;\nf = [50, 100];\nA = sparse([10, 5;4, 10; 1, 1.5]);\nb = [2500, 2000, 450];\ne = [-1, -1, -1];\n\n[m,n] = size(A);\nlp=mxlpsolve('make_lp',m,n);\nmxlpsolve('set_obj_fn',lp,f);\nmxlpsolve('set_mat',lp,A);\nmxlpsolve('set_rh_vec',lp,b);\nmxlpsolve('set_maxim',lp);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp',lp);\npause;\n\n% Example 3\n\nclc;\n\nf = -[40, 36];\nvub = [8, 10];\nA = sparse([5, 3]);\nb = [45];\ne = 1;\n\n[m,n] = size(A);\nlp=mxlpsolve('make_lp',m,n);\nmxlpsolve('set_obj_fn',lp,f);\nmxlpsolve('set_mat',lp,A);\nmxlpsolve('set_rh_vec',lp,b);\nmxlpsolve('set_constr_type',lp,1,2);\nmxlpsolve('set_upbo',lp,1,8);\nmxlpsolve('set_upbo',lp,2,10);\nmxlpsolve('set_maxim',lp);\nresult=mxlpsolve('solve',lp)\nobj=mxlpsolve('get_objective', lp)\nx=mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp',lp);\npause;\n\n% L1 Data fitting example with integer constraint on the intercept\n\n% Generate data\n\nclc;\nn = 40;\nt = (0:n-1)';\ny = 3.5 -.2*t;\ny = y + 0.5*randn(size(y));\n\nm = [ones(n,1),t(:)];\na = [m,-m,speye(n)];\nf = -[sum(m),sum(-m),2*ones(1,n)];\ne = ones(n,1);\n\nvub = [10, 10, 10, 10, 5*ones(1,n)];\n\n[v,x] = lp_solve(f,sparse(a),y,e,[],vub,[1,3]);\np = x(1:2)-x(3:4);\nerr = y-m*p;\n\nplot(t,y,'o',t,m*p);\nxlabel('t');\nylabel('y');\n\ndisp('Press any key to continue.');\npause;\n\nclc;\n% Now solve bigger problem\n\nn = 200;\nm = 100;\na = rand(m,n);\nidx = find(a<0.8);\na(idx) = zeros(length(idx),1);\na = sparse(a);\nz = rand(n,1);\nb = a*z;\n\n[v,x] = lp_solve(-ones(1,n),a,b,zeros(m,1));\n\nplot(a*x-b);\ntitle('Residuals');\nxlabel('Equation Number');\n\necho off\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Solvers/lp_solve/distribution/lpdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6368540483641699}} {"text": "function [X,info] = IRsirt(A,b,varargin)\n%IRsirt Simuletaneous Iterative Reconstruction Technique\n%\n% options = IRsirt('defaults')\n% [X,info] = IRsirt(A,b,K)\n% [X,info] = IRsirt(A,b,K,options)\n%\n% This function calls the function 'sirt' in AIR Tools II that implements a\n% number of Simultaneous Iterative Reconstruction Technique (SIRT) methods:\n% cav, cimmino, drop, landweber and sart (see AIR Tools II for more details).\n% The default method is sart which, in the CT community, is known as 'sirt'.\n%\n% With 'defaults' as input prints the default options. Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options. With options as input: uses the user- specified options\n% and all the other default options.\n%\n% Inputs:\n% A : either (a) a full or sparse matrix\n% (b) a matrix object that performs the matrix*vector operation\n% (c) user-defined function m-file\n% b : right-hand side vector\n% K : (optional) integer vector that specifies which iterates are returned\n% in X; the maximum number of iterations is assumed to be max(K)\n% [ positive integer | vector of positive components ]\n% options : structure with the following fields (optional)\n% sirt_mthod - the specific SIRT method to be used;\n% [ 'cav' | 'cimmino' | 'drop' | 'landweber' | {'sart'} ]\n% x0 - initial guess for the iterations; default = zero vector\n% [ array | {'none'} ]\n% MaxIter - maximum allowed number of iterations\n% [ {100} | positive integer ]\n% x_true - true solution; allows us to returns error norms\n% with respect to x_true at each iteration\n% [ array | {'none'} ]\n% stopCrit - stopping criterion for the iterations\n% [ {'none'} | 'discrep' ]\n% Note: 'discrep' requires NoiseLevel and eta\n% NoiseLevel - norm of noise in rhs divided by norm of rhs \n% [ {'none'} | nonnegative scalar]\n% eta - safety factor for the discrepancy principle\n% [ {1.01} | scalar greater than (and close to) 1 ]\n% relaxParam - constant relaxation parameter, bounded above 2 divided\n% by the spectral radius of the iteration matrix\n% [ positive scalar | {'none'} ]\n% If 'none' then a good value is chosed by the function\n% nonnegativity - apply nonnegativity constraints\n% [ 'on' | {'off'} ]\n% Ubound - apply box constraints in the interval [0,Ubound]\n% [ positive scalar | {'off'} ]\n% IterBar - shows the progress of the iterations\n% [ {'on'} | 'off' ]\n% Note: the options structure can be created using the function IRset.\n%\n% Outputs:\n% X : computed solutions, stored column-wise (at the iterations listed in K)\n% info : structure with the following fields:\n% its - number of the last computed iteration\n% saved_iterations - iteration numbers of iterates stored in X \n% StopFlag - a flag that describes the stopping condition:\n% 1 : reached maximum number of iterations\n% 2 : discrepancy principle satisfied\n% relaxParam - the used relaxation parameter\n% Enrm - relative error norms (requires x_true) for the\n% stored iterations\n%\n% Note that this function provides a simplified call to the function \"sirt\"\n% in AIR Tools II which has more features than we allow here. To use the\n% full power of the SIRT methods consider using AIR Tools II directly.\n%\n% See also: IRart, IRget, IRset\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD License. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('x0', 'none', 'IterBar', 'on', 'stopCrit', 'none', ...\n 'eta', 1.01, 'nonnegativity', 'off', 'NoiseLevel','none', ...\n 'Ubound', 'none', 'relaxParam', 'none', 'sirt_method', 'sart', ...\n 'MaxIter', 100, 'x_true', 'none');\n \n% If input is 'defaults,' return the default options in X.\nif nargin==1 && nargout <= 1 && isequal(A,'defaults')\n X = defaultopt;\n return;\nend\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n case 0\n K = []; options = [];\n case 1\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = [];\n else\n K = []; options = varargin{1};\n end\n case 2\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = varargin{2};\n else\n K = varargin{2}; options = varargin{1};\n end\n otherwise\n error('Too many input parameters')\nend\n\nif isempty(options)\n options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\n\nif min(K) < 1, error('Number of iterations must be positive'), end\n\nx0 = IRget(options, 'x0', [], 'fast');\nif strcmpi(x0, 'none')\n x0 = [];\nend\n\nMaxIter = IRget(options, 'MaxIter', [], 'fast');\nmethod = IRget(options, 'sirt_method', [], 'fast');\nIterBar = IRget(options, 'IterBar', [], 'fast');\nrelaxParam = IRget(options, 'relaxParam', [], 'fast');\nstopCrit = IRget(options, 'stopCrit', [], 'fast');\nnonnegativity = IRget(options, 'nonnegativity', [], 'fast');\nUbound = IRget(options, 'Ubound', [], 'fast');\nx_true = IRget(options, 'x_true', [], 'fast');\n\nif isempty(K)\n K = MaxIter;\nend\n% Sorting the iteration numbers (in case they are shuffled in input).\nK = sort(K,'ascend'); K = unique(K);\nif ~((isreal(K) && (all(K > 0)) && all(K == floor(K))))\n error('K must be a vector of positive real integers')\nend\n\n% Set options for SIRT. Always used a fixed lambda, either chosen by the\n% user or set by the SIRT function. Always use no stopping rule or stop\n% by the size of the residual (discrepancy principle).\n\nif strcmpi(relaxParam,'none')\n % The field lambda is not present.\nelse\n sirtoptions.relaxpar = relaxParam;\nend\n\nif strcmpi(stopCrit,'discrep')\n sirtoptions.stoprule.type = 'DP';\n if isempty(options.NoiseLevel) || strcmp(options.NoiseLevel,'none')\n error('When using discrepancy principle: options.NoiseLevel must be specified')\n end\n sirtoptions.stoprule.taudelta = options.eta*options.NoiseLevel*norm(b);\nelse\n sirtoptions.stoprule.type = 'none';\nend\n\nif strcmpi(nonnegativity,'on')\n sirtoptions.lbound = 0;\nend\n\nif (isreal(Ubound) && isscalar(Ubound) && Ubound > 0)\n sirtoptions.lbound = 0;\n sirtoptions.ubound = Ubound;\nend\n\nif strcmp(IterBar,'on')\n sirtoptions.waitbar = true;\nend\n \n% Call the requested SIRT method.\n[X,sirtinfo] = sirt(method,A,b,K,x0,sirtoptions);\n\nswitch sirtinfo.stoprule\n case 0\n info.StopFlag = 1;\n case 2\n info.StopFlag = 2;\n if sirtinfo.finaliter==0\n warning(['No iterations were performed, beause the starting',...\n ' vector x0 satisfies the discrepancy principle'])\n end\nend\ninfo.its = sirtinfo.finaliter;\ninfo.saved_iterations = sirtinfo.itersaved;\ninfo.relaxParam = sirtinfo.relaxpar;\n\n% Compute relative error norms, if requested.\nif ~strcmp(x_true,'none')\n Enrm = zeros(length(info.saved_iterations),1);\n for k=1:length(info.saved_iterations)\n Enrm(k) = norm(x_true-X(:,k));\n end\n info.Enrm = Enrm/norm(x_true);\nend", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/IRcodes/IRsirt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6368540366720499}} {"text": "function varargout = solver_sBPDN_WW( A, alpha, W1, beta, W2, b, epsilon, mu, x0, z0, opts, varargin )\n% SOLVER_SBPDN_WW BPDN with two separate (weighted) l1-norm terms. Uses smoothing.\n% [ x, out, opts ] = solver_sBPDN_WW( A, alpha, W_1, beta, W_2, b, epsilon, mu, x0, z0, opts )\n% Solves the smoothed basis pursuit denoising problem\n% minimize alpha*norm(W_1 x,1) + beta*norm(W_2 x, 1) + 0.5*mu*(x-x0).^2\n% s.t. norm(A*x-b,2) <= epsilon\n% by constructing and solving the composite dual.\n% A, W_1 and W_2 must be a linear operator or matrix, and b must be a vector. The\n% initial points x0, z0 and the options structure opts are optional.\n% See also solver_sBPDN and solver_sBPDN_W\n\n% Supply default values\nerror(nargchk(8,12,nargin));\nif nargin < 9, x0 = []; end\nif nargin < 10, z0 = []; end\nif nargin < 11, opts = []; end\nif ~isfield( opts, 'restart' ), opts.restart = 5000; end\n\nif epsilon < 0\n error('TFOCS error: epsilon is negative');\nend\nif ~epsilon\n error('TFOCS error: cannot handle epsilon = 0. Please call solver_sBP instead');\nelseif epsilon < 100*builtin('eps')\n warning('TFOCS:badConstraint',...\n 'TFOCS warning: epsilon is near zero; consider calling solver_sBP instead');\nend\n\n% Need to estimate the norms of A*A' and W*W' in order to be most efficient\nif isfield( opts, 'noscale' ) && opts.noscale,\n normA2 = 1; normW12 = 1; normW22 = 1;\nelse\n normA2 = []; normW12 = []; normW22 = [];\n if isfield( opts, 'normA2' )\n normA2 = opts.normA2;\n opts = rmfield( opts, 'normA2' );\n end\n if isfield( opts, 'normW12' )\n normW12 = opts.normW12;\n opts = rmfield( opts, 'normW12' );\n end\n if isfield( opts, 'normW22' )\n normW22 = opts.normW22;\n opts = rmfield( opts, 'normW22' );\n end\nend\nif isempty( normA2 ),\n normA2 = linop_normest( A ).^2;\nend\nif isempty( normW12 ),\n normW12 = linop_normest( W1 ).^2;\nend\nif isempty( normW22 ),\n normW22 = linop_normest( W2 ).^2;\nend\nif isempty(alpha), \n alpha = 1; \nend\nif isempty(beta), \n beta = 1; \nend\n\nproxScale1 = sqrt( normW12 / normA2 );\nproxScale2 = sqrt( normW22 / normA2 );\nprox = { prox_l2( epsilon ), ...\n proj_linf( proxScale1 * alpha ),...\n proj_linf( proxScale2 * beta ) };\nW1 = linop_compose( W1, 1 / proxScale1 );\nW2 = linop_compose( W2, 1 / proxScale2 );\n[varargout{1:max(nargout,1)}] = ...\n tfocs_SCD( [], { A, -b; W1, 0; W2, 0 }, prox, mu, x0, z0, opts, varargin{:} );\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\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/solver_sBPDN_WW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6367025496559632}} {"text": "function toms446_test02 ( )\n\n%*****************************************************************************80\n%\n%% TOMS446_TEST02 tests MULTPLY, which multiplies two Chebyshev series.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2011\n%\n% Author:\n%\n% John Burkardt\n%\n nf = 5;\n npl = 10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TOMS446_TEST02\\n' );\n fprintf ( 1, ' Test MLTPLY, which computes the\\n' );\n fprintf ( 1, ' product of two Chebyshev series.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Multiply series for SIN(X) and COS(X)\\n' );\n fprintf ( 1, ' and compare with series for 1/2*SIN(2X).\\n' );\n\n x = cheby ( nf, npl, @functn );\n\n for i = 1 : npl\n x1(i) = x(i,1);\n x2(i) = x(i,2);\n x(i,3) = 0.5 * x(i,3);\n end\n\n x3 = mltply ( x1, x2, npl );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sin(x) Cos(x) 1/2*Sin(2x) RESULT\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : npl\n fprintf ( 1, ' %10.4f %10.4f %10.4f %10.4f\\n', x(i,1:3), x3(i) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms446/toms446_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.636701365734451}} {"text": "function [filt] = notchfilter(dat,Fs,Fl,N)\n\n% NOTCHFILTER line noise reduction filter for EEG/MEG data\n%\n% [filt] = notchfilter(dat, Fsample, Fline)\n%\n% where\n% dat data matrix (Nchans X Ntime)\n% Fsample sampling frequency in Hz\n% Fline line noise frequency (would normally be 50Hz)\n% N optional filter order, default is 4\n%\n% if Fline is specified as 50, a band of 48-52 is filtered out\n% if Fline is specified as [low high], that band is filtered out\n\n% original (c) 2003, Pascal Fries\n% modifications (c) 2003, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin<4\n % set the default filter order\n N = 4;\nend\n\nNchans = size(dat,1);\nNsamples = size(dat,2);\n\n% use a digital FIR filter\nFn = Fs/2; % Nyquist frequency\nif length(Fl)==1\n % default use a notch-width of 2Hz in both directions\n % otherwise use the specified band\n Fl = [Fl-2 Fl+2];\nend\n[B, A] = butter(N, [min(Fl)/Fn max(Fl)/Fn], 'stop');\nfilt = filtfilt(B, A, dat')';\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/notchfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6365621042096166}} {"text": "function [ R, subgrad, data ] = risk2( data, W )\n%RISK evaluates risk term.\n% \n% Synopsis:\n% [R,subgrad,data] = risk(data)\n% [R,subgrad,data] = risk(data,W)\n%\n% Description:\n% Let the risk term be defined as\n%\n% R(W) = 1/m sum_{i=1}^m [ max_{y \\in Y}( (L(y_i, y) + ) - ]\n%\n% This function returns value R and subgradient SUBGRAD of the \n% risk R(W) at W.\n% \n% 10-08-10 Michal Uricar\n% 11-07-11 Michal Uricar, corners dataset (checked-only) + loss function modification\n\n options = data.options;\n\n if (nargin < 2)\n W = buildPsi2(options, data.tmpData, data.Y{1});\n W = sparse(length(W), 1);\n end\n \n psi_xiyhat = sparse(length(W), data.nImages);\n psi_xiyi = sparse(length(W), data.nImages);\n suma_all = zeros(1, data.nImages);\n \n for i = 1 : data.nImages\n% parfor i = 1 : data.nImages\n [lbpdat lbp_sparse] = getPsiMat(data, i);\n GT = data.Y{i};\n \n % \\hat{y_i} = argmax_{y \\in Y} [ L(y_i, y) + ]\n L = computeL(options, GT, data.kappa(i)); % with normalization\n% L = computeL(options, GT); % without normalization\n y_hat = argmax_mex(options, W, data.mapTable, lbp_sparse, L);\n \n % \\Psi(x_i, \\hat{y_i})\n psi_xiyhat(:, i) = buildPsi2(options, lbpdat, y_hat);\n % \\Psi(x_i, y_i)\n psi_xiyi(:, i) = buildPsi2(options, lbpdat, GT);\n \n % sum_{i = 1}^{m} ( max_{y \\in Y}( L(y_i, y) + )> ) - )\n % with normalization coefficient kappa \n suma_all(i) = 100 * data.kappa(i) * ...\n sum(1/data.options.M * sqrt(sum( (y_hat - GT).^2 ))) ...\n + W'*psi_xiyhat(:, i) - W'*psi_xiyi(:, i);\n% % without normalization coefficient kappa\n% suma_all(i) = sum(1/data.options.M * sqrt(sum( (y_hat - GT).^2 ))) ...\n% + W'*psi_xiyhat(:, i) - W'*psi_xiyi(:, i);\n end;\n\n suma = sum(suma_all);\n \n % \\hat{R}(w) = 1/m \\sum_{i = 1}^m [ max_{y \\in Y}( L(y_i, y) + )> ) - ]\n R = 1/data.nImages * suma;\n % \\partial_w \\hat{R}(w) = 1/m \\sum_{i = 1}^m ( \\Psi(x_i, \\hat{y_i}) - \\Psi(x_i, y_i) )\n subgrad = 1/data.nImages * sum(psi_xiyhat - psi_xiyi, 2);\n\nend\n", "meta": {"author": "uricamic", "repo": "flandmark", "sha": "ecf122f93f73504fe7d8faccca525c6b1e98fdcd", "save_path": "github-repos/MATLAB/uricamic-flandmark", "path": "github-repos/MATLAB/uricamic-flandmark/flandmark-ecf122f93f73504fe7d8faccca525c6b1e98fdcd/learning/code/Functions/risk2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6365078944009569}} {"text": "function x = singlehex2num(s)\n%SINGLEHEX2NUM Convert single precision IEEE hexadecimal string to number.\n% SINGLEHEX2NUM(S), where S is a 8 character string containing\n% a hexadecimal number, returns a double type number\n% equal to the IEEE single precision\n% floating point number it represents. Fewer than 8\n% characters are padded on the right with zeros.\n%\n% If S is a character array, each row is interpreted as a single\n% precision number (and returned as a double).\n%\n% NaNs, infinities and denorms are handled correctly. \n%\n% Example:\n% hexsingle2num('40490fdb') returns Pi.\n% hexsingle2num('bf8') returns -1.\n%\n% See also HEX2NUM.\n\n% Based on Matlab's hex2num.\n% Note: IEEE Standard 754 for floating point numbers\n%\n% Floating point numbers are represented as:\n% x = +/- (1+f)*2^e\n%\n% doubles: 64 bits\n% Bit 63 (1 bit) = sign (0=positive, 1=negative)\n% Bit 62 to 52 (11 bits)= exponent biased by 1023\n% Bit 51 to 0 (52 bits)= fraction f of the number 1.f\n% singles: 32 bits\n% Bit 31 (1 bit) = sign (0=positive, 1=negative)\n% Bit 30 to 23 (8 bits) = exponent biased by 127\n% Bit 22 to 0 (23 bits)= fraction f of the number 1.f\n%\n% Original file hexsingle2num from Mark Lubinski\n% Changed on 19-may-05 by Matthias Noell: denormalized power set 2^-126\n\nif iscellstr(s), s = char(s); end\nif ~ischar(s)\n error('Input to hexsingle2num must be a string.')\nend\nif isempty(s), x = []; return, end\n\n[row,col] = size(s);\nblanks = find(s==' '); % Find the blanks at the end\nif ~isempty(blanks), s(blanks) = '0'; end % Zero pad the shorter hex numbers.\n\n% Convert characters to numeric digits.\n% More than 8 characters are ignored\n% For double: d = zeros(row,16);\nd = zeros(row,8);\nd(:,1:col) = abs(lower(s)) - '0';\nd = d + ('0'+10-'a').*(d>9);\nneg = d(:,1) > 7;\nd(:,1) = d(:,1)-8*neg;\n\nif any(d > 15) | any(d < 0)\n error('Input string to hexsingle2num should have just 0-9, a-f, or A-F.')\nend\n\n% Floating point exponent.\n% For double: e = 16*(16*(d(:,1)-4) + d(:,2)) + d(:,3) + 1;\n% For double: e = 256*d(:,1) + 16*d(:,2) + d(:,3) - 1023;\nexpBit = (d(:,3) > 7);\ne = 32*d(:,1) + 2*d(:,2) + expBit - 127;\nd(:,3) = d(:,3)-8*expBit; % Remove most sig. bit of d(:,3) which belongs to exponent\n\n% Floating point fraction.\n% For double: sixteens = [16;256;4096;65536;1048576;16777216;268435456];\n% For double: sixteens2 = 268435456*sixteens(1:6);\n% For double: multiplier = 1./[sixteens;sixteens2];\n% For double: f = d(:,4:16)*multiplier;\nsixteens = [16;256;4096;65536;1048576;16777216];\nmultiplier = 2./[sixteens];\nf = d(:,3:8)*multiplier;\n\nx = zeros(row,1);\n% Scale the fraction by 2 to the exponent.\n% For double: overinf = find((e>1023) & (f==0));\noverinf = find((e>127) & (f==0));\nif ~isempty(overinf), x(overinf) = inf; end\n\n% For double: overNaN = find((e>1023) & (f~=0));\noverNaN = find((e>127) & (f~=0));\nif ~isempty(overNaN), x(overNaN) = NaN; end\n\n% For double: underflow = find(e<-1022);\nunderflow = find(e<-126);\nif ~isempty(underflow), x(underflow) = pow2(f(underflow),-126); end\n\n% For double: allothers = find((e<=1023) & (e>=-1022));\nallothers = find((e<=127) & (e>=-126));\nif ~isempty(allothers), x(allothers) = pow2(1+f(allothers),e(allothers)); end\n\nnegatives = find(neg);\nif ~isempty(negatives), x(negatives) = -x(negatives); end\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/7689-singlehex2num/singlehex2num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6365078918787033}} {"text": "function [R,current_eps]=MC_USTM_Alamouti(snrdB,T,L,epsilon,prec,filename)\n%\n% metaconverse bound for the Alamouti ensemble\n%-------------------------------------------------------------------\n% SET-UP PARAMETERS\n%-------------------------------------------------------------------\n\nSAVE=1;\nMAT=1;\n\nK = 2^prec; % number of monte carlo simulations (at least 100 x 1/epsilon)\nrho = 10.^(snrdB/10); % SNR in linear scale\nMt=2;\nMr=2;\n%-------------------------------------------------------------------\n% MONTE CARLO SIMULATION\n%-------------------------------------------------------------------\nIp = zeros(K,1); %allocate for the montecarlo runs\n% Iq = zeros(K,1); %allocate for the montecarlo runs\n%-------------------------------------------------------------------\n% CONSTANTS\n%-------------------------------------------------------------------\nrho_tilde = T*rho/Mt;\n\nlambda=1+rho_tilde;\nlambda1=1/lambda;\nlambda2=rho_tilde*lambda1;\n\nx1=rho_tilde;\nx2=rho_tilde;\n\nD= [diag([sqrt(1+x1), sqrt(1+x2)]), zeros(Mt,T-Mt);\nzeros(T-Mt,Mt), eye(T-Mt)]; % D matrix (covariance matrix of equivalent noise)\n\n\n%-------------------------------------------------------------------\n% MONTE CARLO\n%-------------------------------------------------------------------\n\n%tic\n\n\nnorm=sqrt(.5);\n\nfor k=1:K\n \n\n i_L = 0; \n \n Z = randn(T,Mr,L)*norm+1i*randn(T,Mr,L)*norm; \n\n for l = 1:L %Create each realization\n \n \n %COMPUTE EVERYTHING THAT HAS TO DO WITH SINGULAR VALUES\n Sigma_alt= svd(D*Z(:,:,l)).^2;\n Sigma_alt=sort(Sigma_alt,1,'descend');\n TraceZ=abs(trace(Z(:,:,l)'*Z(:,:,l)));\n \n Y=D*Z(:,:,l);\n \n Ytilde=(zeros(T,4)); \n \n Ytilde(:,[1,3])=Y;\n \n Ytilde(1:2:T,[2,4])= conj(Y(2:2:T,:));\n \n Ytilde(2:2:T,[2,4])= -conj(Y(1:2:T,:));\n \n Sigma=svd(Ytilde).^2;\n \n Sigma=[Sigma(1),Sigma(3)];\n \n Sigma=Sigma*lambda2;\n \n \n if (T>4), \n \n M=[gammainc(Sigma(1), T-5), gammainc(Sigma(1), T-4), exp(Sigma(2)-Sigma(1))*gammainc(Sigma(2), T-5)/(Sigma(2)/Sigma(1))^(T-4), exp(Sigma(2)-Sigma(1))*gammainc(Sigma(2), T-4)/(Sigma(2)/Sigma(1))^(T-4) ;\n (T-2)*Sigma(1), Sigma(1)^2,(T-2)*Sigma(2), Sigma(2)^2 ;\n T-3, Sigma(1),T-3, Sigma(2);\n (T-4)/Sigma(1),1,(T-4)/Sigma(2),1];\n \n logd=log(det(M))-(T-4)*log(Sigma(1))+Sigma(1);\n \n else\n \n M=[ 1, 2*Sigma(1), 1, 0 ; ...\n 1, Sigma(1)^2, Sigma(1), 1; ...\n exp(Sigma(2)-Sigma(1)), 2*Sigma(2), 1, 0; ...\n exp(Sigma(2)-Sigma(1)), Sigma(2)^2, Sigma(2), 1];\n \n logd=(log(det(M)))+Sigma(1);\n \n end\n \n log_exp_sum = logd -4*log(Sigma(1)-Sigma(2));\n \n i = - TraceZ +sum(Sigma_alt) - log(gamma(T)) - log_exp_sum;\n \n i_L = i_L + i; %add it to the total i_L \n \n end\n\n Ip(k) = i_L; %put all computations on a pile to compute the average later\nend\n\nif (SAVE==1) \n if (MAT==1)\n save(filename,'Ip')\n else\n save(filename,'Ip','-ascii','-append')\n end\nend\n\n\n\n%---------------------------------------\n% SEARCHING THE RATE\n%--------------------------------------- \n\n% load saved data (to account for append possibilities)\nif (SAVE==1 && MAT==0)\n\n Ip=load(filename);\nend\n\nIp=sort(Ip);\n\nKcurrent=length(Ip); % redefine K to account for append\n\ncurrent_prec=floor(log2(Kcurrent)); % actual precision\n\nK=2^(current_prec); % round off K to avoid search errors\n\n\n% first find a suitable initial point for the linear search\nstep=K/2;\nindex=step;\n\nonevec=ones(K,1);\n\nwhile(step>1),\n \n th=Ip(index);\n \n current_eps=sum(Ip<=th)/K;\n \n step=step/2;\n \n if current_eps> epsilon,\n \n index=index-step;\n \n else\n \n index=index+step;\n \n end\n \nend\n\ncurrent_eps=sum(Ip<=Ip(index))/K; \n\nif(current_eps \n% Water resource management problem\n\n%------------------------------- Reference --------------------------------\n% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,\n% A benchmark-suite of real-world constrained multi-objective optimization\n% problems and some baseline results, Swarm and Evolutionary Computation,\n% 2021, 67: 100961.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Initialization\n function Setting(obj)\n obj.M = 5;\n obj.D = 3;\n obj.lower = [0.01 0.01 0.01];\n obj.upper = [0.45 0.1 0.1];\n obj.encoding = ones(1,obj.D);\n end\n %% Evaluate multiple solutions\n function Population = Evaluation(obj,varargin)\n x = varargin{1};\n x1 = x(:,1);\n x2 = x(:,2);\n x3 = x(:,3);\n % Objectives\n f(:,1) = 106780.37 .* (x2 + x3) + 61704.67 ;\n f(:,2) = 3000 .* x1 ;\n f(:,3) = 305700 .* 2289 .* x2 ./ power(0.06.*2289, 0.65) ;\n f(:,4) = 250 .* 2289 .* exp(-39.75.*x2+9.9.*x3+2.74) ;\n f(:,5) = 25 .* (1.39 ./(x1.*x2) + 4940.*x3 -80) ;\n % Constraints \n g(:,1) = 1 - (0.00139./(x1.*x2)+4.94.*x3-0.08);\n g(:,2) = 1 - (0.000306./(x1.*x2)+1.082.*x3-0.0986);\n g(:,3) = 50000 - (12.307./(x1.*x2) + 49408.24.*x3+4051.02);\n g(:,4) = 16000 - (2.098./(x1.*x2)+8046.33.*x3-696.71);\n g(:,5) = 10000 - (2.138./(x1.*x2)+7883.39.*x3-705.04);\n g(:,6) = 2000 - (0.417.*x1.*x2 + 1721.26.*x3-136.54);\n g(:,7) = 550 - (0.164./(x1.*x2)+631.13.*x3-54.48);\n g = -g;\n Population = SOLUTION(varargin{1},f,g,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate a point for hypervolume calculation\n function R = GetOptimum(obj,~)\n R = [7.3450511e+04 1.3500000e+03 2.8534690e+06 6.6200320e+06 2.5000000e+04];\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/RWMOPs/RWMOP11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6364831381106743}} {"text": "function value = c8_div ( z1, z2 )\n\n%*****************************************************************************80\n%\n%% C8_DIV divides two C8's.\n%\n% Discussion:\n%\n% A C8 is a complex value.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 09 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, complex Z1, Z2, the arguments.\n%\n% Output, complex VALUE, the function value.\n%\n a = c8_real ( z1 );\n b = c8_imag ( z1 );\n c = c8_real ( z2 );\n d = c8_imag ( z2 );\n\n e = c * c + d * d;\n\n f = ( a * c + b * d ) / e;\n g = ( b * c - a * d ) / e;\n\n value = f + g * i;\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/c8lib/c8_div.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.636476047842312}} {"text": "function [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (dec)\n% by Sundar Krishnan\n% 2003, Edited in June, 2004\n%\n% Description :\n% This function Fr_dec2bin.m will convert a POSITIVE Decimal system\n% Fraction (dec) to Binary system Fraction Fr_bin.\n% Matlab itself has bin2dec.m and dec2bin.m, but there seems to be\n% no standard Matlab function when fractions are involved.\n%\n% This function Fr_bin2dec.m and it's companion / dual function Fr_dec2bin.m\n% were developed mainly with a view to get quick results\n% while learning Arithmetic (Entropy) Coding in School.\n% (Now, more comments have been added to better explain the programme.)\n%\n% The results of this function are limited in accuracy due to the\n% \"precision\" used in the function num2str.m in addition to\n% Floating Point limits and Rounding errors.\n%\n% Accumulation of errors due to these limits can be seen\n% when Fr_bin2dec and Fr_dec2bin are tested back-to-back in pairs.\n%\n% After experiments, I observed that the best precision is 16. \n% If all the digits of the input bin are used for a pure fraction,\n% the results are likely to be more accurate since we have more margin\n% wrt the limit of 16 digits.\n%\n% Given below under \"Usage Eg\" are the many cases\n% that have been tested during the development of this program,\n% together with the results obtained in each case.\n%\n% Pl do forward me any new case that breaks the code \n% beyond the aforesaid limitations.\n%\n% Outputs str_Fr and Fr_dec are intermediate results.\n%\n% See also : [Fr_dec, str_Fr, Fr_bin] = Fr_bin2dec (bin)\n%\n% Additional Test Cases involving pairs of dual tests\n% are given towards the end.\n%\n% ********************\n%\n% Usage Eg : (The foll have been tried out.)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.6796875) % 0.1010111\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (113.6796875) % 1110001.1010111\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (113.68359374)\n% = 1110001.10101110111111111\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (1045.013671875)\n% = 10000010101.000000111\n%\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.013671875) % 0.000000111\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000131835937)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (10099300.131835937)\n% = 100110100001101001100100.0010000111000000\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (1.0450137e+018)\n%\n% Also try this ! and enjoy the result :\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (1.0450137e+100)\n%\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (2987.120089)\n% % = 101110101011.0001111010111110\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (1167892987.120089)\n% % = 1000101100111001010000111111011.0001111010111110\n%\n% &&&&&&&&&&&&\n%\n% Usage Eg : Check in pairs :\n% Fr_dec = Fr_bin2dec (10000010100.0010000111) % = 1.044125000000000e+003\n% Fr_bin = Fr_dec2bin (1.044125000000000e+003) % = 10000010100.001\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec (10000010100.0010000111) )\n% returns Fr_bin = 10000010100.001\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec (101110101011.00011111) )\n% returns Fr_bin = 101110101011.0001 (corr to 2987.0625)\n% instead of the expected (same) 101110101011.00011111\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ...\n% (1000101100111001010000111111011.0001111010111110) )\n% returns Fr_bin = 1000101100111001000000000000000.00000000000000000\n% (corr to 1167884288)\n% instead of the expected (same)\n% 1000101100111001010000111111011.0001111010111110\n% which itself was obtained with Fr_dec2bin (1167892987.120089)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec (101110101011.0001111010111110) )\n% returns Fr_bin = 101110101011.0001 (corr to 2987.0625)\n% instead of the expected (same) 101110101011.0001111010111110\n% which itself was obtained with Fr_dec2bin (2987.120089)\n%\n%\n% ********************\n\n% 1) Inits :\nFr_bin = 0 ;\nexp_power = 0 ;\n\n% &&&&&&&&&&&&\n\n% 2) Use num2str to convert the input to string :\n%\n% After experiments, I observed that the best precision is 16. \n% For eg, with precision >= 17,\n% str_Fr = num2str ( .1010111, 17 ) = 0.10101110000000001\n% str_Fr = num2str ( .1010111, 16 ) = 0.1010111\n%\n% num2str.m's output will also contain \"0\" prefix before the decimal dot \".\"\n% which we remove later.\n\n% 2-a) Check if the input is greater than 1.\n% If yes, can we use higher precision ?\n% NO, I have found problems with precision > 16 even when the input > 1 !\n% So, commenting out the foll code, and retaining precision = 16 only.\n% str_Fr = num2str (dec) ;\n% if str_Fr > 1\n% precision = 48 ;\n% else\n% precision = 16 ;\n% end\n\nprecision = 16 ; % See the note above.\nstr_Fr = num2str (dec, precision) ;\n% Some egs of dec = 1045.0137 , 1.0450137e+018 , 0.131835937 , 0.0000131835937\n\n% NOTE : For long input dec strings, pl note that even with precision > 16,\n% say, with precision = 48, the input itself is accurately read\n% only for the first 16 digits ; or, if it is converted to an exp format,\n% then the input is accurately read only till 15 decimals after the dot.\n% For eg, if dec = 116789292349873465787.120089,\n% the whole integer part is taken as :\n% 116789292349873470000 = % 1.1678929234987347e+016\n% So, this will by itself creep in errors !\n\n% In general, it is observed errors will creep in\n% if the whole integer part > 999999999999999\n\n% &&&&&&&&&&&&\n\n% 3) Now, if str_Fr above is in exp format, as for eg,\n% '2.987062500000000e+003', we would like to get it in the form = 2987.0625\n%\n% I have observed that if the input no < 0.0001 (ie, < 0.0001000...)\n% num2str.m's output is in the exp form ie, with powers less than e-005.\n% For eg, dec = 0.000100000001 gives str_Fr = 0.000100000001\n% But dec = 0.0000999999999999 gives str_Fr = 9.9999999999900001e-005\n%\n% Also, with precision = 16, num2str.m's output for nos > 1, upto 1.0e+015,\n% is WITHOUT the exp form of power. For eg,\n% with dec = 999999999999999.9999999999999999\n% str_Fr = num2str (dec, 16) % gives = 1.0e+015 = 1 0000 0000 0000 000\n%\n% For nos > 1e+016, num2str.m's output is in exp form.\n\nif ~isempty ( findstr ( str_Fr, 'e') )\n \n exp_power = 0 ;\n [str_Fr_Bef_Exp, exp] = strtok ( str_Fr, 'e' ) ;\n % Some egs = str_Fr_Bef_Exp = 1.119996810555458, exp = e-005\n \n [exp_power, ign ] = strtok ( exp, 'e' ) ;\n % exp starts with 'e', hence see LHS\n \n exp_power = abs ( str2num (exp_power) ) ;\n \n % Remove the dot at the 2nd place : (as in 1.119996810555458)\n % However, there is no dot when it's a pure fraction,\n % and is an exact submultiple of 2 !\n if length (str_Fr_Bef_Exp) >= 2 ;\n str_Fr_Bef_Exp (2) = [] ;\n end\n \n \n if exp (2) == '-' % < 1e-005\n for k = 1 : exp_power - 1\n str_Fr_Init_Zeros(k) = '0' ;\n end\n \n str_Fr = strcat ( '0.', str_Fr_Init_Zeros, str_Fr_Bef_Exp ) ;\n\n \n elseif exp (2) == '+' % > 1.0e+015\n \n str_Fr = str_Fr_Bef_Exp ;\n \n % Normally, the foll \"if\" loop should not be necessary\n % since exp format does not occur for powers <= 1.0e+015. Still ...\n if length ( str_Fr ) > exp_power + 1\n \n str_Fr ( end + 1 ) = str_Fr (end) ;\n \n for j = length (str_Fr) - 1 : -1 : ...\n length (str_Fr) - (exp_power + 1) + 1\n \n str_Fr ( j ) = str_Fr (j-1) ;\n end\n \n str_Fr (exp_power + 2) = '.' ;\n \n end\n \n % Foll logic when exp_power > 1.0e+015, like for eg,\n % str_Fr = '1.0450137e+018'\n % implies str_Fr_Bef_Exp = 10450137 (length = 8)\n % ie, str_Fr should become 10450137 0000 0000 000 (length = 19)\n % ie, padding with 0s at the end is reqd.\n if length ( str_Fr ) < exp_power\n str_Fr = strcat ( str_Fr, ...\n repmat ( ['0'], 1, exp_power - (length ( str_Fr ) - 1) ) ) ;\n end\n \n end\n \nend\n\n% &&&&&&&&&&&&\n\n% 4) Separate the whole integer and fraction parts of str_Fr.\n[bef_dec, Fr_dec] = strtok ( str_Fr, '.' ) ;\n\n% &&&&&&&&&&&&\n\n% Now, we have bef_dec as the whole integer part, and\n% the Fractional part starting \".\"\n\n% 5) Convert first the whole integer part to binary\n% by calling the std Matlab's fn dec2bin.m\nbef_bin = dec2bin ( str2num (bef_dec) ) ;\n\n% &&&&&&&&&&&&\n\n% 6) Now, finally, deal with the Fractional Part.\n\nlen_strFr = length (Fr_dec) ;\n% eg of Fr_dec = '.123456789' or = '.000000001' or = '.12402343750000'\n\n% The Fractional Part Fr_bin should start here with the dot :\n% We will later concatenate bef_bin and Fr_bin\n%\n% Note : The part about the Fractional Part Fr_bin is not as starightforward\n% as the Fractional part Fr_dec in the dual file Fr_bin2dec.m\n% It is more complex due to the fact that we need to find the decreasing\n% powers of 2 that will match with Fr_dec.\n\nFr_bin = '.' ;\n\nFr_dec_Current = str2num (Fr_dec) ;\n\nfor k = 1 : 16\n if Fr_dec_Current >= 2^(-k)\n % Fr_bin = strcat ( Fr_bin, repmat (['0'], 1, k - length(Fr_bin)), ...\n % '1' ) ; % Old round about code, but it seems it still works !\n Fr_bin = strcat ( Fr_bin, '1' ) ;\n \n Fr_dec_Current = Fr_dec_Current - 2^-(k) ;\n \n % Don't go beyond the pt where the current decremented balance\n % is 0 or negative. This will happen if input dec is <= 2^(-16) !\n if Fr_dec_Current <= 0 % Uncomment foll when you want to see details\n % fprintf ( '\\n ********** Fr_dec_Current <= 0 ********** \\n' ) ;\n % fprintf ( '\\n ******* Pausing ... Prees any Key ******* \\n' ) ;\n % pause\n break ;\n end\n\n else\n % Fr_bin = strcat ( Fr_bin, repmat (['0'], 1, k - length(Fr_bin)), ...\n % '0' ) ; % Old round about code, but it seems it still works !\n Fr_bin = strcat ( Fr_bin, '0' ) ;\n end\n \nend % for k = 1 : 16\n\n% k, Fr_bin, Fr_dec_Current % Uncomment for testing\n\n% Note that since precision is set to 16, the limit in our code is :\n% 2^(-16) = 0.0000152587890625\n% So, if a fraction is less than 2^(-16), we will have Fr_bin = \".\"\n% at this point.\n\n% ++++++++++++\n\n% 6-b) Also, check at the next level 2^(-k-1) ie, beyond the above k\n% to add 1 at the end if Fr_dec_Current >= the half mark.!\n% At the limit of k = 16 above, 2^(-17) = 0.00000762939453125\n\n% However, we need to take caution if the no is lower than 2^(-16)\n% in which case Fr_bin at this point, would be just '.0000000000000000'\n\nif length(Fr_bin) == 17 & all ( Fr_bin == '.0000000000000000' )\n% Note for R13 : If short-circuiting double && were used (not in R12),\n% the 2nd expr will NOT be evaluated if the 1st is false\n% ie, if false AND X is always false, so X is not computed.\n\n% However, it is observed that even with this single &,\n% the 2nd expr is not computed if the 1st expr is false.\n\n if Fr_dec_Current >= 2^-(17)\n % Fr_bin = strcat ( Fr_bin, repmat ( ['0'], 1, 16 ), '1' ) ; % Old\n Fr_bin = strcat ( Fr_bin, '1' ) ;\n \n Fr_dec_Current = Fr_dec_Current - 2^-(17) ;\n if Fr_dec_Current >= 2^(-18)\n Fr_bin = strcat ( Fr_bin, '1' ) ;\n end\n \n else\n % Fr_bin = strcat ( Fr_bin, repmat ( ['0'], 1, 17 ), '1' ) ; % Old\n Fr_bin = strcat ( Fr_bin, '0' ) ;\n \n Fr_dec_Current = Fr_dec_Current - 2^-(18) ;\n if Fr_dec_Current >= 2^(-19)\n Fr_bin = strcat ( Fr_bin, '1' ) ;\n end\n end\n \nelseif Fr_dec_Current >= 2^(-k-1)\n % At this point, normally, k should be 16\n % unless at some point above, Fr_dec_Current <= 0\n Fr_bin = strcat ( Fr_bin, '1' ) ;\n % fprintf ( '\\n ************ Last 1 added. ************ \\n' ) ;\nend\n\n% &&&&&&&&&&&&\n\n% 7) Concatenate the whole integer part and the fraction parts.\nFr_bin = strcat ( bef_bin, Fr_bin ) ;\n\n% Fr_bin\n\n% class_Fr_bin = class(Fr_bin) % = char (Note)\n% But note that the dual function :\n% Fr_dec = Fr_bin2dec (bin) returns a double !\n\n\n% ********************\n\n% 8) Some additional Test Cases :\n\n% dec < 2^(-16) = 0.0000152587890625 (nearer to 2^-16 than 2^-17)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000131835937) \n% = 0.000000000000000011 (16 0s, 1, 1)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.000000000000000011 ) )\n% = 0.000000000000000011 (16 0s, 1, 1)\n% Fr_bin2dec ( 0.000000000000000011 ) = 0.000011444091796875\n% (= 2^-17 + 2^-18) in place of 0.0000131835937\n\n% ++++++++++++\n\n% dec < 2^(-16) = 0.0000152587890625 (nearer to 2^-17 than 2^-16)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000101835937)\n% = 0.00000000000000001 (16 0s, 1)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.00000000000000001 ) )\n% = 0.00000000000000001 (16 0s, 1)\n% Fr_bin2dec ( 0.00000000000000001 ) = 0.00000762939453125\n% (= 2^-17) in place of 0.0000101835937\n\n\n% ++++++++++++\n\n% Midway betn 2^-17 and 2^-18 = 0.0000057220458984375\n% dec < 2^(-17) = 0.00000762939453125 (nearer to 2^-18 than 2^-17)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000056835937)\n% = 0.00000000000000000 (17 0s)\n% \n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.00000000000000000 ) )\n% = 0.00000000000000000 (17 0s)\n% Fr_bin2dec ( 0.00000000000000000 ) = 0.0\n% in place of 0.0000056835937\n\n\n% ++++++++++++\n\n% dec < 2^(-17) = 0.00000762939453125 (nearer to 2^-17 than 2^-18)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000070835937)\n% = 0.000000000000000001 (17 0s, 1)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.000000000000000001 ) )\n% = 0.000000000000000001 (17 0s, 1)\n% Fr_bin2dec ( 0.000000000000000001 ) = 0.000003814697265625\n% (= 2^-18) in place of 0.0000070835937\n\n\n% ++++++++++++\n\n% dec < 2^(-17) = 0.00000762939453125 (nearer to 2^-18 than 2^-17)\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.0000039935937)\n% = 0.00000000000000000 (17 0s)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.00000000000000000 ) )\n% = 0.00000000000000000 (17 0s)\n% Fr_bin2dec ( 0.00000000000000000 ) = 0.0\n% in place of 0.0000039935937\n% in place of anything < (2^-17 - 2^-19)\n% ie, < Midway betn 2^-17 and 2^-18\n% ie, < 0.0000057220458984375\n\n% ++++++++++++\n\n% dec = 0.00001652587890625 very slightly > 2^(-16) = 0.0000152587890625\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (0.00001652587890625)\n% = 0.0000000000000001 (15 0s, 1)\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 0.0000000000000001 ) )\n% = 0.0000000000000001 (15 0s, 1)\n% Fr_bin2dec ( 0.0000000000000001 ) = 0.0000152587890625\n% in place of 0.00001652587890625\n\n\n% ++++++++++++\n\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (999 + 2^-11 + 2^-9)\n% = 1111100111.00000000101\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 1111100111.00000000101 ) )\n% = 1111100111.00000000000000000\n%\n% Fr_bin2dec ( 1111100111.00000000101 ) = 999\n% [Fr_dec, str_Fr, Fr_bin] = Fr_bin2dec ( 1111100111.00000000101 )\n% gives Fr_dec = 999 in place of 999.00244140625 ,\n% str_Fr = 1111100111 and an empty Fr_bin \n% because of the precision = 16 limit !\n%\n% However, Fr_bin2dec ( .00000000101 ) = 0.00244140625\n% This shows that if the all the digits of the input bin are used\n% for a pure fraction, the results are likely to be more accurate\n% since we have more margin wrt the limit of 16 digits.\n\n% ++++++++++++\n\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (879.0010365625)\n% = 1101101111.00000000010000111\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 1101101111.00000000010000111 ) )\n% = 1101101111.00000000000000000\n% Fr_bin2dec ( 1101101111.00000000010000111 ) = 879\n% in place of 879.0010365625\n\n% ++++++++++++\n\n% [Fr_bin, str_Fr, Fr_dec] = Fr_dec2bin (879.0012765625)\n% = 1101101111.00000000010100111\n%\n% Fr_bin = Fr_dec2bin ( Fr_bin2dec ( 1101101111.00000000010100111 ) )\n% = 1101101111.00000000000000000\n% Fr_bin2dec ( 1101101111.00000000010100111 ) = 879\n% in place of 879.0012765625\n\n% ++++++++++++\n\n% ********************\n\n% 9) Some useful values :\n% (Pl note that the char length below in each line may cross 80 chars !\n% But wrapping will not look nice nor easy to understand !)\n%\n% 2^-9 = 0.001953125\n% 2^-10 = 0.0009765625\n% 2^-11 = 0.00048828125\n% 2^(-14) = 0.00006103515625\n% 2^(-15) = 0.000030517578125\n% 2^(-16) = 0.0000152587890625\n% 2^(-17) = 0.00000762939453125\n% 2^(-18) = 0.000003814697265625\n% 2^(-19) = 0.0000019073486328125\n%\n% The pgm was tested with these values during development.\n% These values can be spot-tested by testing the result of Fr_dec2bin ( dec). For eg :\n% Fr_dec2bin ( 0.000285828865257397324183692319802554 ) ; = 0.00000000000100101\n%\n% Test Base = 2^(-15) :\n% 2^(-15) + 2^(-16) = 0.0000457763671875 0.0000000000000011\n%\n% 2^(-15) + 2^(-16.9) = 0.0000386945607188132718216934686662547 0.00000000000000101\n% 2^(-15) + 2^(-17) = 0.00003814697265625 0.00000000000000101\n% 2^(-15) + 2^(-17.1) = 0.0000376360549281067460325725041667934 0.0000000000000010\n%\n% 2^(-15) + 2^(-18) = 0.000034332275390625 0.0000000000000010\n% 2^(-15) + 2^(-18.01) = 0.0000343059253518563686429336937594913 0.0000000000000010\n% 2^(-15) = 0.000030517578125\n\n\n% Test Base = 2^(-14) :\n% 2^(-14) + 2^(-15) = 0.000091552734375 0.000000000000011\n% 2^(-14) + 2^(-15.1) = 0.0000895090634624269841302900166671735 0.00000000000001011\n%\n% 2^(-14) + 2^(-15.55) = 0.0000826143426875777442749281116365005 0.0000000000000101\n% 2^(-14) + 2^(-16) = 0.0000762939453125 0.0000000000000101\n%\n% 2^(-14) + 2^(-16.55) = 0.0000714572163143493310459230799506385 0.00000000000001001\n% 2^(-14) + 2^(-17) = 0.00006866455078125 0.00000000000001001\n%\n% 2^(-14) + 2^(-18) = 0.000064849853515625 0.0000000000000100\n% 2^(-14) + 2^(-18.01) = 0.0000648235034768563686429336937594913 0.0000000000000100\n% 2^(-14) = 0.00006103515625 0.00000000000001\n\n\n% Test Base = 2^(-13) :\n\n% 2^(-13) + 2^(-14) = 0.00018310546875 0.00000000000011\n% 2^(-13) + 2^(-14.01) = 0.00018268386812970189828693910015186 0.00000000000010111\n% 2^(-13) + 2^(-14.1) = 0.000179018126924853968260580033334347 0.00000000000010111\n% 2^(-13) + 2^(-14.45) = 0.000166750662107715619528003885783119 0.00000000000010101\n%\n% 2^(-13) + 2^(-14.75) = 0.000158362033538901399741134642656265 0.0000000000001010\n% 2^(-13) + 2^(-15) = 0.000152587890625 0.000000000000101\n%\n% 2^(-13) + 2^(-15.75) = 0.000140216173019450699870567321328132 0.0000000000001001\n% 2^(-13) + 2^(-16) = 0.0001373291015625 0.0000000000001001\n% 2^(-13) = 0.0001220703125 0.0000000000001\n\n\n% Test Base = 2^(-12) :\n% 2^(-12) + 2^(-13) = 0.0003662109375 0.0000000000011\n% 2^(-12) + 2^(-13.55) = 0.000327517105514794648367384639605108 0.0000000000010101\n%\n% 2^(-12) + 2^(-14) = 0.00030517578125 0.00000000000101\n% 2^(-12) + 2^(-14.55) = 0.000285828865257397324183692319802554 0.00000000000100101\n%\n% 2^(-12) + 2^(-15) = 0.000274658203125 0.000000000001001\n% 2^(-12) = 0.000244140625 0.000000000001\n\n\n% Test Base = 2^(-1) :\n% 2^(-1) + 2^(-16) = 0.5000152587890625 0.1000000000000001\n% 2^(-1) + 2^(-16.1) = 0.500014236953606213492065145008334 0.10000000000000001\n\n% 2^(-1) + 2^(-16.9) = 0.500008176982593813271821693468666 0.10000000000000001\n% 2^(-1) + 2^(-17) = 0.50000762939453125 0.10000000000000001\n% 2^(-1) + 2^(-17.1) = 0.500007118476803106746032572504167 0.1000000000000000 \n\n% 2^(-1) + 2^(-17.99) = 0.500003841230583407283053713600975 0.1000000000000000\n% 2^(-1) + 2^(-18) = 0.500003814697265625 0.1000000000000000\n% 2^(-1) + 2^(-18.01) = 0.500003788347226856368642933693759 0.1000000000000000\n% 2^(-1) = 0.5 0.1\n\n\n% Test Base = 2^(-16) :\n% 2^(-16) + 2^(-16.99) = 0.0000229412502293145661074272019509372 0.00000000000000011\n% 2^(-16) + 2^(-17) = 0.00002288818359375 0.00000000000000011\n% 2^(-16) + 2^(-17.01) = 0.0000228354835162127372858673875189825 0.0000000000000001\n%\n% 2^(-16) + 2^(-17.99) = 0.0000191000196459072830537136009754686 0.0000000000000001\n% 2^(-16) + 2^(-18) = 0.000019073486328125 0.0000000000000001\n% 2^(-16) + 2^(-18.01) = 0.0000190471362893563686429336937594913 0.0000000000000001\n%\n% 2^(-16) + 2^(-19) = 0.0000171661376953125 0.0000000000000001\n% 2^(-16) = 0.0000152587890625 0.0000000000000001\n\n% Test Base = 2^(-17) :\n% 2^(-17) = 0.00000762939453125 0.00000000000000001\n\n% Test Base = 2^(-18) :\n% 2^(-18) = 0.000003814697265625 0.0000000000000000\n\n% Midway betn 2^-17 and 2^-18 = 0.0000057220458984375 is just above 0 ;\n% 0.0000057220458984375 is the limit for this set of programmes.\n% Anything < (2^-17 - 2^-19) ie, anything < 0.0000057220458984375 is 0.\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/5396-conversion-of-fractions-from-binary-to-decimal-and-vice-versa/Fr_dec2bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6364760452022739}} {"text": "function [A,B,D,E,I]=twt(X);\n% subprogram for Twin T circuit\n%\nN=3; % N = no. of L's & C's\nM=1; % M = no. of indep inputs\nU=2; % U = no. of dep nodes in dc equivalent circuit\nY=2; % Y = output node in dc equiv ckt = V3\n%\n% X = [R1 R3 R5 R7 C2 C4 C6];\n% 1 2 3 4 5 6 7 \n%\nR1=X(1);R3=X(2);R5=X(3);R7=X(4);C2=X(5);C4=X(6);C6=X(7);\n% Create array space\nA1=zeros(U+N);B2=zeros(U+N,N+M);V=zeros(U+N,N+M);H=zeros(N,M+N);\n%\n% Build A1 matrix.\n%\nA1=[1/R5 0 0 -1 -1;\n 0 -1/R3 1 0 0;\n 0 1/R3+1/R7 0 0 1;\n 1 0 0 0 0;\n -1 1 0 0 0];\n%\n% Fill in B2 array\nE2=1;E4=1;E6=1;Ein=1;\n%\nB2=[0 0 0 0;\n -E2*(1/R1+1/R3) 0 0 Ein/R1;\n E2/R3 0 0 0;\n 0 -E4 0 Ein;\n 0 0 E6 0];\n%\nP=diag([C2 C4 C6]);\n%\n% As stated previously, the following code is\n% the same for every circuit.\n% \nV=A1\\B2;H=V(U+1:U+N,1:N+M);I=eye(N);\nAB=P\\H;A=AB(1:N,1:N);B=AB(1:N,N+1:N+M);\nD=V(Y:Y,1:N);E=V(Y:Y,N+1:N+M);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/twt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686647, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6364681362979017}} {"text": "% function Css = synsq_adm(type, opt)\n%\n% Calculate the Synchrosqueezing admissibility constant, the term\n% R_\\psi in Eq. 3 of [1]. Note, here we multiply R_\\psi by the\n% inverse of log(2)/nv (found in Alg. 1 of that paper).\n%\n% 1. E. Brevdo, N.S. Fučkar, G. Thakur, and H-T. Wu, \"The\n% Synchrosqueezing algorithm: a robust analysis tool for signals\n% with time-varying spectrum,\" 2011.\n%\n% Uses numerical integration.\n%\n% Input:\n% type: type of wavelet (see help wfiltfn)\n% opt: options structure (wavelet parameters, see help wfiltfn)\n%\n% Output:\n% Css: proportional to 2*int(conj(f(w))/w, w=0..inf)\n%\n%---------------------------------------------------------------------------------\n% Synchrosqueezing Toolbox\n% Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\nfunction Css = synsq_adm(type, opt)\n if nargin<2, opt=struct(); end\n switch type\n % case 'sombrero',\n % if ~isfield(opt,'s'), s = 1; else s = opt.s; end\n % Cpsi = (4/3)*s*sqrt(pi);\n % case 'shannon',\n % Cpsi = log(2);\n otherwise\n psihfn = wfiltfn(type, opt);\n Css = quadgk(@(x) conj(psihfn(x))./x, 0, Inf);\n end\n\n % Normalization constant, due to logarithmic scaling in wavelet\n % transform\n Css = Css / (sqrt(2*pi)*2*log(2));\nend\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/synchrosqueezing/synchrosqueezing/synsq_adm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6364576091575391}} {"text": "% ir_ct_roi_split1.m\n% \"frequency split\" approach to ROI recon of Lin Fu et al. from Fully 3D 2015.\n% Low frequency part of ROI sinogram comes from reprojecting FBP ROI image,\n% whereas high frequency part comes from original sinogram.\n% ROI reconstructed using PWLS-OS-LALM\n% 2015-06-17 Jeff Fessler, University of Michigan\n\nif ~isvar('Af'), printm 'setup geometry'\n\tf.down = 4;\n\tigf = image_geom('nx', 512, 'fov', 50, 'down', f.down);\n\tigf.mask = igf.circ > 0;\n\tsg = sino_geom('ge1', 'units', 'cm', 'strip_width', 'd', ...\n\t\t'down', f.down);\n\n\tigr = igf;\n\tigr.mask = igr.circ(11, 11, -10, 4) > 0;\n\tim(igf.mask + igr.mask)\n\n\t% system objects\n\tif has_mex_jf\n\t\tAf = Gtomo2_dscmex(sg, igf); % full\n\t\tAr = Gtomo2_dscmex(sg, igr); % roi\n\telse\n\t\tAf = Gtomo_nufft_new(sg, igf);\n\t\tAr = Gtomo_nufft_new(sg, igr);\n\tend\nend\n\n\nif ~isvar('xtrue'), printm 'xtrue, sinogram'\n\t% read image\n xtrue256 = ir_get_data('ncat_256_slice_140_ct_x100.fld');\n\txtrue256 = single(xtrue256) / 200 * 0.4; % convert to 1/cm units\n\n\tif 1 % more realistic sinogram from finer image, avoid \"inverse crime\"\n\t\tig_big = image_geom('nx', 512, 'fov', igf.fov, 'down', 2);\n\t\tif has_mex_jf\n\t\t\tAbig = Gtomo2_dscmex(sg, ig_big);\n\t\telse\n\t\t\tAbig = Gtomo_nufft_new(sg, ig_big);\n\t\tend\n\t\tsino_true = Abig * xtrue256;\n\tend\n\txtrue = downsample2(xtrue256, f.down/2);\n\n\tim plc 2 2\n\tclim = [0 0.4];\n\tim(1, xtrue, 'x true', clim), cbar\n\txlabelf('units: 1 / %s', sg.units)\n\tim(2, sino_true, 'sino true'), cbar\n\tim(3, xtrue + igf.mask + igr.mask)\n\n\tclear ddir ig_big Abig\ndrawnow\nend\n\n\nmask2 = conv2(single(igr.mask), ones(9)/9^2, 'same') > 0.999; % for roi rmse\nim(3, igf.mask + igr.mask + mask2, 'ROIs')\nxl = @(x) xlabelf('RMSE = %.3f / %s', rms(col(x - xtrue)), sg.units);\nxr = @(x) xlabelf('RMSE = %.3f / %s', rms(x(mask2) - xtrue(mask2)), sg.units);\n\n\nif ~isvar('sino'), printm 'noisy sinogram'\n\trng(0)\n\t% transmission data:\n\tI0 = 1e5;\n\tyi = poisson(I0 * exp(-sino_true), 0, 'factor', 0.1);\n\tif any(yi(:) == 0)\n\t\twarn('%d of %d values are 0 in sinogram!', ...\n\t\t\tsum(yi(:)==0), length(yi(:)));\n\tend\n\tsino = log(I0 ./ max(yi,1)); % noisy fan-beam sinogram\n\tim(4, sino, 'sino noisy'), cbar\ndrawnow\n%\tir_savefig ir_ct_roi_split1a\nend\n\n\nif ~isvar('fbp'), printm 'fbp 2d fan-beam reconstruction'\n\ttmp = fbp2(sg, igf);\n\tfbp = fbp2(sino, tmp, 'window', 'hanning,0.75');\n\tim(2, fbp, 'FBP Hanning', clim), cbar\n\txl(fbp)\nprompt\nend\n\n\nif ~isvar('kappa'), printm 'kappa: try to make resolution approximately uniform'\n\twi = yi; % will give 0 weight to any ray where yi=0!\n\tkappa = sqrt( div0(Af' * wi, Af' * ones(size(wi))) );\n\tim(3, kappa, 'kappa'), cbar\nprompt\nend\n\n\n% use local psf to help select beta\nif ~isvar('R'), printm 'R'\n\tf.l2b = 10; % maybe a bit too big, but ok for now\n\tf.delta = 0.001;\n%\tf.pot_arg = {'lange3', f.delta}; % todo: why not as sharp as hyper3?\n\tf.pot_arg = {'hyper3', f.delta};\n\tR = Reg1(kappa, 'beta', 2^f.l2b, 'pot_arg', f.pot_arg);\n\tRr = Reg1(kappa .* igr.mask, 'beta', 2^f.l2b, 'pot_arg', f.pot_arg);\n%\tqpwls_psf(A, R, 1, igf.mask, Gdiag(wi), 'loop', 1); % use this to choose beta\nend\n\nf.niter = 6;\nf.nblock = 41; % 41 subsets\n\n% OS-LALM\nif ~isvar('xlalmf'), printm 'iterative reconstruction - lalm full'\n\tAb = Gblock(Af, f.nblock);\n\txlalmf = ir_pwls_os_lalm(fbp(igf.mask), Ab, sino, R, 'wi', wi, ...\n\t\t'isave', 'last', 'niter', f.niter);\n\txlalmf = igf.embed(xlalmf);\n\tim(4, xlalmf(:,:,end), 'LALM full', clim), cbar\n\txl(xlalmf(:,:,end))\n%\tir_savefig ir_ct_roi_split1b\nend\n\n\nif ~isvar('fbpr'), printm 'fbp 2d fan-beam reconstruction - roi'\n\ttmp = fbp2(sg, igr);\n\tfbpr = fbp2(sino, tmp);\n\tim(1, xtrue .* igr.mask, 'True roi', clim), cbar\n\tim(2, fbpr, 'FBP roi', clim), cbar\n\txr(fbpr)\nprompt\nend\n\nif ~isvar('Hhi'), printm 'filters'\n\tnf = 2 * sg.nb;\n\tu = [-nf/2:nf/2-1]'/nf;\n\tcut = 0.1;\n\tHhi = min((u/cut).^2, 1);\n\tHlo = 1 - Hhi;\n\tplot(u, Hlo, '-o')\n\tclear u\nend\n\nif ~isvar('sino_roi'), printm 'sino_roi'\n\tsino_f = fft(sino, nf, 1);\n\tsino_hi = ifft(sino_f .* repmat(ifftshift(Hhi), [1 sg.na]), [], 1);\n\tsino_hi = sino_hi(1:sg.nb, :);\n\tim(1, fftshift(sino_f, 1))\n\tim(2, sino_hi, 'Hi-pass sino')\n\n\tsino_Ar = Ar * fbpr;\n\tsino_Arf = fft(sino_Ar, nf, 1);\n\tim(1, sino_Ar, 'Reproj FBP')\n sino_lo = ifft(sino_Arf .* repmat(ifftshift(Hlo), [1 sg.na]), [], 1);\n\tsino_lo = sino_lo(1:sg.nb, :);\n\tim(3, sino_lo, 'Low-pass sino')\n\n\tsino_roi = sino_lo + sino_hi;\n\tim(4, sino_roi, 'Synth ROI sino')\n\tclear sino_f sino_Arf\n%\tir_savefig ir_ct_roi_split1c\nprompt\nend\n\n\n% OS-LALM\nif ~isvar('xlalmr'), printm 'iterative reconstruction - lalm roi'\n\tAb = Gblock(Ar, f.nblock);\n\txlalmr = ir_pwls_os_lalm(fbpr(igr.mask), Ab, sino_roi, Rr, 'wi', wi, ...\n\t\t'isave', 'last', 'niter', 2*f.niter);\n\txlalmr = igr.embed(xlalmr);\nend\n\nif 1 % pics\n\tim(4, xlalmr(:,:,end), 'PWLS-OS-LALM roi', clim), cbar\n\txr(xlalmr(:,:,end))\n\n\tim(1, xtrue .* igr.mask, 'True roi', clim), cbar\n\tim(2, fbpr, 'FBP Ramp roi', clim), cbar\n\txr(fbpr)\n\tim(3, fbp .* igr.mask, 'FBP Hanning roi', clim), cbar\n\txr(fbp)\n%\tir_savefig ir_ct_roi_split1d\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/ir_ct_roi_split1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6364561754284632}} {"text": "\nclear all\nB0 = 1; Rtriple = 2; Damnio = 3;\nB1 = 4; Ramnio = 5; Dabort = 6; \nB2 = 7; U = 8;\n\nN = 8;\ndag = zeros(N,N);\ndag(B0, [Rtriple B1 Ramnio]) = 1;\ndag(Rtriple, [Damnio Dabort]) = 1;\ndag(Damnio, [B1 Ramnio]) = 1;\ndag(B1, B2) = 1;\ndag(Ramnio, [Dabort U]) = 1;\ndag(Dabort, B2) = 1;\ndag(B2, U) = 1;\n\n\n\nns = zeros(1,N);\nns(B0) = 2;\nns(B1) = 3;\nns(B2) = 4;\nns(Rtriple) = 2;\nns(Ramnio) = 3;\nns(Damnio) = 2;\nns(Dabort) = 2;\nns(U) = 1;\n\nlimid = mk_limid(dag, ns, 'chance', [B0 B1 B2], ...\n\t\t 'decision', [Damnio Dabort], 'utility', [U]);\n\n% states of nature\nhealthy = 1; downs = 2; miscarry = 3; aborted = 4;\n% test results\npos = 1; neg = 2; unk = 3;\n% actions\nyes = 1; no = 2;\n\n% Prior probability baby has downs syndrome\ntbl = zeros(2,1);\np = 1/1000; % from www.downs-syndrome.org.uk figure\np = 24/10000; % www-personal.umich.edu/~bobwolfe/560/review/Downs.pdf (for women agen 35-40)\ntbl(healthy) = 1-p;\ntbl(downs) = p;\nlimid.CPD{B0} = tabular_CPD(limid, B0, tbl);\n\n% Reliability of triple screen test\n% Unreliable sensor\n% B0 -> Rtriple\ntbl = zeros(2,2); % Rtriple = pos, neg\np = 0.5; % high false positive rate (guess)\ntbl(healthy, :) = [p 1-p];\np = 0.6; % low detection rate (march of dimes figure)\ntbl(downs, :) = [p 1-p]; \nlimid.CPD{Rtriple} = tabular_CPD(limid, Rtriple, tbl);\n\nlimid.CPD{Damnio} = tabular_decision_node(limid, Damnio);\n\n% Effect of amnio on baby B0,Damnio -> B1\n % 1/200 risk of miscarry \np = 1/200; % (march of dimes figure)\ntbl = zeros(2, 2, 3); % B1 = healthy, downs, miscarry\ntbl(healthy, no, :) = [1 0 0];\ntbl(downs, no, :) = [0 1 0];\ntbl(healthy, yes, :) = [1-p 0 p];\ntbl(downs, yes, :) = [0 1-p p];\nlimid.CPD{B1} = tabular_CPD(limid, B1, tbl);\n\n% Reliability of amnio B0, Damnio -> Ramnio\n% Perfect sensor\ntbl = zeros(2,2,3); % Ramnio = pos, neg, unk\ntbl(:, no, :) = repmat([0 0 1], 2 ,1);\ntbl(healthy, yes, :) = [0 1 0]; \ntbl(downs, yes, :) = [1 0 0]; \nlimid.CPD{Ramnio} = tabular_CPD(limid, Ramnio, tbl);\n\nlimid.CPD{Dabort} = tabular_decision_node(limid, Dabort);\n\n% Effect of abortion on baby B1, Dabort -> B2\ntbl = zeros(3, 2, 4); % B2 = healthy, downs, miscarry, aborted\ntbl(:, yes, :) = repmat([0 0 0 1], 3, 1);\ntbl(healthy, no, :) = [1 0 0 0];\ntbl(downs, no, :) = [0 1 0 0];\ntbl(miscarry, no, :) = [0 0 1 0];\nlimid.CPD{B2} = tabular_CPD(limid, B2, tbl);\n\n% Utility U(Ramnio, B2)\ntbl = zeros(3, 4);\ntbl(:, healthy) = 5000;\ntbl(:, downs) = -50000;\ntbl(:, miscarry) = -1000;\ntbl(:, aborted) = -1000;\n\nif 0\n%tbl(unk, miscarry) = 0; % this case is impossible\ntbl(pos, miscarry) = -1;\ntbl(neg, miscarry) = -1000;\nif 1\n tbl(unk, aborted) = -100;\n tbl(pos, aborted) = -1;\n tbl(neg, aborted) = -500;\nelse % pro-life utility fn\n tbl(unk, aborted) = -500000;\n tbl(pos, aborted) = -500000;\n tbl(neg, aborted) = -500000;\nend \nend\n\nlimid.CPD{U} = tabular_utility_node(limid, U, tbl);\n\n\n\nengine = jtree_limid_inf_engine(limid);\n[strategy, MEU] = solve_limid(engine);\n\n% Rtriple U(Damnio=1=yes) U(Damnio=2=no)\n% 1=pos 0 1\n% 2=neg 0 1\ndispcpt(strategy{Damnio})\nif isequal(strategy{Damnio}(1,:), strategy{Damnio}(2,:))\n % Rtriple result irrelevant\n doAmnio = argmax(strategy{Damnio}(1,:))\nelse\n doAmnio = 1;\nend\n\n% Rtriple Ramnio U(Dabort=yes=1) U(Dabort=no=2)\n% 1=pos 1=pos 1 0\n% 2=neg 1=pos 1 0\n% 1=pos 2=neg 0 1\n% 2=neg 2=neg 0 1\n% 1=pos 3=unk 0 1\n% 2=neg 3=unk 0 1\ndispcpt(strategy{Dabort})\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/limids/amnio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.636456172443711}} {"text": "% to test whether scg inference engine can handl dynameic BN\n% Make a linear dynamical system\n% X1 -> X2\n% | | \n% v v\n% Y1 Y2 \n\nintra = zeros(2);\nintra(1,2) = 1;\ninter = zeros(2);\ninter(1,1) = 1;\nn = 2;\n\nX = 2; % size of hidden state\nY = 2; % size of observable state\n\nns = [X Y];\ndnodes = [];\nonodes = [2];\neclass1 = [1 2];\neclass2 = [3 2];\nbnet = mk_dbn(intra, inter, ns, dnodes, eclass1, eclass2);\n\nx0 = rand(X,1);\nV0 = eye(X);\nC0 = rand(Y,X);\nR0 = eye(Y);\nA0 = rand(X,X);\nQ0 = eye(X);\n\nbnet.CPD{1} = gaussian_CPD(bnet, 1, 'mean', x0, 'cov', V0);\n%bnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', zeros(Y,1), 'cov', R0, 'weights', C0, 'full', 'untied', 'clamped_mean');\n%bnet.CPD{3} = gaussian_CPD(bnet, 3, 'mean', zeros(X,1), 'cov', Q0, 'weights', A0, 'full', 'untied', 'clamped_mean');\nbnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', zeros(Y,1), 'cov', R0, 'weights', C0);\nbnet.CPD{3} = gaussian_CPD(bnet, 3, 'mean', zeros(X,1), 'cov', Q0, 'weights', A0);\n\n\nT = 5; % fixed length sequences\n\nclear engine;\n%engine{1} = kalman_inf_engine(bnet, onodes);\nengine{1} = scg_unrolled_dbn_inf_engine(bnet, T, onodes);\nengine{2} = jtree_unrolled_dbn_inf_engine(bnet, T);\n\nN = length(engine);\n\n% inference\n\nev = sample_dbn(bnet, T);\nevidence = cell(n,T);\nevidence(onodes,:) = ev(onodes, :);\n\nt = 2;\nquery = [1 3];\nm = cell(1, N);\nll = zeros(1, N);\n\nengine{1} = enter_evidence(engine{1}, evidence);\n[engine{2}, ll(2)] = enter_evidence(engine{2}, evidence);\nm{1} = marginal_nodes(engine{1}, query);\nm{2} = marginal_nodes(engine{2}, query, t);\n\n\n% compare all engines to engine{1}\nfor i=2:N\n assert(approxeq(m{1}.mu, m{i}.mu));\n assert(approxeq(m{1}.Sigma, m{i}.Sigma));\n% assert(approxeq(ll(1), ll(i)));\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/dynamic/Old/scg_dbn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.636409799125227}} {"text": "function B=nancumsum(A,dim,nmode)\n% NANCUMSUM: Cumulative sum of a matrix, with user-specified treatment of NaNs.\n% Computes the cumulative sum of matrix A along dimension DIM, allowing\n% the user to replace NaNs with zeros, to skip over them, or to reset\n% on NaNs, maintaining NaNs as placeholders. \n% \n% USAGE: B = nancumsum(A, DIM, NMODE)\n%\n% ARGUMENTS:\n%\n% A: Input matrix.\n%\n% B: Output cumulative sum matrix, treating NaNs as determined by nmode.\n%\n% DIM: B = nancumsum(A, DIM) returns the nan-cumulative sum of the elements\n% along the dimension of A specified by scalar DIM. For example,\n% nancumsum(A,1) works down the columns, nancumsum(A,2) works\n% across the rows. If DIM is not specified, it defaults to the first\n% non-singleton dimension of A. \n%\n% NMODE: specifies how NaNs should be treated. Acceptable values are:\n% 1: REPLACE NaNs with zeros (default).\n% 2: MAINTAIN NaNs as position holders in B. (Skip NaNs without reset.)\n% 3: RESET sum on NaNs, replacing NaNs with zeros.\n% 4: RESET sum on NaNs, maintaining NaNs as position holders.\n%\n% EXAMPLES:\n%\n% 1) a = [NaN,2:5];\n%\n% nancumsum(a)\n% ans =\n% 0 2 5 9 14\n%\n% nancumsum(a,[],2)\n% ans =\n% NaN 2 5 9 14\n%\n% nancumsum(a,[],3)\n% ans =\n% 2 5 9 14\n%\n% 2) a = magic(3); a(5)=NaN;\n%\n% b = nancumsum(a,2) % (Default NMode = 1)\n% b =\n% 8 9 15\n% 3 3 10\n% 4 13 15\n%\n% b = nancumsum(a,2,2)\n% b =\n% 8 9 15\n% 3 NaN 10\n% 4 13 15\n%\n% b = nancumsum(a,2,3)\n% b =\n% 8 9 15\n% 3 0 7\n% 4 13 15\n%\n% b = nancumsum(a,2,4)\n% b =\n% 8 9 15\n% 3 NaN 7\n% 4 13 15\n\n% See also: cumsum, nansum, nancumprod, nanmean, nanmedian, ...\n% (nancumprod is available from the FEX. Other nan* may require Toolboxes)\n\n% Brett Shoelson\n% brett.shoelson@mathworks.com\n% 05/04/07\n%\n% Revision: 08/28/11\n% Fixed bug in option 2 (faulty reset). Thanks to Andrew Stevens and Rick\n% Patterson for reporting it. Also, eliminated old option 3 (deleting NaNs\n% in a vector) as a trivial case and added two new options. \n% Revision: 09/15/11\n% Fixed a bug with multiple NaNs. Thanks to Tim Yates.\n%\n% Copyright The MathWorks, Inc. 2011\n\n% Set defaults, check and validate inputs\nif nargin < 3\n nmode = 1;\nend\n\nif ~ismember(nmode,1:4)\n error('NANCUMSUM: unacceptable value for nmode parameter.');\nend\n\nif nargin < 2 || isempty(dim)\n if ~isscalar(A)\n dim = find(size(A)>1);\n dim = dim(1);\n else\n % For scalar inputs (no nonsingleton dimension)\n dim = 1;\n end\nend\n\n% Calculate cumulative sum, depending on selection of nmode\nswitch nmode\n case 1\n % TREAT NaNs as 0's\n B = A;\n B(B~=B) = 0;\n B = cumsum(B, dim);\n case 2\n % DO NOT INCREMENT, BUT USE NaNs AS PLACEHOLDERS.\n B = nancumsum(A, dim, 1);\n B(A~=A) = NaN;\n case 3\n % RESET sum on NaNs, replacing NaNs with zeros.\n naninds = find(A~=A);\n for ii = 1:numel(naninds)\n B = nancumsum(A, dim, 1);\n A(naninds(ii)) = -B(naninds(ii));\n end\n B = cumsum(A,dim);\n otherwise %case 4\n % RESET sum on NaNs, maintaining NaNs as position holders.\n naninds = find(A~=A);\n B = nancumsum(A,dim,3);\n B(naninds)= NaN;\nend\n \n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/14895-nancumsum/nancumsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6363555924016673}} {"text": "function linpack_d_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests DCHEX.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n lda = n;\n nz = 1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' For double precision, general storage,\\n' );\n fprintf ( 1, ' DCHEX can shift columns in a Cholesky factorization.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of equations is N = %d\\n', n );\n%\n% Set the values of the matrix A.\n%\n a(1:n,1:n) = 0.0;\n\n for i = 1 : n\n a(i,i) = 2.0;\n end\n\n for i = 1 : n-1\n a(i,i+1) = -1.0;\n end\n\n for i = 2 : n\n a(i-1,i) = -1.0;\n end\n\n for i = 1 : n\n z(i,1) = i;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The matrix A:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The vector Z:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %14f\\n', z(i) );\n end\n%\n% Decompose the matrix.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Decompose the matrix.\\n' );\n\n job = 0;\n ipvt(1:n) = 0;\n\n [ a, ipvt, info ] = dchdc ( a, lda, n, ipvt, job );\n\n if ( info ~= n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DCHDC returned INFO = %d\\n', info );\n fprintf ( 1, ' This means the matrix is not positive definite.\\n' );\n end\n%\n% Zero out the lower diagonal.\n%\n for i = 2 : n\n for j = 1 : i-1\n a(i,j) = 0.0;\n end\n end\n%\n% Print the factorization.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The Cholesky factor U:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Right circular shift columns L through K.\n%\n k = 1;\n l = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ...\n ' Right circular shift columns K = %d through L = %d\\n', k, l );\n\n job = 1;\n [ a, z, c, s ] = dchex ( a, lda, n, k, l, z, n, nz, job );\n%\n% Left circular shift columns K+1 through L.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ...\n ' Left circular shift columns K+1 = %d through L = %d\\n', k+1, l );\n\n job = 2;\n [ a, z, c, s ] = dchex ( a, lda, n, k+1, l, z, n, nz, job );\n%\n% Print the factorization.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The shifted Cholesky factor U:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The shifted vector Z:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %14f\\n', z(i) );\n end\n%\n% Compute the Cholesky product.\n%\n a(1:n,1:n) = a(1:n,1:n)' * a(1:n,1:n);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The shifted product U'' * U:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n for j = 1 : n\n fprintf ( 1, ' %14f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/linpack_d_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6363555727626746}} {"text": "% solveCoordinateDescent.m\n%\n% Implementation of the Coordinate Descent algorithm proposed in the paper.\n%\n%% I/O\n% Inputs:\n% A: m x n matrix or a function handle to a method that\n% returns A*x. \n% At: The adjoint (transpose) of 'A'. If 'A' is a function handle, 'At'\n% must be provided.\n% b0: m x 1 real,non-negative vector consists of all the measurements.\n% x0: n x 1 vector. It is the initial guess of the unknown signal x.\n% opts: A struct consists of the options for the algorithm. For details,\n% see header in solvePhaseRetrieval.m or the User Guide.\n%\n% Note: When a function handle is used, the\n% value of 'At' (a function handle for the adjoint of 'A') must be \n% supplied.\n% \n% Outputs:\n% sol: n x 1 vector. It is the estimated signal.\n% outs: A struct consists of the convergence info. For details,\n% see header in solvePhaseRetrieval.m or the User Guide.\n% \n% \n% See the script 'testCoordinateDescent.m' for an example of proper usage\n% of this function.\n%\n%% Notations\n% Notations mainly follow the paper's notation.\n%\n%% Algorithm Description\n% CD is an iterative procedure that successively minimizes the objective\n% function along coordinate directions. A single unknown is solved at each\n% iteration while all other variables are kept fixed. As a result, only\n% minimization of a univariate quartic polynomial is needed which is\n% easily achieved by finding the closed-form roots of a cubic equation.\n% \n% Specifically, the method has the following steps: It keeps running until\n% the normalized gradient becomes smaller than the tolerance (1) At each\n% iteration, use the selected rule to choose an index i. (2) Minimize the\n% objective f with respect to the ith variable while keeping\n% all other 2n-1 (both real and imaginary parts are variables so there\n% are 2n in total) variables fixed by solving the cubic equation to\n% get alpha that minimize the objective along the ith variable.\n% (3) update the estimate along the ith variable by alpha.\n% \n%% References\n% Paper Title: Coordinate Descent Algorithms for Phase Retrieval\n% Place: Chapter II.B\n% Authors: Wen-Jun Zeng, H. C. So\n% arXiv Address: https://arxiv.org/abs/1706.03474\n% \n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n\n\n\n%% -----------------------------START----------------------------------- \n \n\nfunction [sol, outs] = solveCoordinateDescent(A, At, b0, x0, opts)\n \n validateOptions(opts); % Check the validity of algorithm-specific options\n \n % Initialization\n m = length(b0);\n n = length(x0);\n sol = x0;\n Ax = A(sol);\n\n % Initialize values potentially computed at each round.\n currentTime = [];\n currentResid = [];\n currentReconError = [];\n currentMeasurementError = [];\n \n % Initialize vectors for recording convergence information\n [solveTimes,measurementErrors,reconErrors,residuals] = initializeContainers(opts);\n\n maxDiff = -inf;\n \n C = zeros(m, 3);\n \n % Used to compute gradient of objective function (used by greedy index\n % choice rule)\n f = @(z) (abs(z).^2 - b0.^2) .* z;\n \n \n startTime = tic; % Begin timer\n for iter = 1 : opts.maxIters \n switch lower(opts.indexChoice)\n case 'random'\n if opts.isComplex\n index = randi(2*n);\n else\n index = randi(n);\n end\n case 'cyclic'\n if opts.isComplex\n index = mod(iter-1, 2*n) + 1;\n else\n index = mod(iter-1, n) + 1;\n end\n case 'greedy'\n grad = At(f(A(sol)));\n \n if opts.isComplex\n grad_bar = [real(grad); imag(grad)];\n else\n grad_bar = grad;\n end\n [~, index] = max(abs(grad_bar));\n end\n \n vals = conj(A(double(1:n == mod(index-1, n)+1)'));\n for j = 1 : m \n if index > n\n C(j, 2) = 2*imag(Ax(j) * vals(j));\n else\n C(j, 2) = 2*real(Ax(j) * vals(j));\n end\n C(j, 3) = abs(vals(j))^2;\n C(j, 1) = abs(Ax(j))^2;\n end\n \n d_4 = sum(C(:, 3).^2);\n d_3 = sum(2 * C(:, 3) .* C(:, 2));\n d_2 = sum(C(:, 2).^2 + 2 * C(:, 3) .* (C(:, 1) - b0.^2));\n d_1 = sum(2 * C(:, 2) .* (C(:, 1) - b0.^2));\n \n % Desired alpha is a root of polynomial\n alphas = roots([4*d_4 3*d_3 2*d_2 d_1])';\n % Select only the real roots\n alphas = alphas(imag(alphas) == 0);\n % Function of alpha to be minimized\n g = @(x) d_4*x.^4 + d_3*x.^3 + d_2*x.^2 + d_1*x;\n % Find index of best alpha\n [~, idx] = min(g(alphas));\n alpha = alphas(idx);\n \n % Update x\n if (index > n)\n a_j = A(double(1:n == index - n)');\n sol(index - n) = sol(index - n) + 1i * alpha;\n Ax = Ax + (1i * alpha) * a_j;\n else\n a_j = A(double(1:n == index)');\n sol(index) = sol(index) + alpha;\n Ax = Ax + alpha * a_j;\n end\n \n diff = abs(alpha);\n maxDiff = max(diff, maxDiff);\n \n \n\n\n % Record convergence information and check stopping condition\n % If xt is provided, reconstruction error will be computed and used for stopping\n % condition. Otherwise, residual will be computed and used for stopping\n % condition.\n if ~isempty(opts.xt)\n x = sol;\n xt = opts.xt;\n % Compute optimal rotation\n alpha = (x(:)'*xt(:))/(x(:)'*x(:));\n x = alpha*x;\n currentReconError = norm(x-xt)/norm(xt);\n if opts.recordReconErrors\n reconErrors(iter) = currentReconError;\n end\n end\n\n if isempty(opts.xt) | opts.recordResiduals\n currentResid = diff / max(maxDiff, 1.0e-30);\n end\n\n if opts.recordResiduals\n residuals(iter) = currentResid;\n end\n \n currentTime = toc(startTime); % Record elapsed time so far\n if opts.recordTimes\n solveTimes(iter) = currentTime;\n end\n if opts.recordMeasurementErrors\n currentMeasurementError = norm(abs(A(sol)) - b0) / norm(b0);\n measurementErrors(iter) = currentMeasurementError;\n end\n \n % Display verbose output if specified\n if opts.verbose == 2\n displayVerboseOutput(iter, currentTime, currentResid, currentReconError, currentMeasurementError);\n end\n\n % Test stopping criteria. \n if stopNow(opts, currentTime, currentResid, currentReconError)\n break;\n end\n\n end\n\n % Create output according to the options chosen by user\n outs = generateOutputs(opts, iter, solveTimes, measurementErrors, reconErrors, residuals);\n\n % Display verbose output if specified\n if opts.verbose == 1\n displayVerboseOutput(iter, currentTime, currentResid, currentReconError, currentMeasurementError);\n end\nend\n\n% Validate algorithm-specific options\nfunction validateOptions(opts)\n validIndexChoices = {'cyclic', 'random', 'greedy'}; \n checkIfInList('indexChoice',opts.indexChoice,validIndexChoices);\nend\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/solvers/solveCoordinateDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6363456801488994}} {"text": "clear all;\nclose all;\nclc;\n\ndisplay('Nth (3) order Reconstruction');\nN = 3; % Nth order nonuniform sampling\nTQ = 1;Fs = 1/TQ; % Nyquist Period \n\nT = [2*TQ 3*TQ 6*TQ]; % Decimation Periods\nK = 0.5*lcm(2*T(1), 2*T(2)); K = 0.5*lcm(2*K, 2*T(3))/TQ;\ncapT = K*TQ; M = capT./T;\ncapM = lcm(M(1), M(2)); capM = lcm(capM, M(3));\nexcess = ceil((K-1)/capM);\nmaxf = K/(excess*capM+1);\nTQ1 = maxf*TQ;\nK1 = K/maxf;\n\nML = 400; % number of slices\nw_c = 0.85;\nNS = 100; % Number of Sinusoids\n\nLF = capM*2*K1*(1:10)+1; %359,159,239 % min length of LF should be capM*2*K1\n\nstd = 1e-1;\ntaus = [0 1.1+std*randn 2.2+std*randn]*TQ; \ntausI = sort([taus(1) taus(2) taus(3) T(1)+taus(1) T(2)+taus(2) 2*T(1)+taus(1)]);\n% display(tausI);\n\nFrq = rand(1,NS)*w_c/2;\nAmp = rand(1,NS)/(sqrt(NS)*2);\nPhi = rand(1,NS)*2*pi;\n\ninput = zeros(1,ML*K);\ninputN = zeros(1,ML*K1);\nfor k = 1:NS\n input = input + Amp(k)*sin(2*pi*Frq(k)*(0:ML*K-1)*TQ+Phi(k));\n inputN = inputN + Amp(k)*sin(2*pi*Frq(k)*(0:ML*K1-1)*TQ1+Phi(k));\nend;\n\ntauI = zeros(K,ML);\nfor p = 1:K\n tauI(p,:) = tausI(p)+(0:ML-1)*capT;\nend;\n\nx11 = zeros(K,ML);\nfor k = 1:NS\n x11 = x11 + Amp(k)*sin(2*pi*Frq(k)*tauI+Phi(k));\nend;\n\ntauPr = zeros(K,ML);\nfor p = 1:K\n tauPr(p,:) = -tausI(p)+(0:ML-1)*capT;\nend;\nx1p = zeros(K,ML);\nfor k = 1:NS\n x1p = x1p + Amp(k)*sin(2*pi*Frq(k)*tauPr+Phi(k));\nend;\n\ntimeP = zeros(size(LF));\ntimeE = zeros(size(LF));\ntimeI = zeros(size(LF));\ntimeV = zeros(size(LF));\ntimePr = zeros(size(LF));\ntimeJ = zeros(size(LF));\n\nMC_runs = 1;\nfor rrr = 1:length(LF)\ndisplay(rrr);\nn = -(LF(rrr)-1)/2:1:(LF(rrr)-1)/2;\n\nfor tt = 1:MC_runs\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Filterbank Reconstruction of Bandlimited Signals from Nonuniform and\n% Generalized Samples \n% Authors: Y C Eldar and A V Oppenheim\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny = zeros(N,ML*K1);\nfor p = 1:N\n tau = taus(p)+(0:ML*M(p)-1)*T(p);\n x1 = zeros(1,ML*M(p));\n for k = 1:NS\n x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tau+Phi(k));\n end;\n LFE = M(p)*84*rrr+1; % length of LF should be Multiple of LCM{M(p)}*2*K\n nE = -(LFE-1)/2:1:(LFE-1)/2;\n \n tic\n y1 = upsample(x1,K1);\n h = sinc((nE/K1)-(taus(p)/T(p))).*kaiser_mine1(LFE,18,-K1*(taus(p)/T(p)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 1 %%%%%%%%%%%%%%%%%%%%%%%%%%% \n% G = M(setdiff((1:N),p));\n% F = taus(setdiff((1:N),p));\n% temp1 = G(1)-G(2);\n% temp2 = G(1)+G(2);\n% bb = zeros(2*(K-M(p))+1,M(p));\n% if temp1~=0\n% for l = 0:M(p)-1\n% c = 0.5*cos(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n% s = -0.5*sin(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n% bb(1+temp2-temp1,l+1) = 0.5*(c+1i*s);\n% bb(1+temp2+temp1,l+1) = conj(bb(1+temp2-temp1,l+1));\n% end;\n% else\n% bb(1+temp2,1:M(p)) = 0.5*cos(pi*G(1)*(F(2)-F(1))/capT);\n% end;\n% for l = 0:M(p)-1\n% c = -0.5*cos(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n% s = 0.5*sin(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n% bb(1+temp2-temp2,l+1) = 0.5*(c+1i*s);\n% bb(1+temp2+temp2,l+1) = conj(bb(1+temp2-temp2,l+1));\n% end;\n% aaa = ones(1,M(p));\n% bbvl = zeros(M(p),LFE);\n% for l = 1:M(p)\n% for q = 1:N\n% if q ~= p\n% aaa(l) = aaa(l)*sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n% end;\n% end;\n% bbv = zeros(2*(K-M(p))+1,LFE);\n% for v = -(K-M(p)):K-M(p)\n% bbv(K-M(p)+1+v,:) = bb(K-M(p)+1+v,l)*exp(1i*(pi/(K1*M(p)))*v*nE);\n% end;\n% bbvl(l,:) = sum(bbv,1)/aaa(l);\n% end;\n% bbb = zeros(M(p),LFE);\n% bbn = zeros(M(p),LFE);\n% for m = 1:M(p)\n% for l = 1:M(p)\n% bbb(l,:) = bbvl(l,:)*exp(1i*(2*pi/M(p))*(m-1)*(l-1));\n% end\n% bbb = sum(bbb,1);\n% bbn(m,:) = bbb.*exp(1i*(2*pi/M(p))*(m-1)*nE);\n% end;\n% bbn = sum(bbn,1);\n% bbn = bbn.*h/M(p);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%\n% G = M(setdiff((1:N),p));\n% F = taus(setdiff((1:N),p));\n% temp1 = G(1)-G(2);\n% temp2 = G(1)+G(2);\n% bb = zeros(2*(K-M(p))+1,M(p));\n% if temp1~=0\n% for l = 0:M(p)-1\n% c = 0.5*cos(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n% s = -0.5*sin(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n% bb(1+temp2-temp1,l+1) = 0.5*(c+1i*s);\n% bb(1+temp2+temp1,l+1) = conj(bb(1+temp2-temp1,l+1));\n% end;\n% else\n% bb(1+temp2,1:M(p)) = 0.5*cos(pi*G(1)*(F(2)-F(1))/capT);\n% end;\n% for l = 0:M(p)-1\n% c = -0.5*cos(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n% s = 0.5*sin(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n% bb(1+temp2-temp2,l+1) = 0.5*(c+1i*s);\n% bb(1+temp2+temp2,l+1) = conj(bb(1+temp2-temp2,l+1));\n% end;\n% aaa = ones(1,M(p));\n% for l = 1:M(p)\n% for q = 1:N\n% if q ~= p\n% aaa(l) = aaa(l)/sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n% end;\n% end;\n% end;\n% AE = diag(aaa);\n% BE = bb.';\n% \n% dim = K-M(p); w = -dim:1:dim;\n% FE = exp(1i*(pi/(K1*M(p))).*kron(nE,w'));\n% \n% E1E = exp(1i*(2*pi/M(p)).*kron((0:M(p)-1),(0:M(p)-1)'))/M(p);\n% \n% E2E = exp(1i*(2*pi/M(p)).*kron(nE,(0:M(p)-1)'));\n% \n% temp = E1E*AE*BE*FE;\n% bbn = h.*sum(E2E.*temp,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Implementation 3 %%%%%%%%%%%%%%%%%%%%%%%%%%%\n aaa = ones(1,M(p));\n bb = ones(M(p),LFE);\n for l = 1:M(p)\n for q = 1:N\n if q ~= p\n aaa(l) = aaa(l)*sin(pi*(taus(p)-taus(q)+(l-1)*T(p))/T(q));\n bb(l,:) = bb(l,:).*sin(pi*((nE*TQ1/M(p))-taus(q)+(l-1)*T(p))/T(q));\n end;\n end;\n bb(l,:) = bb(l,:)/aaa(l);\n end;\n\n bbb = zeros(M(p),LFE);\n bbn = zeros(M(p),LFE);\n for m = 1:M(p)\n for l = 1:M(p)\n bbb(l,:) = bb(l,:)*exp(1i*(2*pi/M(p))*(m-1)*(l-1));\n end\n bbb = sum(bbb,1);\n bbn(m,:) = bbb.*exp(1i*(2*pi/M(p))*(m-1)*nE);\n end;\n bbn = sum(bbn,1);\n bbn = bbn.*h/M(p);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n y1 = conv(y1,bbn);\n delay = (length(h)-1)/2;\n y(p,:) = y1(1+delay:M(p):end-delay);\n timeE(rrr) = timeE(rrr)+toc;\nend;\ny = real(sum(y,1));\nx = inputN;\n% y = y(160:end);\n% x = x(160:end);\nserE = 20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A realization of Digital Filter Banks for Reconstruction of Uniformly\n% sampled signals from nonuniform samples\n% Authors: Itami, Watanabe, Nishihara\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntic\na = zeros(1,K);\nfor p = 1:K\n a(p) = 1;\n for q = 1:K\n if q ~= p\n a(p) = a(p)/sin(pi*(tausI(p)-tausI(q))/capT);\n end;\n end;\nend;\n% c = sin(pi*(tausI(0+1))/capT);\n% s = cos(pi*(tausI(0+1))/capT);\n% b(1,1) = 0.5*(c+1i*s);\n% c = sin(pi*(tausI(1+1))/capT);\n% s = cos(pi*(tausI(1+1))/capT);\n% b(1,2) = 0.5*(c+1i*s);\n% b(3,:) = conj(b(1,:));\n% b(2,:) = 0;\n\nb = zeros(2*K-1,K);\nc = 0.25*(sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.25*(cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(5,1) = 0.5*(c+1i*s);\n\nc = 0.25*(sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.25*(cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(5,2) = 0.5*(c+1i*s);\n\nc = 0.25*(sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.25*(cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(5,3) = 0.5*(c+1i*s);\n\nc = 0.25*(sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\ns = 0.25*(cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\nb(5,4) = 0.5*(c+1i*s);\n\nc = 0.25*(sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\ns = 0.25*(cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\nb(5,5) = 0.5*(c+1i*s);\n\nc = 0.25*(sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.25*(cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(5,6) = 0.5*(c+1i*s);\nb(7,:) = conj(b(5,:));\n\nc = 0.125*(-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(3,1) = 0.5*(c+1i*s);\n\nc = 0.125*(-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(3,2) = 0.5*(c+1i*s);\n\nc = 0.125*(-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(3,3) = 0.5*(c+1i*s);\n\nc = 0.125*(-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(0+1))/capT)-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\nb(3,4) = 0.5*(c+1i*s);\n\nc = 0.125*(-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)+cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)-tausI(3+1))/capT)-cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)-sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)+0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\nb(3,5) = 0.5*(c+1i*s);\n\nc = 0.125*(-sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)+cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(-cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(4+1)-tausI(3+1))/capT)-cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(2+1)-tausI(1+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)+0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(3,6) = 0.5*(c+1i*s);\nb(9,:) = conj(b(3,:));\n\nc = 0.125*(0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(1,1) = 0.5*(c+1i*s);\n\nc = 0.125*(0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(0+1)+tausI(2+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(1,2) = 0.5*(c+1i*s);\n\nc = 0.125*(0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(1,3) = 0.5*(c+1i*s);\n\nc = 0.125*(0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(0+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(0+1)+tausI(4+1))/capT));\nb(1,4) = 0.5*(c+1i*s);\n\nc = 0.125*(0.5*sin(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(5+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(0+1))/capT)+0.5*sin(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*cos(pi*(-tausI(5+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(0+1))/capT));\nb(1,5) = 0.5*(c+1i*s);\n\nc = 0.125*(0.5*sin(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\ns = 0.125*(0.5*cos(pi*(-tausI(0+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*cos(pi*(tausI(3+1)+tausI(4+1))/capT)+0.5*sin(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT)*cos(pi*(tausI(1+1)+tausI(2+1))/capT)-0.5*cos(pi*(-tausI(0+1))/capT)*sin(pi*(tausI(1+1)+tausI(2+1))/capT)*sin(pi*(tausI(3+1)+tausI(4+1))/capT));\nb(1,6) = 0.5*(c+1i*s);\nb(11,:) = conj(b(1,:));\nb = -b;\n\ny1=upsample(x11.',K1).';\n\nk = -(K-1):1:(K-1);\nm = (0:1:(2*K1-1))';\nF = exp(1i*(pi/K1).*kron(m,k));\n\ny = zeros(K,size(y1,2));\nfor r = 1:K\n tempI = a(r)*y1(r,:);\n% tempI2 = F*b(:,r)*a(r);\n tempI2 = F*b(:,r);\n% y2 = tempI2*y1(r,:);\n y2 = tempI2*tempI;\n% y2 = F*b(:,r)*a(r)*y1(r,:);\n h = sinc((n/K1)-tausI(r)/capT).*kaiser_mine1(LF(rrr),18,-tausI(r)/TQ1);\n for i=1:2*K1\n h1 = upsample(downsample(h,2*K1,i-1),2*K1);\n% y2(i,:) = filter(h1,1,y2(i,:));\n% y2(i,:) = filter([zeros(1,i-1),1],1,y2(i,:));%,zeros(1,2*K-i)\n temp = filter([zeros(1,i-1),1],1,h1);\n y2(i,:) = filter(temp,1,y2(i,:));\n end;\n y(r,:) = sum(y2,1);\nend;\ny = -real(sum(y,1));\ntimeI(rrr) = timeI(rrr)+toc;\ndelayI = (LF(rrr)-1)/2;\nx=inputN(1:end-delayI);\ny=y(1+delayI:end);\n% y = y(160:end);\n% x = x(160:end);\nserI = 20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Nonuniformly Sampled Band-Limited Signals\n% Using a Differentiator-Multiplier Cascade\n% Authors: Stefan Tertinek and Christian Vogel\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nr = tausI-TQ*(0:K-1);\nrr = r(mod((0:ML*K-1),K)+1);\nx1 = reshape(x11,1,K*size(x11,2));\n% x1 = x11;% LF = (0:11); Fs = 1;\n% Differentiator Design\n% figure();\n% NFFT = 2^nextpow2(length(Hd)); % Next power of 2 from length of Hd\n% HD = fftshift(fft(Hd,NFFT))/length(Hd);\n% f = Fs*linspace(-1,1,NFFT);\n% % Plot double-sided amplitude spectrum.\n% plot(f,2*abs(HD(1:NFFT))) \n% title('Double-Sided Amplitude Spectrum of Hd(n)')\n% xlabel('Frequency (Hz)')\n% ylabel('|HD(f)|')\ntic\nHd = firpm(LF(rrr)-1,[0 w_c],[0 w_c*pi],'differentiator');\ndelayV = (LF(rrr)-1)/2;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny1 = filter(Hd,1,x1);\nx1 = filter([zeros(1,delayV),1],1,x1);\nr2 = filter([zeros(1,delayV),1],1,rr);\ne = y1.*r2;\ny1 = x1-e;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny2 = filter(Hd,1,y1);\ntemp = filter([zeros(1,delayV),1],1,y2);\nx1 = filter([zeros(1,2*delayV),1],1,x1);\nr2 = filter([zeros(1,2*delayV),1],1,r2);\ne1 = temp.*r2;\ny2 = filter(Hd,1,y2);\ne2 = 0.5*y2.*r2.^2;\ny2 = x1-e1-e2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny3 = filter(Hd,1,y2);\ntemp = filter([zeros(1,2*delayV),1],1,y3);\nx1 = filter([zeros(1,3*delayV),1],1,x1);\nr2 = filter([zeros(1,3*delayV),1],1,r2);\ne1 = temp.*r2;\ny3 = filter(Hd,1,y3);\ntemp = filter([zeros(1,delayV),1],1,y3);\ne2 = 0.5*temp.*r2.^2;\ny3 = filter(Hd,1,y3);\ne3 = (y3.*r2.^3)/6;\ny3 = x1-e1-e2-e3;\ntimeV(rrr) = timeV(rrr)+toc;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ny = real(y3(1+6*delayV:end));\nx = input(1:end-6*delayV);\n% y = y(160:end);\n% x = x(160:end);\nserV = 20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Band-Limited Periodic Nonuniformly Sampled Signals \n% Through Multirate Filter Banks\n% Ryan S Prendergast, Bernard C Levy, Paul J Hurst\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntic\nH = zeros(K,LF(rrr));\nfor i=1:K\n% H(i,:) = sinc(n-tausI(i)).*conv(sinc(n-tausI(i)),kaiser(LF,10).','same');\n H(i,:) = sinc(n-tausI(i)).*kaiser_mine1(LF(rrr),18,-tausI(i));\nend;\nH = H(:,1:end-1);\nEP = reshape(H.',K,length(H(1,:))/K,K);\ncapE = [];\nfor k=1:K\n temp = [];\n for i=1:K\n temp=[temp,toeplitz([EP(i,1,k),zeros(1,(length(H(1,:))/K)-1)],[EP(i,:,k),zeros(1,(length(H(1,:))/K)-1)])];\n end\n capE = [capE;temp];\nend\nd = ceil(size(capE,2)/(2*K));\nP = kron(eye(K),[zeros(1,d),1,zeros(1,(size(capE,2)/K)-d-1)]);\nR = P/capE;\n% size(capE) \n% size(zeros(LF-1,2*LF-2-K))\n% size(R)\n% size(zeros(K,LF-1))\n% size(P)\n% size(zeros(K,2*LF-2-K))\nR = upsample(R.',K).';\nrt = size(R,2)/K;\nFR = zeros(K,rt);\nfor j=1:K\n for i=1:K\n temp = filter([zeros(1,K-i),1],1,R(i,(j-1)*rt+1:j*rt));\n FR(j,:) = FR(j,:)+temp;\n end\nend\nyb = upsample(x1p.',K).';\nfor i = 1:K\n yb(i,:) = filter(FR(i,:),1,yb(i,:));\nend;\ny = sum(yb,1);\ntimePr(rrr) = timePr(rrr)+toc;\ndelayPr = (size(FR,2))/2+K-1;\nx=input(1:end-delayPr);\ny=y(1+delayPr:end);\n% y = y(160:end);\n% x = x(160:end);\nserPr = 20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of Periodically Nonuniformly Sampled Bandlimited Signals\n% Using Time-Varying FIR Filters\n% Authors: H. Johansson and Per Lowenborg\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nr = r.';\nx1 = reshape(x11,1,size(x11,2)*K);\ntic\nw_o = w_c*pi*TQ;\nhJ = zeros(K,LF(rrr));\nC = zeros(1,LF(rrr));\nNt = (LF(rrr)-1)/2;\nfor i = 1:K\n C = -2*sin(w_o*(n-r(1+(mod(i-1-n,K)))'))./(pi*(n-r(1+(mod(i-1-n,K)))'));\n C(isnan(C)==1)=-2*w_o/pi;\n C = C.';\n S = zeros(LF(rrr),LF(rrr));\n for k = 1:LF(rrr)\n S(k,:) = sin(w_o*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')))./(pi*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')));\n end;\n S(isnan(S)==1)=w_o/pi;\n hJ(i,:) = -0.5*S\\C;\nend;\n\ny1 = zeros(K,length(x1));\nfor j=1:K\n y1(j,:) = filter(hJ(j,:),1,x1);\n y1(j,:) = upsample(downsample(y1(j,:),K,j-1),K)/K;\n y1(j,:) = filter([zeros(1,j-1),1],1,y1(j,:));\nend;\ny = K*0.25*sum(y1,1);\ntimeJ(rrr) = timeJ(rrr)+toc;\ndelayJ = (size(hJ,2)-1)/2;\ny = real(y(1+delayJ:end));\nx = input(1:end-delayJ);\n% y = y(160:end);\n% x = x(160:end);\nserJ = 20*log10(norm(x,2)/norm(y-x,2));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Reconstruction of N-th order nonuniformly sampled bandlimited signals\n% using digital filter banks\n% Authors: S. K. Sindhi, K. M. M. Prabhu\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nxp = zeros(N,ML*K1);\nfor p = 1:N\n tau = taus(p)+(0:ML*M(p)-1)*T(p);\n x1 = zeros(1,ML*M(p));\n for k = 1:NS\n x1 = x1 + Amp(k)*sin(2*pi*Frq(k)*tau+Phi(k));\n end;\n tic\n m = (0:1:M(p)-1)'; lemda = 0:1:M(p)-1;\n W = exp(1i*(2*pi/M(p)).*kron(m,lemda)); % m*lemda\n \n aaa = ones(1,M(p));\n for l = 1:M(p)\n for q = 1:N\n if q ~= p\n aaa(l) = aaa(l)/(sin(pi*M(q)*(taus(p)-taus(q)+(l-1)*T(p))/capT));\n end;\n end;\n end;\n A = diag(aaa); %display(A);\n \n G = M(setdiff((1:N),p));\n F = taus(setdiff((1:N),p));\n temp1 = G(1)-G(2);\n temp2 = G(1)+G(2);\n bb = zeros(2*(K-M(p))+1,M(p));\n if temp1~=0\n for l = 0:M(p)-1\n c = 0.5*cos(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n s = -0.5*sin(pi*(l*T(p)*temp1+G(2)*F(2)-G(1)*F(1))/capT);\n bb(1+temp2-temp1,l+1) = 0.5*(c+1i*s);\n bb(1+temp2+temp1,l+1) = conj(bb(1+temp2-temp1,l+1));\n end;\n else\n bb(1+temp2,1:M(p)) = 0.5*cos(pi*G(1)*(F(2)-F(1))/capT);\n end;\n for l = 0:M(p)-1\n c = -0.5*cos(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n s = 0.5*sin(pi*(l*T(p)*temp2-G(2)*F(2)-G(1)*F(1))/capT);\n bb(1+temp2-temp2,l+1) = 0.5*(c+1i*s);\n bb(1+temp2+temp2,l+1) = conj(bb(1+temp2-temp2,l+1));\n end;\n B = bb;% display(B);\n \n y1 = upsample(x1,K1);\n y1 = reshape(y1,M(p),length(y1)/M(p));\n \n if M(p)>1\n y1(2:end,:) = flipud(y1(2:end,:));\n for i = 1:M(p)-1\n y1(i+1,:) = filter([0,1],1,y1(i+1,:));\n end;\n end;\n \n dim = K-M(p); w = -dim:1:dim;\n \n xlemda = zeros(M(p),size(y1,2));\n for lemda = 0:M(p)-1\n \n rP = (lemda/M(p))+(0:1:(2*K1-1))';\n Fshift = exp(1i*(pi/K1).*kron(rP,w)); % r*w\n mtemp = A*W;\n mtemp = B*mtemp;\n mtemp = Fshift*mtemp;\n Htemp = mtemp*W(:,lemda+1);\n \n h = sinc((n*TQ1/T(p))+(lemda/K1)-(taus(p)/T(p))).*kaiser_mine1(LF(rrr),18,(lemda/M(p))-(taus(p)/TQ1));\n h1 = zeros(2*K1, length(h)+2*K1-1);\n for i = 2:2*K1\n h1(i,:) = [filter([zeros(1,i-1),1],1,upsample(downsample(h,2*K1,i-1),2*K1)) zeros(1,2*K1)]*Htemp(i);\n end;\n h1(1,:) = upsample(downsample(h,2*K1),2*K1)*Htemp(1);\n h1 = sum(h1,1);\n xlemda(lemda+1,:) = filter(h1,1,y1(lemda+1,:));\n end;\n xp(p,:) = sum(xlemda,1)/M(p);\n timeP(rrr) = timeP(rrr)+toc;\nend;\ny = sum(xp,1);\ndelayP = (length(h)-1)/2;\ny = y(1+delayP:end);\nx = inputN(1:end-delayP);\n% y = y(160:end);\n% x = x(160:end);\nserP = 20*log10(norm(x,2)/norm(y-x,2));\nend;\nend;\ntimeP = timeP/MC_runs;\ntimeE = timeE/MC_runs;\ntimeI = timeI/MC_runs;\ntimeV = timeV/MC_runs;\ntimePr = timePr/MC_runs;\ntimeJ = timeJ/MC_runs;\n\nfigure();hold on;\nplot(LF,timeJ,'kp-','LineWidth',2);\nplot(LF,timePr,'ko-','LineWidth',2);\nplot(LF,timeV,'ks-','LineWidth',2);\nplot(LF,timeP,'kd-','LineWidth',2);\nplot(LF,timeI,'k>-','LineWidth',2);\nplot(LF,timeE,'k+-','LineWidth',2);\nlegend('Johansson','Prendergast','Tertinek','Proposed','Itami','Eldar');\nxlabel('Filter length','fontsize',14,'fontweight','b');\nylabel('Time in seconds','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')\n\n% temp = (LF.^3);%+(K*LF*ML*K);\n% temp = temp/max(temp);\n% timePrI = timePr(rrr)*temp;\n% \n% temp = (LF.^3);%+(K*(LF+1)*ML*K);\n% temp = temp/max(temp);\n% timeJI = timeJ(rrr)*temp;\n% \n% temp = (LF.^2);%+(6*LF*ML*K);\n% temp = temp/max(temp);\n% timeVI = timeV(rrr)*temp;\n% plot(LF,timePrI,'k--','LineWidth',2);\n% plot(LF,timeJI,'k--','LineWidth',2);\n% plot(LF,timeVI,'k--','LineWidth',2);\n\nfigure();hold on;\nplot(LF,timeJ,'kp-','LineWidth',2);\ntemp = (LF.^3);%+(K*(LF+1)*ML*K);\ntemp = temp/max(temp);\ntimeJI = timeJ(rrr)*temp;\nplot(LF,timeJI,'k--','LineWidth',2);\nlegend('Johansson','Ideal curve');\nxlabel('Filter length','fontsize',14,'fontweight','b');\nylabel('Time in seconds','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')\n\nfigure();hold on;\nplot(LF,timePr,'ko-','LineWidth',2);\ntemp = (LF.^3);%+(K*LF*ML*K);\ntemp = temp/max(temp);\ntimePrI = timePr(rrr)*temp;\nplot(LF,timePrI,'k--','LineWidth',2);\nlegend('Prendergast','Ideal curve');\nxlabel('Filter length','fontsize',14,'fontweight','b');\nylabel('Time in seconds','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')\n\nfigure();hold on;\nplot(LF,timeV,'ks-','LineWidth',2);\ntemp = (LF.^2);%+(6*LF*ML*K);\ntemp = temp/max(temp);\ntimeVI = timeV(rrr)*temp;\nplot(LF,timeVI,'k--','LineWidth',2);\nlegend('Tertinek','Ideal curve');\nxlabel('Filter length','fontsize',14,'fontweight','b');\nylabel('Time in seconds','fontsize',14,'fontweight','b');\ngrid on;box on;\nset(gca,'fontsize',14,'fontweight','b')\n\ndisplay(serI)\ndisplay(serV)\ndisplay(serPr)\ndisplay(serJ)\ndisplay(serP)\ndisplay(serE)\n\n% LF = 84*(1:30)+1; % length of LF should be Multiple of LCM{M(p)}*2*K\n% timeJ = [timeJ,zeros(1,length(1:length(LF)-10))];\n% for rrr = 11:length(LF)\n% display(rrr);\n% n = -(LF(rrr)-1)/2:1:(LF(rrr)-1)/2;\n% for tt = 1:MC_runs\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % Reconstruction of Periodically Nonuniformly Sampled Bandlimited Signals\n% % Using Time-Varying FIR Filters\n% % Authors: H. Johansson and Per Lowenborg\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% r = tausI-TQ*(0:K-1);\n% r = r.';\n% x1 = reshape(x11,1,size(x11,2)*K);\n% tic\n% w_o = w_c*pi*TQ;\n% hJ = zeros(K,LF(rrr));\n% C = zeros(1,LF(rrr));\n% Nt = (LF(rrr)-1)/2;\n% for i = 1:K\n% C = -2*sin(w_o*(n-r(1+(mod(i-1-n,K)))'))./(pi*(n-r(1+(mod(i-1-n,K)))'));\n% C(isnan(C)==1)=-2*w_o/pi;\n% C = C.';\n% S = zeros(LF(rrr),LF(rrr));\n% for k = 1:LF(rrr)\n% S(k,:) = sin(w_o*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')))./(pi*(-Nt+k-1-r(1+(mod(i-1-(-Nt+k-1),K)))-(n-r(1+(mod(i-1-n,K)))')));\n% end;\n% S(isnan(S)==1)=w_o/pi;\n% hJ(i,:) = -0.5*S\\C;\n% end;\n% \n% y1 = zeros(K,length(x1));\n% for j=1:K\n% y1(j,:) = filter(hJ(j,:),1,x1);\n% y1(j,:) = upsample(downsample(y1(j,:),K,j-1),K)/K;\n% y1(j,:) = filter([zeros(1,j-1),1],1,y1(j,:));\n% end;\n% y = K*0.25*sum(y1,1);\n% timeJ(rrr) = timeJ(rrr)+toc;\n% delayJ = (size(hJ,2)-1)/2;\n% y = real(y(1+delayJ:end));\n% x = input(1:end-delayJ);\n% % y = y(160:end);\n% % x = x(160:end);\n% serJ = 20*log10(norm(x,2)/norm(y-x,2));\n% end;\n% end;\n% timeJ(11:length(LF)) = timeJ(11:length(LF))/MC_runs;\n% figure();hold on;\n% plot(LF,timeJ,'kp-','LineWidth',2);\n% temp = (LF.^3);%+(K*(LF+1)*ML*K);\n% temp = temp/max(temp);\n% timeJI = timeJ(rrr)*temp;\n% plot(LF,timeJI,'k--','LineWidth',2);\n% legend('Johansson','Prendergast','Tertinek','Proposed','Itami','Eldar');\n% xlabel('Filter length','fontsize',14,'fontweight','b');\n% ylabel('Time in seconds','fontsize',14,'fontweight','b');\n% grid on;box on;\n% set(gca,'fontsize',14,'fontweight','b')\n\n% figure();\n% subplot(2,1,1);\n% plot(([x' y']));\n% title('input / output signals');\n% xlabel('sample');\n% ylabel('signal value');\n% grid on;\n% subplot(2,1,2);\n% plot((x'-y'));\n% xlabel('time (sample)');\n% ylabel('error value');\n% grid on;", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/SindhiPrabhu/Time_N3_LF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6363456725847159}} {"text": "% VL_FISHER Fisher vector feature encoding\n% ENC = VL_FISHER(X, MEANS, COVARIANCES, PRIORS) computes the Fisher\n% vector encoding of the vectors X relative to the Gaussian mixture\n% model with means MEANS, covariances COVARIANCES, and prior mode\n% probabilities PRIORS.\n%\n% X has one column per data vector (e.g. a SIFT descriptor), and\n% MEANS and COVARIANCES one column per GMM component (covariance\n% matrices are assumed diagonal, hence these are simply the variance\n% of each data dimension). PRIORS has size equal to the number of\n% GMM components. All data must be of the same class, either SINGLE\n% or DOUBLE.\n%\n% ENC is a vector of the same class of X of size equal to the\n% product of the data dimension and the number of components.\n%\n% By default, the standard Fisher vector is computed. VL_FISHER()\n% accepts the following options:\n%\n% Normalized::\n% If specified, L2 normalize the Fisher vector.\n%\n% SquareRoot::\n% If specified, the signed square root function is applied to\n% ENC before normalization.\n%\n% Improved::\n% If specified, compute the improved variant of the Fisher\n% Vector. This is equivalent to specifying the Normalized and\n% SquareRoot options.\n%\n% Fast::\n% If specified, uses slightly less accurate computations but\n% significantly increase the speed in some cases (particularly\n% with a large number of Gaussian modes).\n%\n% Verbose::\n% Increase the verbosity level (may be specified multiple times).\n%\n% See: Fisher vectors, VL_HELP().\n\n% Authors: David Novotny, Andrea Vedaldi\n\n% Copyright (C) 2013 David Novotny and Andrea Vedaldi\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n", "meta": {"author": "yihui-he", "repo": "panorama", "sha": "0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b", "save_path": "github-repos/MATLAB/yihui-he-panorama", "path": "github-repos/MATLAB/yihui-he-panorama/panorama-0c993d4ba6780dcb175b2c1fc7d25b513b7bb39b/lib/vlfeat-0.9.20/toolbox/fisher/vl_fisher.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.636345669476816}} {"text": "function Gxy = ffmGreenKernel(X,Y,green,k)\n%+========================================================================+\n%| |\n%| OPENFFM - LIBRARY FOR FAST AND FREE MEMORY CONVOLUTION |\n%| openFfm is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : ffmGreenKernel.m |\n%| # | VERSION : 0.6 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Green kernel computation using string |\n%| `---' | definition |\n%+========================================================================+\n\n% Security\nif (size(X,2) ~= 3) || (size(Y,2) ~= 3)\n error('ffmGreenKernel.m : unavailable case')\nend\nif isempty(k)\n k = 0;\nend\n\n% Distances between particles\nRxy = sqrt( ...\n (X(:,1) - Y(:,1)).^2 + ...\n (X(:,2) - Y(:,2)).^2 + ...\n (X(:,3) - Y(:,3)).^2 );\n\n% For empty wave-number\nif isempty(k)\n k = 0;\nend\n\n% Green kernel definition\nif strcmp(green,'[1/r]')\n Gxy = 1./Rxy; \n \nelseif strcmp(green,'[exp(ikr)/r]')\n Gxy = exp(1i*k*Rxy)./Rxy; \n\nelseif strcmp(green(1:end-1),'gradx[1/r]') \n j = str2double(green(end));\n Gxy = - (X(:,j)-Y(:,j)) ./ (Rxy.^3);\n \nelseif strcmp(green(1:end-1),'grady[1/r]') \n j = str2double(green(end));\n Gxy = (X(:,j)-Y(:,j)) ./ (Rxy.^3); \n \nelseif strcmp(green(1:end-1),'gradx[exp(ikr)/r]') \n j = str2double(green(end));\n Gxy = (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) .* ...\n (X(:,j)-Y(:,j)) ./ (Rxy.^2);\n \nelseif strcmp(green(1:end-1),'grady[exp(ikr)/r]') \n j = str2double(green(end));\n Gxy = - (1i*k - 1./Rxy) .* exp(1i*k.*Rxy) .* ...\n (X(:,j)-Y(:,j)) ./ (Rxy.^2);\n \nelseif strcmp(green(1:end-2),'[ij/r+rirj/r^3]') \n i = str2double(green(end-1));\n j = str2double(green(end));\n Gxy = (i==j)./Rxy + (X(:,i)-Y(:,i)).*(X(:,j)-Y(:,j))./(Rxy.^3);\n \nelseif strcmp(green(1:end-3),'[rirjrk/r^5]') \n i = str2double(green(end-2));\n j = str2double(green(end-1));\n k = str2double(green(end)); \n Gxy = (X(:,i)-Y(:,i)).*(X(:,j)-Y(:,j)).*(X(:,k)-Y(:,k))./(Rxy.^5);\n \nelse\n error('Error in ffmGreenKernel.m : unknown green kernel')\nend\n\n% Singularity\nif strcmp(green,'[exp(ikr)/r]')\n Gxy(Rxy<1e-8) = 0 + 1i*k;\nelse\n Gxy(Rxy<1e-8) = 0;\nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openFfm/ffmGreenKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6363067628717877}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox \n% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and \n% Intensity-Preserving Diffeomorphic Image Registration\n% \n% For details and license info see \n% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM\n%\n% function [Jc,para,dJ,H] = LDDMMobjFctn(T,Rc,omega,m,beta,M,wRef,xc,vc)\n%\n% Objective Function for LDDMM using Lagrangian PDE solver\n%\n% computes J(vc) = D(T(yc(vc)),Rc) + S(vc - vRef), where\n%\n% vc - is a velocity field (stationary or instationary)\n% yc(vc) = trafo(wc,xc) is obtained by tracing characteristics using RK4\n% scheme\n% Tc = T(yc) = imgModel(T,omega,yc),\n% D(Tc,Rc) = distance(Tc,Rc,omega,m)\n% S = regularizer, e.g., S(uc) = 0.5*uc'*B*uc\n% vRef = reference guess for velocities\n%\n% For more details see the paper:\n%\n% @article{MangRuthotto2017,\n% Title = {A {L}agrangian {G}auss--{N}ewton--{K}rylov solver for mass- and intensity-preserving diffeomorphic image registration},\n% Year = {2017},\n% Journal = {SIAM Journal on Scientific Computing},\n% Author = {A. Mang, L. Ruthotto},\n% }\n%\n% Input:\n% T - data for template image, Tc = imgModel(T,omega,yc)\n% Rc - reference image on grid, Rc = imgModel(R,omega,xc)\n% omega - representation of computational domain\n% m - discretization size\n% vRef - reference velocity\n% xc - discretization of Omega\n% omegaV - computational domain for velocity field (can be larger)\n% mV - discretization size for velocities\n% N - number of time steps for RK4 scheme\n% vc - current velocities\n%\n% Output:\n% Jc - current function value J(vc)\n% para - struct {Tc=T(y(vc)), Rc, omega, m, yc=y(vc,xc), Jc}, for plots\n% dJ - gradient of J\n% H - approximation to Hessian of J\n%\n% see also ELDDMM_Hand2D\n%==============================================================================\nfunction [Jc,para,dJ,H] = LDDMMobjFctn(T,Rc,omega,m,vRef,xc,omegaV,mV,N,vc)\n\npara = struct([]);\nif nargin == 0,\n help(mfilename);\n runMinimalExample;\n return;\nelseif ~exist('vc','var') || isempty(vc),\n % if wc is not an input argument, reports status\n if nargout == 1, Jc = 'LDDMM'; return; end;\n % report current settings\n dimstr = @(m) sprintf('[%s]',sprintf(' %d',m));\n vc = trafo('w0');\n nt = regularizer('get','nt');\n fprintf('Large Deformation Diffeomorphic Mapping (LDDMM):\\n');\n fprintf(' J(vc) = D(T(yc(vc)),Rc) + S(vc-vRef) != min\\n');\n fprintf(' %20s : %s\\n','m',dimstr(m));\n fprintf(' %20s : %s\\n','omega',dimstr(omega));\n fprintf(' %20s : %s\\n','IMAGE MODEL',imgModel);\n fprintf(' %20s : %s\\n','DISTANCE',distance);\n fprintf(' %20s : %s\\n','TRAFO',trafo);\n fprintf(' %20s : %s\\n','#timeSteps',num2str(N));\n fprintf(' %20s : %s\\n','nt',num2str(nt));\n fprintf(' %20s : %s\\n','mV',dimstr(mV));\n fprintf(' %20s : %s\\n','omegaV',dimstr(omegaV));\n fprintf(' %20s : %s\\n','length(vc)',num2str(length(vc)));\n Jc = vc; % return starting guess\n return;\nend;\ntspan = [1 0];\ndim = numel(omega)/2;\nnt = round(numel(vc)/(dim*prod(m)))-1;\n\n% do the work ------------------------------------------------------------\nmatrixFree = regularizer('get','matrixFree');\ndoDerivative = (nargout>2); % flag for necessity of derivatives\n\n% compute transformation, distance, and regularization and combine these\nif nt<1\n [yc,dy,pTrafo] = getTrafoFromVelocityRK4(vc,xc,'omega',omegaV,'m',mV,'N',N,'tspan',tspan,'doDerivative',doDerivative);\nelse\n [yc,dy,pTrafo] = getTrafoFromInstationaryVelocityRK4(vc,xc,omegaV,[mV,nt],'N',N,'tspan',tspan,'doDerivative',doDerivative);\nend\n[Tc,dT] = imgModel(T,omega,center(yc,m),'doDerivative',doDerivative);\n\n% compute distance\n[Dc,~,dD,dres,d2psi] = distance(Tc,Rc,omega,m,'doDerivative',doDerivative);\n\n% compute regularizer\n[Sc,dS,d2S] = regularizer(vc-vRef,omegaV,mV,'doDerivative',doDerivative,'tspan',tspan);\n\nJc = Dc + Sc;\n\n% collect variables for plots\npara = struct('Tc',Tc,'Rc',Rc,'omega',omega,'m',m,'yc',yc,'Jc',Jc,'Sc',Sc,'Dc',Dc,...\n 'N',pTrafo.N);\n\nif ~doDerivative, return; end;\ndD = dD*dT*dy;\ndJ = dD + dS;\nif nargout<4, return; end;\n\n% approximation to Hessian\ndres = dres*dT*dy;\n\n% multiply outer and inner derivatives, note: dy might be sparse\nif not(matrixFree),\n H = dres'*d2psi*dres + d2S;\nelse\n % approximation to d2D in matrix free mode\n % d2D = dr'*d2psi*dr\n % P and P' are operators matrix free\n H.omega = omegaV;\n H.m = mV;\n H.nt = nt;\n H.tspan = tspan;\n H.d2D.how = '*dr''*d2psi*dr';\n H.d2D.P = @(x) x;\n H.d2D.dr = dres;\n H.d2D.d2psi = d2psi;\n\n H.d2S = d2S;\n\nend;\n\nfunction runMinimalExample\nsetup2DGaussianData;\nlvl = 5;\nregularizer('reset','regularizer','mbElastic','alpha',1)\nv0 = getVelocityStartingGuess(omega,m);\nxc = getCellCenteredGrid(omega,ML{lvl}.m);\nT = reshape(imgModel(ML{lvl}.T,omega,center(xc,ML{lvl}.m)),ML{lvl}.m);\nRc = imgModel(ML{lvl}.R,omega,center(xc,ML{lvl}.m));\n\nfctn = @(vc) LDDMMobjFctn(T,Rc,omega,ML{lvl}.m,v0,xc,omega,m,10,vc);\ncheckDerivative(fctn,v0)\n\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/add-ons/LagLDDMM/LDDMMobjFctn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6362564967244436}} {"text": "function [GF2] = GreenFunction2(r0,r,f0)\n\nparameter; % Define parameters\nk0 = 2*pi*f0/c; % fixed wavenumber\n\nGF2 = zeros(1,N+1); % Initialisation of array vector\nmode0 = zeros(1,N+1);\n\n\n% Construct a line from r0 to r\ndiff_r_r0 = r - r0; %distance between r and r0\nrz0 = [r(1);r(2);0]; %Projection onto x-y plane\ndiff_rz0_r = rz0 - r0; %distance between r in z-axis and r0\n\n% Calculate the angles between the lines \nangle1 = acos((diff_r_r0'*diff_rz0_r)/(norm(diff_r_r0)*norm(diff_rz0_r)));\nangle2 = acos((diff_rz0_r'*rz0)/(norm(rz0)*norm(diff_rz0_r)));\n\nLvec = norm(diff_r_r0); %length of line\nNvec = (0:1:N);\nxpos = Nvec.*Lvec/N*cos(angle1)*sin(angle2) + r0(1);\nypos = Nvec.*Lvec/N*cos(angle1)*cos(angle2) + r0(2);\nzpos = Nvec.*Lvec/N*sin(angle1) + r0(3);\n\nfor d = 1:N+1\n \n%%% Calculate the AXIAL MODE %%%\n %lx\n \tN = fix(2*2*lx*f0/c); %number of axial modes below frequency f0\n nx = 1:N;\n rx = xpos(d);\n \t[modeshape,k_term] = AxialMode(nx,lx,rx,r0(1),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n %ly\n N = fix(2*2*ly*f0/c); %number of axial modes below frequency f0\n ny = 1:N;\n ry = ypos(d);\n \t[modeshape,k_term] = AxialMode(ny,ly,ry,r0(2),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n %lz\n N = fix(2*2*lz*f0/c); %number of axial modes below frequency f0\n nz = 1:N;\n rz = zpos(d);\n \t[modeshape,k_term] = AxialMode(nz,lz,rz,r0(3),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term)); \n \n%%% Calculate the TANGENTIAL MODE %%%\n %lx,ly\n \tN = fix(2*pi*lx*ly*f0^2/c^2); %number of tangential modes below frequency f0\n \tnx = 1:N; ny = nx;\n rx = xpos(d); ry = ypos(d);\n \t[modeshape,k_term] = TangentialMode(nx,ny,lx,ly,rx,ry,r0(1),r0(2),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n %ly,lz\n\t\tN = fix(2*pi*ly*lz*f0^2/c^2); %number of tangential modes below frequency f0 \n ny = 1:N; nz = ny;\n ry = ypos(d); rz = zpos(d);\n \t[modeshape,k_term] = TangentialMode(ny,nz,ly,lz,ry,rz,r0(2),r0(3),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n %lx,lz\n \tN = fix(2*pi*lx*lz*f0^2/c^2); %number of tangential modes below frequency f0\n nx = 1:N; nz = nx;\n rx = xpos(d); rz = zpos(d);\n \t[modeshape,k_term] = TangentialMode(nx,nz,lx,lz,rx,rz,r0(1),r0(3),k0);\n \tGF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n \n%%% Calculate the OBLIQUE MODE %%% \n %lx,ly,lz\n \tN = fix(2*4*pi*lx*ly*lz*f0^3/(3*c^3)); %number of oblique modes below frequency f0\n ny = 1:N; nz = ny;\n rx = xpos(d); ry = ypos(d); rz = zpos(d);\n for nx = 1:N,\n [modeshape,k_term] = ObliqueMode(nx,ny,nz,lx,ly,lz,rx,ry,rz,r0(1),r0(2),r0(3),k0);\n GF2(d) = GF2(d) + (-1/V)*sum(sum(modeshape./k_term));\n end;\n\n%%% Calculate the (0,0,0) mode %%%\n mode0 = -8/(V*k0.^2);\n\n%%% Calculate the Green function plus the (0,0,0) mode\n GF2(d) = GF2(d) + mode0; \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/10486-greens-function-in-a-room/GreenFunction2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.636256090737005}} {"text": "function [a,T] = compute_tf_model(xyu_trimmed, p_drone, p_physics)\n% COMPUTE_TF_MODEL - Function computing the transfer function model\n%\n% Syntax: out = airdata(x)\n%\n% Inputs:\n% x_trim - desired trimmed state\n% u_trim - desired trimmed input delta\n% y_trim - desired trimmed air data\n% P - parameters structure\n%\n% Outputs:\n% T_phi_da - transfer function (tf) from delta_aileron to roll\n% T_chi_phi - tf from chi to roll\n% T_theta_de - tf from delta_elevator to pitch \n% T_h_theta - tf from pitch to altitude\n% T_h_Va - tf from Va to altitude\n% T_Va_dt - tf from delta_thrust to Va\n% T_Va_theta - tf from pitch to Va\n% T_vy_dr - tf from delta_rudder to vy\n\nx_trim = xyu_trimmed(1:12);\ny_trim = xyu_trimmed(13:15);\nu_trim = xyu_trimmed(16:19);\n\n% Relabel inputs\n% Position in NED\n% pn = x_trim(1);\n% pe = x_trim(2);\n% pd = x_trim(3); % -altitude\n\n% UAV velocity wrt inertial frame in body frame\n% vx = x_trim(4);\n% vy = x_trim(5);\n% vz = x_trim(6);\n% v_xyz = x_trim(4:6);\n\n% Euler angles\n% phi = x_trim(7);\ntheta = x_trim(8);\n% psi = x_trim(9);\n\n% Rotation rates\n% p = x_trim(10);\n% q = x_trim(11);\n% r = x_trim(12);\n\n% Actuators\nde = u_trim(1); % delta elevator\n% da = u_trim(2); % delta aileron\n% dr = u_trim(3); % delta rudder\ndt = u_trim(4); % delta thrust\n\n% Wind\nVa = y_trim(1);\nalpha = y_trim(2);\n% beta = y_trim(3);\n\n% Compute parametrs\np_dyn = 0.5*p_physics.rho*Va^2;\nkb = p_drone.kb(Va);\nif isinf(kb)\n kb =0;\nend\nkc = p_drone.kc(Va);\nif isinf(kc)\n kc =0;\nend\n\na.phi1 = - p_dyn*p_drone.S_wing*p_drone.b*p_drone.Cp_p*kb;\na.phi2 = p_dyn*p_drone.S_wing*p_drone.b*p_drone.Cp_da;\n\na.beta1 = - 0.5 * p_physics.rho * Va * p_drone.S_wing / p_drone.mass * p_drone.CY_beta;\na.beta2 = 0.5 * p_physics.rho * Va * p_drone.S_wing / p_drone.mass * p_drone.CY_dr;\n\na.theta1 = - p_dyn * p_drone.c * p_drone.S_wing / p_drone.Jy * p_drone.Cm_q * kc;\na.theta2 = - p_dyn * p_drone.c * p_drone.S_wing / p_drone.Jy * p_drone.Cm_alpha;\na.theta3 = p_dyn * p_drone.c * p_drone.S_wing / p_drone.Jy * p_drone.Cm_de;\n\na.va1 = p_physics.rho * Va * p_drone.S_wing / p_drone.mass * ( p_drone.CD0 + p_drone.CD_alpha*alpha + p_drone.CD_de*de ) + ...\n p_physics.rho * p_drone.S_prop / p_drone.mass * p_drone.C_prop * Va;\na.va2 = p_physics.rho * p_drone.S_prop / p_drone.mass * p_drone.C_prop * p_drone.k_motor^2 * dt;\na.va3 = p_physics.gravity * cos(theta - alpha);\n\n% Define transfer functions\nT.phi_da = tf([a.phi2],[1,a.phi1,0]);\nT.chi_phi = tf([p_physics.gravity/Va],[1,0]);\nT.theta_de = tf(a.theta3,[1,a.theta1,a.theta2]);\nT.h_theta = tf([Va],[1,0]);\nT.h_Va = tf([theta],[1,0]);\nT.Va_dt = tf([a.va2],[1,a.va1]);\nT.Va_theta = tf([-a.va3],[1,a.va1]);\nT.vy_dr = tf([Va*a.beta2],[1,a.beta1]);\n\n", "meta": {"author": "lis-epfl", "repo": "swarmlab", "sha": "3574deddd2e4fdcc5696d08f93d6e888f45c8ecc", "save_path": "github-repos/MATLAB/lis-epfl-swarmlab", "path": "github-repos/MATLAB/lis-epfl-swarmlab/swarmlab-3574deddd2e4fdcc5696d08f93d6e888f45c8ecc/control/control_drone/compute_tf_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6362560848456461}} {"text": "function [x, infos] = sparse_nmf(V, rank, in_options)\n% Sparse nonnegative matrix factorization (sparseNMF)\n%\n% The problem of interest is defined as\n%\n% min D(V||W*H) + lambda * sum(H(:)),\n% where \n% {V, W, H} > 0.\n%\n% L1-based sparsity constraint on H.\n% Normalizes W column-wise.\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n% V : (m x n) non-negative matrix to factorize\n% rank : rank\n% in_options \n%\n%\n% Output:\n% x : non-negative matrix solution, i.e., x.W: (m x rank), x.H: (rank x n)\n% infos : log information\n% epoch : iteration nuber\n% cost : objective function value\n% optgap : optimality gap\n% time : elapsed time\n% grad_calc_count : number of sampled data elements (gradient calculations)\n%\n% Reference:\n%\n%\n% This file is part of NMFLibrary.\n%\n% Created by Patrik Hoyer, 2006 (and modified by Silja Polvi-Huttunen, \n% University of Helsinki, Finland, 2014)\n%\n% Modified by H.Kasai on Jul. 23, 2018\n%\n% Change log: \n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n% Jul. 14, 2022 (Hiroyuki Kasai): Fixed algorithm.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n\n % set local options \n local_options.lambda = 0; % regularizer for sparsity\n local_options.cost = 'euc'; % 'euc' or 'kl-div'\n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options); \n \n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W;\n H = init_factors.H; \n \n % initialize\n method_name = 'sparseNMF';\n epoch = 0; \n grad_calc_count = 0; \n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n % store additionally different cost\n reg_val = options.lambda*sum(sum(H));\n f_val_total = f_val + reg_val;\n infos.cost_reg = reg_val;\n infos.cost_total = f_val_total; \n \n if options.verbose > 1\n fprintf('sparseNMF: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', f_val, optgap); \n end \n\n % set start time\n start_time = tic();\n\n % main loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end\n\n % update H with MU\n %H = (H.*(W'*(V./(W*H))))/(1+alpha);\n VC = V./(W*H + 1e-9);\n VC(V==0 & W*H==0) = 1+1e-9;\n H = (H.*(W'*VC))/(1+options.lambda);\n \n \n % update W by Lee and Seung's divergence step\n %W = W.*((V./(W*H))*H')./(ones(vdim,1)*sum(H'));\n VC = V./(W*H + 1e-9);\n VC(V==0 & W*H==0) = 1+1e-9;\n W = W.*(VC*H')./(ones(m,1)*sum(H,2)'); \n \n % Liu, Zheng, and Lu add this normalization step\n W = W./(ones(m,1)*sum(W)); \n \n % measure elapsed time\n elapsed_time = toc(start_time); \n \n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n;\n\n % update epoch\n epoch = epoch + 1; \n \n % store info\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time); \n % store additionally different cost\n reg_val = options.lambda*sum(sum(H));\n f_val_total = f_val + reg_val;\n infos.cost_reg = [infos.cost_reg reg_val];\n infos.cost_total = [infos.cost_total f_val_total]; \n\n % display info\n display_info(method_name, epoch, infos, options); \n\n end \n\n x.W = W;\n x.H = H;\n \nend", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/sparse/sparse_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6362437054292491}} {"text": "function x = haar ( n, x )\n\n%*****************************************************************************80\n%\n%% HAAR performs a Haar transform.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2011\n%\n% Author:\n%\n% Ken Beauchamp\n%\n% Reference:\n%\n% Ken Beauchamp,\n% Walsh functions and their applications,\n% Academic Press, 1975,\n% ISBN: 0-12-084050-2,\n% LC: QA404.5.B33.\n%\n% Parameters:\n%\n% Input, integer N, the number of items in X.\n% N must be a power of 2.\n%\n% Input, real X(N), the data to be transformed.\n%\n% Output, real X(N), the transformed data.\n%\n k = i4_log_2 ( n );\n\n for i = 1 : k\n\n l = k + 1 - i;\n l2 = 2^( l - 1 );\n\n y(1:2*l2) = x(1:2*l2);\n\n for j = 1 : l2\n l3 = l2 + j;\n jj = 2 * j - 1;\n x(j) = y(jj) + y(jj+1);\n x(l3) = y(jj) - y(jj+1);\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/walsh/haar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6362297964550885}} {"text": "% capillary pressure curve for drainage\n% Written by Ali A. Eftekhari\nfunction res=dpc_drain(sw, pce, swc, labda)\npc0=1.0e7;\nres=zeros(size(sw));\nfor i=1:numel(sw) \n sw0=swc(i)+(1-labda*log(pc0/pce(i))+sqrt((-1+labda*log(pc0/pce(i)))^2+...\n 4*swc(i)/(1-swc(i))))/2*(1-swc(i));\n if sw(i)>sw0\n res(i)=-1.0/((1-swc(i))*labda)*pce(i)*((sw(i)-swc(i))/(1-swc(i)))^(-1.0/labda-1);\n elseif 0.0<=sw(i) && sw(i)<=sw0\n res(i)=-1.0/((1-swc(i))*labda)*pce(i)*((sw0-swc(i))/(1-swc(i)))^(-1.0/labda-1);\n else\n res(i)=0.0;\n end\nend", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/FieldGeology/dpc_drain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6362002601841039}} {"text": "function [SurfCov,Dis,CylVol,dis] = surface_coverage(P,Axis,Point,nl,ns,Dmin,Dmax)\n \n% ---------------------------------------------------------------------\n% SURFACE_COVERAGE.M Computes point surface coverage measure\n%\n% Version 1.1.0\n% Last update 7 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Inputs: \n% Axis Axis direction (1 x 3) \n% Point Starting point of the cylinder (1 x 3)\n% nl Number of layers in the axis direction used for to partition\n% the cylinder surface into layer/sectors\n% ns Number of sectors used to partition the cylinder surface into \n% layer/sectors\n% Dmin (Optional) Minimum point distance from the axis to be included\n% into SurfCov calculations\n% Dmax (Optional) Maximum point distance from the axis to be included\n% into SurfCov calculations\n% \n% Output: \n% SurfCov Number between 0 and 1 descring how big portion of the cylinder\n% surface is covered with points\n% Dis (Optional) Mean distances of the distances of the layer/sectors\n% CylVol (Optional) Volume of the cylinder estimated by the mean\n% distances of the layer/sectors as cylindrical sections\n% dis (Optional) Same as \"Dis\" but empty cells are interpolated\n% ---------------------------------------------------------------------\n% Computes surface coverage (number between 0 and 1) of points on cylinder \n% surface defined by \"Axis\" and \"Point\".\n\n% Changes from version 1.0.0 to 1.1.0, 7 Oct 2021:\n% 1) Added two possible inputs, minimum and maximum distance, \n% Dmin and Dmax, which can be used to filter out points for the surface\n% coverage calculations\n% 2) Computes the SurfCov estimate with four baseline directions used in\n% the sector determination and selects the largest value\n% 3) Smalle changes to speed up computations\n\n%% Compute the distances and heights of the points\n[d,V,h] = distances_to_line(P,Axis,Point);\nh = h-min(h);\nLen = max(h);\n\n%% (Optional) Filter out points based on the distance to the axis\nif nargin >= 6\n Keep = d > Dmin;\n if nargin == 7\n Keep = Keep & d < Dmax;\n end\n V = V(Keep,:);\n h = h(Keep);\nend\n\n%% Compute SurfCov\n% from 4 different baseline directions to determine the angles and select\n% the maximum value\nV0 = V;\n[U,W] = orthonormal_vectors(Axis); % First planar axes\nR = rotation_matrix(Axis,2*pi/ns/4); % Rotation matrix to rotate the axes\nSurfCov = zeros(1,4);\nfor i = 1:4\n %% Rotate the axes\n if i > 1\n U = R*U;\n W = R*W;\n end\n \n %% Compute the angles (sectors) of the points\n V = V0*[U W];\n ang = atan2(V(:,2),V(:,1))+pi;\n \n %% Compute lexicographic order (sector,layer) of every point\n Layer = ceil(h/Len*nl);\n Layer(Layer <= 0) = 1;\n Layer(Layer > nl) = nl;\n Sector = ceil(ang/2/pi*ns);\n Sector(Sector <= 0) = 1;\n LexOrd = [Layer Sector-1]*[1 nl]';\n \n %% Compute SurfCov\n Cov = zeros(nl,ns);\n Cov(LexOrd) = 1;\n SurfCov(i) = nnz(Cov)/nl/ns;\nend\nSurfCov = max(SurfCov);\n\n\n%% Compute volume estimate\nif nargout > 1\n % Sort according to increasing lexicographic order\n [LexOrd,SortOrd] = sort(LexOrd);\n d = d(SortOrd);\n \n % Compute mean distance of the sector-layer intersections\n Dis = zeros(nl,ns); % mean distances\n np = length(LexOrd); % number of points\n p = 1;\n while p <= np\n t = 1;\n while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\n t = t+1;\n end\n Dis(LexOrd(p)) = average(d(p:p+t-1));\n p = p+t;\n end\n \n if nargout > 2\n % Interpolate missing distances\n D = Dis;\n dis = Dis;\n Dinv = D((nl:-1:1)',:);\n D = [Dinv Dinv Dinv; D D D; Dinv Dinv Dinv];\n Zero = Dis == 0;\n RadMean = average(Dis(Dis > 0));\n for i = 1:nl\n for j = 1:ns\n if Zero(i,j)\n if nnz(D(i+nl-1:i+nl+1,j+ns-1:j+ns+1)) > 1\n d = D(i+nl-1:i+nl+1,j+ns-1:j+ns+1);\n dis(i,j) = average(d(d > 0));\n elseif nnz(D(i+nl-2:i+nl+2,j+ns-2:j+ns+2)) > 1\n d = D(i+nl-2:i+nl+2,j+ns-2:j+ns+2);\n dis(i,j) = average(d(d > 0));\n elseif nnz(D(i+nl-3:i+nl+3,j+ns-3:j+ns+3)) > 1\n d = D(i+nl-3:i+nl+3,j+ns-3:j+ns+3);\n dis(i,j) = average(d(d > 0));\n else\n dis(i,j) = RadMean;\n end\n end\n end\n end\n % Compute the volume estimate\n r = dis(:);\n CylVol = 1000*pi*sum(r.^2)/ns*Len/nl;\n end\nend\n", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/tools/surface_coverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6361593612161368}} {"text": "%IISUM Sum of integral image\n%\n% S = IISUM(II, U1, V1, U2, V2) is the sum of pixels in the rectangular image\n% region defined by its top-left (U1,V1) and bottom-right (U2,V2). II is\n% a precomputed integral image.\n%\n% See also INTGIMAGE.\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% MVTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with MVTB. If not, see .\n\nfunction s = iisum(ii, c1, r1, c2, r2)\n\n r1 = r1 - 1;\n if r1 < 1\n sA = 0;\n sB = 0;\n else\n sB = ii(r1,c2);\n end\n c1 = c1 - 1;\n if c1 < 1\n sA = 0;\n sC = 0;\n else\n sC = ii(r2,c1);\n end\n if (r1 >= 1) && (c1 >= 1)\n sA = ii(r1,c1);\n end\n\n s = ii(r2,c2) + sA -sB - sC;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/iisum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6361593600761746}} {"text": "function [Contain]=BuildMPS(A, b, Aeq, beq, cost, L, U, PbName, varargin)\n%\n% function Contain=BuildMPS(A, b, Aeq, beq, cost, L, U, PbName); OR\n% Contain=BuildMPS(..., Param1, Value1, ...);\n%\n% Build ascii fixed-width MPS matrix string that contains linear\n% programming (LP) problem:\n%\n% Minimizing (for x in R^n): f(x) = cost'*x, subject to\n% A*x <= b (LE)\n% Aeq*x = beq (EQ)\n% L <= x <= U (BD).\n%\n% Also supported is integer/mixte programming problem similar to the above,\n% where a subset of components of x is restricted to be integer (N set) or\n% binary set {0,1}.\n%\n% INPUTS:\n% A: (m x n) matrix\n% b: (m x 1) matrix\n% Aeq: (k x n) matrix\n% beq: (k x 1) matrix\n% cost: (n x 1) matrix\n% L: (1 x n), (n x 1) or (1 x 1)\n% U: (1 x n), (n x 1) or (1 x 1)\n%\n% Remark: To disable constraint(s) (LE, EQ, BD), please use empty []\n% for corresponding input matrix/rhs parameters.\n%\n% Optional:\n% - PbName is a string of problem name, default value is 'GENERIC'.\n% Other Params:\n% 'EleNames', 'EqtNames', or 'VarNames'\n% Cells contain string of respectively\n% (LE) equations, (EQ) equations, or variable names\n% - 'EleNameFun', 'EqtNameFun', or 'VarNameFun'\n% Corresponding Value are function handles that return\n% Equation/Variable name from equation/Variable number\n% Example: > VarNameFun=@(m) char('x'+(m-1));\n% These functions will NOT be used if names of equations/variables\n% are defined.\n% - Param is 'MPSfilename': output MPS file to be saved\n% No saving if MPSfilename is undefined.\n% - 'I', 'Int', 'Integer', 'Integers'\n% Array that stores the indexes that defines the set of integer\n% variables (>=0). The indexes must belong to [1,..., n] and\n% correspond to the column of A, Aeq.\n% - 'B', 'Bin', 'Binary', 'Binaries'\n% Array that stores the index that defines the set of binary\n% variables {0,1}. Indexes follow the same convention as with integer\n% case.\n% - 'QUAD', 'Q': a structure with following fields\n% 'Q': (n x n) matrix\n% The lower triangle of Q is assumed to be the transpose of the\n% upper triangle (in other word, Q must be symmetric and we use\n% only the upper part).\n% 'g': (n x 1) vector\n% 'bquad': scalar\n% 'name' (optional): string, name of the constraint.\n% if qs.name is 'COST' then the quadratic term in the\n% cost function to be minimized (see below)\n% 'type' (optional): must contains the string 'QLE'\n% (This field is reserved for future for extension of BuildMPS)\n%\n% QUAD parameters is used to enforce an additional quadratic\n% constraint on the unknown x of the type:\n% 0.5*x'*Q*x + g'*x <= bquad (QLE)\n%\n% Provide as many QUAD parameters as the number of constraints to be\n% meet.\n% Spatial case: if name is 'COST' then it corresponds to a quadratic\n% term of the cost function\n% f(x) = cost'*x + 0.5*x'*Q*x\n% For this case, the 'g' and 'bquad' fields will be ignored.\n%\n% OUTPUT:\n% Contain: char matrix of the MPS format description of LP/IP problem.\n%\n% RESTRICTION:\n% Only single column rhs (b and beq) is supported.\n%\n% The MPS (Mathematical Programming System) file format was introduced by\n% IBM in 1970s, but has also been accepted by most subsequent linear\n% programming codes. To learn about MPS format, please see:\n% http://lpsolve.sourceforge.net/5.5/mps-format.htm\n%\n% See also: SaveMPS\n%\n% Usage example:\n%\n% A = [1 1 0; -1 0 -1];\n% b = [5; -10];\n% L = [0; -1; 0];\n% U = [4; +1; +inf];\n% Aeq = [0 -1 1];\n% beq = 7;\n% cost = [1 4 9];\n% VarNameFun = @(m) (char('x'+(m-1))); % returning varname 'x', 'y' 'z'\n% \n% Qle = [2 1 0;\n% 1 2 0;\n% 0 0 1];\n% g = [0; 0; -3];\n% bquad = 100;\n% quad_le = struct('Q', Qle, ...\n% 'g', g, ...\n% 'bquad', bquad);\n% \n% Qcost = speye(3);\n% quad_cost = struct('Q', Qcost, ...\n% 'name', 'cost'), \n% Contain = BuildMPS(A, b, Aeq, beq, cost, L, U, 'Pbtest', ...\n% 'VarNameFun', VarNameFun, ...\n% 'EqtNames', {'Equality'}, ...\n% 'Q', quad_le, 'Q', quad_cost, ...\n% 'Integer', [1], ... % first variable 'x' integer\n% 'MPSfilename', 'Pbtest.mps');\n%\n% Author: Bruno Luong\n% update: 15-Jul-2008: sligly improved number formatting\n% 25-Aug-2009: Improvement in handling sparse matrix\n% 03-Sep-2009: integer/binary variables\n% 02-May-2010: quadratic term\n\nif nargin<8 || isempty(PbName)\n PbName='GENERIC';\nend\n\n%\n% Columns indices of MPS fields\n%\nidx1=02:03;\nidx2=05:12;\nidx3=15:22;\nidx4=25:36;\nidx5=40:47;\nidx6=50:61;\nidxlist={idx1 idx2 idx3 idx4 idx5 idx6};\n\n%\n% Default returned value if error occurs\n%\nContain=[]; %#ok\nOK = 0; %#ok\n\n%\n% Get the size of the input matrices\n%\n[neq nvar]=size(Aeq);\n[nle sizeA2]=size(A);\n\nif neq==0 % Aeq is empty, i.e., no equality constraint\n nvar=sizeA2;\n Aeq=zeros(0,nvar);\nelseif nle==0 % A is empty, i.e., no LE constraint\n sizeA2=nvar;\n A=zeros(0,nvar);\nend\n\n%\n% Default values for naming functions (nested functions)\n%\nelenamefun = @elename;\neqtnamefun = @eqtname;\nvarnamefun = @varname;\nMPSfilename = ''; % MPSfilename\n\n% default empty integer and binary sets\niset = [];\nbset = [];\n\n%\n% Parse options (varargin)\n%\nparseoptions(varargin{:});\n\n% Number of quadratic constraints\nnquadle = length(quadle);\n\nif ~exist('elenames','var')\n elenames=arrayfun(elenamefun, (1:nle), 'UniformOutput', false);\nend\nif ~exist('eqtnames','var')\n eqtnames=arrayfun(eqtnamefun, (1:neq), 'UniformOutput', false);\nend\nif ~exist('varnames','var')\n varnames=arrayfun(varnamefun, (1:nvar), 'UniformOutput', false);\nend\n\nif nargin<6 || isempty(L)\n L=-inf(1,nvar);\nelseif isscalar(L) % extend L if it's a scalar input\n Lval=L;\n L=zeros(1,nvar);\n L(:)=Lval;\nelse % BUG corrected, reshape L in row\n L = reshape(L,1,[]);\nend\nif nargin<7 || isempty(U)\n U=+inf(1,nvar);\nelseif isscalar(U) % extend U if it's a scalar input\n Uval=U;\n U=zeros(1,nvar);\n U(:)=Uval;\nelse % BUG corrected, reshape U in row\n U = reshape(U,1,[]);\nend\n\n%\n% Dimension check\n%\nif length(beq)~=neq || length(b)~=nle || ...\n length(cost)~=nvar || ...\n length(L)~=nvar || length(U)~=nvar || ...\n sizeA2~=nvar\n error('BuildMPS:DimensionsUnMatched', ...\n 'BuildMPS: dimensions do not match');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set problem name\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nl_name=setfields([],0,'NAME');\nl_name=setfields(l_name,3,PbName);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set equations in ROWS and COST\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nl_rows=setfields([],0,'ROWS');\n\nl_cost=setfields([],1,'N',2,'COST');\n\nl_rows_eq=emptyline(neq);\nfor m=1:neq\n l_rows_eq(m,:)=setfields(l_rows_eq(m,:),1,'E',2,eqtnames{m});\nend\n\nl_rows_le=emptyline(nle+nquadle);\nfor m=1:nle\n l_rows_le(m,:)=setfields(l_rows_le(m,:),1,'L',2,elenames{m});\nend\nfor m=1:nquadle\n l_rows_le(nle+m,:)=setfields(l_rows_le(nle+m,:),1,'L',2,quadle(m).name);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set coefficients of constraint equations in COLUMNS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Put all the linear constraint terms of quadratic in a matrix\nquadle_g = cat(2,quadle(:).g).'; % (nquadle x nvar)\nCostAeq = [cost(:).'; \n Aeq;\n A;\n quadle_g]; % CostAeq is sparse if any is sparse\nMustWrite = (CostAeq ~= 0);\nNWrite = sum(MustWrite,1);\nNLines = sum(ceil(NWrite/2));\n\nl_columns=setfields([],0,'COLUMNS');\nl_columnsbody=emptyline(NLines);\n\nc=0;\nfor n=1:nvar % Loop over variables\n var=varnames{n};\n field=3;\n eqtn = find(MustWrite(:,n)); % subset of (1:1+neq+nle+nquadle)\n for m=eqtn(:).' % 1:1+neq+nle+nquadle % Loop over eqt\n if m==1\n colname='COST';\n val = cost(n);\n elseif m<=1+neq\n colname=eqtnames{m-1};\n val=Aeq(m-1,n);\n elseif m<=1+neq+nle\n colname=elenames{m-(1+neq)};\n val=A(m-(1+neq),n);\n else\n iquad = m-(1+neq+nle);\n colname=quadle(iquad).name;\n val=quadle_g(iquad,n); \n end\n if field==3\n c=c+1;\n l_columnsbody(c,:)=setfields(l_columnsbody(c,:),...\n 2,var,...\n field,colname, ...\n field+1,val);\n field=5;\n else % field==5\n l_columnsbody(c,:)=setfields(l_columnsbody(c,:),...\n field,colname, ...\n field+1,val);\n field=3;\n end\n end % for-loop eqt\nend % for-loop variables\nl_columnsbody(c+1:end,:)=[];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set equation RHS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nquadle_bquad = [quadle(:).bquad]; % (1 x nquadle)\n\nrhs=[beq(:); b(:); quadle_bquad(:)];\nMustWrite = (rhs ~= 0);\nNWrite = sum(MustWrite);\nNLines = ceil(NWrite/2);\n\nl_rhs=setfields([],0,'RHS');\nl_rhsbody=emptyline(NLines);\nc=0;\nfield=3;\neqt = find(MustWrite); % subset of (1:neq+nle)\nfor m=eqt(:).' % 1:neq+nle+nquadle % Loop over eqt\n if m<=neq\n colname=eqtnames{m};\n val=rhs(m);\n elseif m<=neq+nle\n colname=elenames{m-neq};\n val=rhs(m);\n else\n colname=quadle(m-(neq+nle)).name;\n val=rhs(m);\n end\n if field==3\n c=c+1;\n l_rhsbody(c,:)=setfields(l_rhsbody(c,:),...\n 2,'RHS',...\n field,colname, ...\n field+1,val);\n field=5;\n else\n l_rhsbody(c,:)=setfields(l_rhsbody(c,:),...\n field,colname, ...\n field+1,val);\n field=3;\n end\nend % for-loop eqt\nl_rhsbody(c+1:end,:)=[];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set bound constraints\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nl_bound=setfields([],0,'BOUNDS');\n\nVarType=zeros(size(U));\n%\n% Var types (local definition)\n%\nVarType(:)=0; % real\nVarType(iset) = 1; % integer\nVarType(bset) = 2; % binary\n\n% Force lower/upper bound for integer variables to be integer as well\nL(iset) = max(ceil(L(iset)),0); % integer lower bound cannot be negative\nU(iset) = floor(U(iset));\n\n% Values not used, but we set for clarity\nL(bset) = 0;\nU(bset) = 1;\n\nupinf=(U==inf);\nloinf=(L==-inf);\nlonz=(L~=0) & ~loinf;\n\nBoundType=zeros(size(U));\n\n%\n% Bound types (local definition)\n%\nBoundType(:) = 3; % Default, 0<=x, real variable\nBoundType(upinf & loinf) = 1; % free, real\nBoundType(upinf & lonz) = 2; % lo<=x (lo ~= 0), real\nBoundType(~upinf & lonz) = 4; % lo<=x<=up, integer or real\nBoundType(~upinf & loinf) = 5; % x<=up, real\nBoundType(~upinf & ~loinf & ~lonz) = 6; % 0<=x<=up, integer or real\nBoundType(upinf & VarType==1) = 7; % lo<=x, integer\nBoundType(bset) = 8; % binary, x = 0 or 1\n\nNLines = sum(ismember(BoundType,[1 2 6 7 8])) + ...\n sum(ismember(BoundType,[4 5]))*2;\nl_boundbody=emptyline(NLines);\nc=0;\nfor n=1:nvar\n var=varnames{n};\n lo=L(n);\n up=U(n);\n vtype = VarType(n);\n if (vtype==2) % Type 8, binary variables\n c=c+1;\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, 'BV', ...\n 2, 'BND1', ...\n 3, var, ...\n 4, 1); % Field 4 must be 1.0 or blank \n elseif (up==inf)\n if (lo==-inf) % Type 1, Free real variable, one line\n c=c+1;\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, 'FR', ...\n 2, 'BND1', ...\n 3, var, ...\n 4, 0);\n elseif (lo~=0) || (vtype==1) % Type 2, or Type 7 lo<=x, one line\n c = c+1;\n if vtype==1 % integer, Type 7\n LOstr = 'LI';\n else % real, Type 2\n LOstr = 'LO';\n end\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, LOstr, ...\n 2, 'BND1', ...\n 3, var, ...\n 4, lo);\n % else 0<=x<=inf: Type3, real variable nothing to write\n end\n else % up-inf\n if lo~=0 % Type 4, lo<=x<=up\n c=c+1;\n if vtype==1 % integer\n LOstr = 'LI';\n else % real\n LOstr = 'LO';\n end\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, LOstr, ...\n 2, 'BND1', ...\n 3, var, ...\n 4, lo);\n %else % 0<=x<=up % Type 6\n end\n else % if lo==-inf % Type 5, x<=up\n c=c+1;\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, 'MI', ...\n 2, 'BND1', ...\n 3, var, ...\n 4, 0);\n end\n % Common Type 4, 5, or 6\n % Type 6 is 0<=x<=up\n c=c+1;\n if vtype==1 % integer\n HIstr = 'UI';\n else % real\n HIstr = 'UP';\n end\n l_boundbody(c,:)=setfields(l_boundbody(c,:),...\n 1, HIstr, ...\n 2, 'BND1', ...\n 3, var, ...\n 4, up);\n end\nend % for-loop on variable\nl_boundbody(c+1:end,:)=[];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Quad section\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfor m=1:nquadle\n % Get the current quad structure\n qs = quadle(m);\n l_quad = setfields([],0,'QSECTION');\n l_quad = setfields(l_quad,3,qs.name);\n \n % Use only the upper-triangular part of Q\n [i j Qij] = find(triu(qs.Q));\n NLines = length(Qij);\n l_quadbody = emptyline(NLines);\n \n for n=1:NLines % Loop over non-zeros elements\n vari=varnames{i(n)};\n varj=varnames{j(n)};\n l_quadbody(n,:) = setfields(l_quadbody(n,:), ...\n 2,vari,...\n 3,varj, ...\n 4,Qij(n));\n end\n \n quadle(m).qsection = [l_quad; \n l_quadbody]; %#ok\n\nend % for-loop on quadratic constraints\n\nif nquadle>1\n % concatenate together all the qsections\n l_allquad = cat(1,quadle(:).qsection);\nelse\n % empty line\n l_allquad = l_name([],:);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Set the last card\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nl_end=setfields([],0,'ENDATA');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Concatenate together all parts of mps format\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nContain=[l_name; ...\n l_rows; ...\n l_cost; ...\n l_rows_eq; ...\n l_rows_le; ...\n l_columns; ...\n l_columnsbody; ...\n l_rhs; ...\n l_rhsbody; ...\n l_bound; ...\n l_boundbody; ...\n l_allquad; ...\n l_end];\n\nif ~isempty(MPSfilename)\n %\n % Save the Contain in MPSfilename\n %\n OK = SaveMPS(MPSfilename, Contain);\n if ~OK % Something is wrong during saving\n warning('BuildMPS:SavingFailure', ...\n ['BuildMPS: Cannot save ' MPSfilename]);\n end\nelse % Nothing to save\n OK = 1;\nend\n\n% return % Uncomment the RETURN statement causes M-lint to crash on 2009A\n% There is no instructions from now on, juts nested functions\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Nested functions: BE AWARE, the functions have access to local\n% variables of BuildMPS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Generate n empty lines of MPS data\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function l=emptyline(n)\n if nargin<1 || isempty(n)\n n=1;\n end\n l=char(zeros(n,61));\n l(:)=' ';\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Convert to string at the fixed length of 12\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function str=num2fixedlengthstr(num, maxlength, roundingflag)\n % function str=num2fixedlengthstr(num); OR\n % str=num2fixedlengthstr(..., maxlength, roundingflag);\n %\n % Convert double NUM to decimal string having MAXLENGTH [12] as maximum\n % length. Smart conversion with accurate result despite length constraint.\n %\n % ROUNDINGFLAG: 0 or [1]\n % 0: truncate fracional part (quicker)\n % 1: rounding fracional part (more accurate).\n %\n % Last update: 15/Aug/2008, remove leading \"0\" when the string starts\n % as \"0.xxxx\"\n %\n if nargin<2\n maxlength=12;\n end\n\n if nargin<3\n roundingflag=1; % rounding by default\n end\n\n if num>=0\n fracNDigits=maxlength;\n else\n fracNDigits=maxlength-1;\n end\n % \"%G\" format:\n % ANSI specification X3.159-1989: \"Programming Language C,\"\n % ANSI, 1430 Broadway, New York, NY 10018.\n str=num2str(num,['%0.' num2str(fracNDigits) 'G']);\n %\n % Try to compact the string data to fit inside the field length\n %\n while length(str)>maxlength\n if regexp(str,'^0\\.') % delete the leading 0 in \"0.xxx\"\n str(1)=[];\n continue;\n end\n [istart iend]=regexp(str,'[+-](0)+'); % +/- followed by multiples 0\n if ~isempty(istart) % Remove zero in xxxE+000yy or xxxE-000yy\n str(istart+1:iend)=[];\n continue\n else\n [istart iend]=regexp(str,'E[+]');\n if ~isempty(istart) % Remove \"+\" char in xxxE+yyy\n str(iend)=[];\n continue\n end\n end\n idot=find(str=='.',1,'first');\n if ~isempty(idot)\n iE=find(str=='E',1,'first');\n if roundingflag % rounding fraction part\n % Calculate the Length of the fractional part\n % Adjust its number of digits and start over again\n if ~isempty(iE) % before the mantissa\n fracNDigits=maxlength-length(str)+iE-idot-1;\n str=num2str(num,['%0.' num2str(fracNDigits) 'E']);\n else %if idot<=maxlength+1 % no manissa\n fracNDigits=maxlength-idot;\n str=num2str(num,['%0.' num2str(fracNDigits) 'f']);\n end\n roundingflag=0; % won't do rounding again\n continue % second pass with new string\n else\n % truncate the fractional part\n if ~isempty(iE) % before the mantissa\n str(maxlength-length(str)+iE:iE-1)=[];\n return;\n else %if idot<=maxlength+1 % no mantissa\n str(maxlength+1:end)=[];\n return;\n end\n end\n end\n % it should not never go here, unless BUG\n error('BuildMPS: cannot convert %0.12e to string\\n',num);\n end % while loop\n\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Set the field of an MPS line by value\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function l=setfield(l,field,var)\n\n if isnumeric(var) % numerical data, convert to string\n var=num2fixedlengthstr(var); % convert to 12-length string\n end\n\n if isempty(l)\n l=emptyline;\n end\n if ~isempty(field) && field>0\n idx=idxlist{field};\n else\n idx=1:61;\n end\n if length(var)>length(idx)\n var=var(1:length(idx));\n else\n idx=idx(1:length(var));\n end\n l(idx)=var;\n\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Set multiple fields of an MPS line by values\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function l=setfields(l, varargin)\n for k=1:2:length(varargin)\n l=setfield(l, varargin{k}, varargin{k+1});\n end\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Generate equation name for (LE) constraint\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function name=elename(m)\n name=['LE' num2str(m)];\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Generate equation name for (EQ) constraint\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function name=eqtname(m)\n name=['EQ' num2str(m)];\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Generate variable name\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function name=varname(n)\n name=['X' num2str(n)];\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Generate equation name for (QLE) constraint\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function name=quadlename(m)\n name=['QLE' num2str(m)];\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Parse a pair of Name/Value option\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function parseoption(strname, value)\n if ischar(strname)\n strname = strtrim(lower(strname));\n switch strname\n case 'elenames', \n if ~iscell(value) || length(value)~=nle || ...\n ~all(cellfun(@ischar, value))\n error('BuildMPS:IncorrectEleNames', ...\n 'BuildMPS: EleNames must be cell of %d strings', nle);\n end\n elenames = value;\n case 'eqtnames',\n if ~iscell(value) || length(value)~=neq || ...\n ~all(cellfun(@ischar, value))\n error('BuildMPS:IncorrectEqtNames', ...\n 'BuildMPS: EqtNames must be cell of %d strings', neq);\n end\n eqtnames = value;\n case 'varnames',\n if ~iscell(value) || length(value)~=nvar || ...\n ~all(cellfun(@ischar, value))\n error('BuildMPS:IncorrectVarNames', ...\n 'BuildMPS: VarNames must be cell of %d strings', nvar);\n end\n varnames = value;\n case 'varnamefun',\n if ischar(value)\n value=str2func(value);\n end\n if ~isa(value,'function_handle')\n error('BuildMPS:IncorrectVarNameFun', ...\n 'BuildMPS: VarNameFun must be a function');\n end\n varnamefun = value;\n case 'eqtnamefun',\n if ischar(value)\n value=str2func(value);\n end\n if ~isa(value,'function_handle')\n error('BuildMPS:IncorrectEqtNameFun', ...\n 'BuildMPS: EqtNameFun must be a function');\n end\n eqtnamefun = value;\n case 'elenamefun',\n if ischar(value)\n value=str2func(value);\n end\n if ~isa(value,'function_handle')\n error('BuildMPS:IncorrectEleNameFun', ...\n 'BuildMPS: EleNameFun must be a function');\n end\n elenamefun = value;\n case 'mpsfilename',\n if ~ischar(value)\n error('BuildMPS:IncorrectMPSfilename', ...\n 'BuildMPS: MPSfilename must be a string');\n end\n MPSfilename = value;\n case {'i' 'int' 'integer' 'integers'},\n iset = value(:);\n if any(iset<1 | iset>nvar)\n error('Integer set contains invalid index');\n end\n case {'b' 'bin' 'binary' 'binaries'},\n bset = value(:);\n if any(bset<1 | bset>nvar)\n error('Binary set contains invalid index'); \n end\n case {'quad' 'q'},\n qcounter = length(quadle)+1;\n % Basic check of quad structure\n if isstruct(value)\n qs = value;\n if ~isfield(qs,'Q') || ~isequal(size(qs.Q),[nvar nvar])\n error('Missing or invalid field in QUAD structure');\n end\n if ~isfield(qs,'g') || isempty(qs.g)\n qs.g = zeros(nvar,1);\n elseif isequal(size(qs.g), [1 nvar])\n % reshape in column\n qs.g = qs.g(:);\n elseif ~isequal(size(qs.g), [nvar 1])\n error('Invalid field in QUAD');\n end\n if ~isfield(qs,'bquad') || isempty(qs.bquad)\n qs.bquad = 0;\n end\n if ~isscalar(qs.bquad)\n error('Missing or invalid field in QUAD structure');\n end \n if ~isfield(qs,'type')\n qs.type = 'QLE';\n end\n if ~strcmpi(qs.type ,'QLE')\n error('Invalid field in QUAD structure');\n end\n if ~isfield(qs,'name') || isempty(qs.name)\n qs.name = quadlename(qcounter);\n elseif strcmpi(qs.name,'COST') %\n qs.name = 'COST'; % force to be upper case\n % The linear term for the functional must be\n % provides in the 5th parameter\n % so we set 'g' to zero\n qs.g(:) = 0;\n qs.bquad(:) = 0;\n end\n else\n if isempty(value)\n return % ignore empty argument\n end\n error('Invalid input QUAD (must be a structure)');\n end\n quadle(qcounter) = orderfields(qs);\n otherwise\n warning('BuildMPS:UnknownParams', ...\n ['BuildMPS: Unknown parameter ' strname]);\n end\n else\n error('BuildMPS:IncorrectCall', ...\n 'BuildMPS: options must be pair of Name/Value');\n end\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Parse options\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function parseoptions(varargin)\n if mod(nargin,2)\n error('BuildMPS:IncorrectCall', ...\n 'BuildMPS: options must be pair of Name/Value'); \n end\n \n % default empty quadle\n quadle = struct('Q', {}, ...\n 'g', {}, ...\n 'bquad', {}, ...\n 'type', {}, ...\n 'name', {} ...\n );\n \n quadle = orderfields(quadle); \n \n %\n % Loop over pair of Name/Value option\n %\n for ivararg=1:2:nargin\n parseoption(varargin{ivararg},varargin{ivararg+1});\n end\n \n end\n\nend % BuildMPS\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/io/BuildMPS/BuildMPS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6361593600761745}} {"text": "function [mappedX, mapping] = kernel_pca(X, no_dims, varargin)\n%KERNEL_PCA Perform the kernel PCA algorithm\n%\n% [mappedX, mapping] = kernel_pca(X, no_dims)\n% [mappedX, mapping] = kernel_pca(X, no_dims, kernel)\n% [mappedX, mapping] = kernel_pca(X, no_dims, kernel, param1)\n% [mappedX, mapping] = kernel_pca(X, no_dims, kernel, param1, param2)\n%\n% The function runs kernel PCA on a set of datapoints X. The variable\n% no_dims sets the number of dimensions of the feature points in the \n% embedded feature space (no_dims >= 1, default = 2). \n% For no_dims, you can also specify a number between 0 and 1, determining \n% the amount of variance you want to retain in the PCA step.\n% The value of kernel determines the used kernel. Possible values are 'linear',\n% 'gauss', 'poly', 'subsets', or 'princ_angles' (default = 'gauss'). For\n% more info on setting the parameters of the kernel function, type HELP\n% GRAM.\n% The function returns the locations of the embedded trainingdata in \n% mappedX. Furthermore, it returns information on the mapping in mapping.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if ~exist('no_dims', 'var')\n no_dims = 2;\n end\n kernel = 'gauss';\n param1 = 1;\n\tparam2 = 3;\n if nargin > 2\n\t\tkernel = varargin{1};\n\t\tif length(varargin) > 1 & strcmp(class(varargin{2}), 'double'), param1 = varargin{2}; end\n\t\tif length(varargin) > 2 & strcmp(class(varargin{3}), 'double'), param2 = varargin{3}; end\n end\n \n % Store the number of training and test points\n ell = size(X, 1);\n\n if size(X, 1) < 2000\n\n % Compute Gram matrix for training points\n disp('Computing kernel matrix...'); \n K = gram(X, X, kernel, param1, param2);\n\n % Normalize kernel matrix K\n mapping.column_sums = sum(K) / ell; % column sums\n mapping.total_sum = sum(mapping.column_sums) / ell; % total sum\n J = ones(ell, 1) * mapping.column_sums; % column sums (in matrix)\n K = K - J - J';\n K = K + mapping.total_sum;\n \n % Compute first no_dims eigenvectors and store these in V, store corresponding eigenvalues in L\n disp('Eigenanalysis of kernel matrix...');\n K(isnan(K)) = 0;\n K(isinf(K)) = 0;\n [V, L] = eig(K);\n else\n % Compute column sums (for out-of-sample extension)\n mapping.column_sums = kernel_function([], X', 1, kernel, param1, param2, 'ColumnSums') / ell;\n mapping.total_sum = sum(mapping.column_sums) / ell;\n \n % Perform eigenanalysis of kernel matrix without explicitly\n % computing it\n disp('Eigenanalysis of kernel matrix (using slower but memory-conservative implementation)...');\n options.disp = 0;\n options.isreal = 1;\n options.issym = 1;\n [V, L] = eigs(@(v)kernel_function(v, X', 1, kernel, param1, param2, 'Normal'), size(X, 1), no_dims, 'LM', options);\n disp(' ');\n end\n \n % Sort eigenvalues and eigenvectors in descending order\n [L, ind] = sort(diag(L), 'descend');\n L = L(1:no_dims);\n\tV = V(:,ind(1:no_dims));\n \n % Compute inverse of eigenvalues matrix L\n\tdisp('Computing final embedding...');\n invL = diag(1 ./ L);\n \n % Compute square root of eigenvalues matrix L\n sqrtL = diag(sqrt(L));\n \n % Compute inverse of square root of eigenvalues matrix L\n invsqrtL = diag(1 ./ diag(sqrtL));\n \n % Compute the new embedded points for both K and Ktest-data\n mappedX = sqrtL * V'; % = invsqrtL * V'* K\n \n % Set feature vectors in original format\n mappedX = mappedX';\n \n % Store information for out-of-sample extension\n mapping.X = X;\n mapping.V = V;\n mapping.invsqrtL = invsqrtL;\n mapping.kernel = kernel;\n mapping.param1 = param1;\n mapping.param2 = param2;\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/kernel_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6360568511411588}} {"text": "classdef CEC2017_F5 < PROBLEM\n% \n% CEC'2017 constrained optimization benchmark problem\n\n%------------------------------- Reference --------------------------------\n% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and\n% evaluation criteria for the CEC 2017 competition on constrained real-\n% parameter optimization, National University of Defense Technology, China,\n% 2016.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n O; % Optimal decision vector\n Mat1;\t% Rotation matrices\n Mat2;\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n CallStack = dbstack('-completenames');\n load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');\n obj.O = Data{5}.o;\n obj.M = 1;\n if isempty(obj.D) || obj.D < 30\n obj.D = 10;\n obj.Mat1 = Data{5}.M1_10;\n obj.Mat2 = Data{5}.M2_10;\n elseif obj.D < 50\n obj.D = 30;\n obj.Mat1 = Data{5}.M1_30;\n obj.Mat2 = Data{5}.M2_30;\n elseif obj.D < 100\n obj.D = 50;\n obj.Mat1 = Data{5}.M1_50;\n obj.Mat2 = Data{5}.M2_50;\n else\n obj.D = 100;\n obj.Mat1 = Data{5}.M1_100;\n obj.Mat2 = Data{5}.M2_100;\n end\n obj.lower = zeros(1,obj.D) - 10;\n obj.upper = zeros(1,obj.D) + 10;\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n PopObj = sum(100*(Z(:,1:end-1).^2-Z(:,2:end)).^2+(Z(:,1:end-1)-1).^2,2);\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);\n Y = Z*obj.Mat1';\n W = Z*obj.Mat2';\n PopCon(:,1) = sum(Y.^2-50*cos(2*pi*Y)-40,2);\n PopCon(:,2) = sum(W.^2-50*cos(2*pi*W)-40,2);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Single-objective optimization/CEC 2017/CEC2017_F5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6360568505709004}} {"text": "function [afixed,sqnorm,ierr] = lsearch (afloat,L,D,Chi2,ncands)\n%LSEARCH: Integer ambiguity resolution, search\n%\n% This routine finds the integer vector which is closest to a given\n% float vector, in a least squares sence. This is the search-step in\n% integer ambiguity resolution. It is best to perform this search only\n% on ambiguities which have been decorrelated using LAMBDA.\n%\n% Input arguments:\n% afloat : Float ambiguities (\\hat{a})\n% L : LtDL-decomposition of the decorrelated\n% D variance-covariance matrix of the ambiguities\n% Chi2 : Size of the search ellipsoid\n% ncands : Number of requested candidates\n%\n% Output arguments:\n% afixed : Estimated integers (matrix)\n% sqnorm : Corresponding squared norms (vector, sorted)\n% ierr : Error code: 0: No errors found\n% 1: Not enough candidates found\n\n% ----------------------------------------------------------------------\n% File.....: lsearch.m\n% Date.....: 19-MAY-1999\n% Author...: Peter Joosten\n% Mathematical Geodesy and Positioning\n% Delft University of Technology\n% ----------------------------------------------------------------------\n\n% -------------------------------\n% --- Initializing statements ---\n% -------------------------------\n\nLinv = (L)^(-1);\nDinv = 1./D;\n\nTrue = 1;\nFalse = 0;\n\nn = max(size(afloat));\n\nright = [zeros(n,1) ; Chi2];\nleft = [zeros(n+1,1)];\ndq = [Dinv(2:n)./Dinv(1:n-1) 1/Dinv(n)];\n\ncand_n = False;\nc_stop = False;\nendsearch = False;\n\nncan = 0;\n\ni = n + 1;\niold = i;\nierr = 0;\n\nafixed = zeros(n,ncands);\nsqnorm = zeros(1,ncands);\n\n% ----------------------------------\n% --- Start the main search-loop ---\n% ----------------------------------\n\nwhile ~ (endsearch);\n\n i = i - 1;\n\n if iold <= i\n lef(i) = lef(i) + Linv(i+1,i);\n else\n lef(i) = 0;\n for j = i+1:n;\n lef(i) = lef(i) + Linv(j,i)*distl(j,1);\n end;\n end;\n iold = i;\n\n right(i) = (right(i+1) - left(i+1)) * dq(i);\n reach = sqrt(right(i));\n delta = afloat(i) - reach - lef(i);\n distl(i,1) = ceil(delta) - afloat(i);\n\n if distl(i,1) > reach - lef(i)\n\n% ----------------------------------------------------\n% --- There is nothing at this level, so backtrack ---\n% ----------------------------------------------------\n\n cand_n = False;\n c_stop = False;\n\n while (~ c_stop) & (i < n);\n\n i = i + 1;\n if distl(i) < endd(i);\n distl(i) = distl(i) + 1;\n left(i) = (distl(i) + lef(i)) ^ 2;\n c_stop = True;\n if i == n; cand_n = True; end;\n end;\n\n end;\n\n if (i == n) & (~ cand_n); endsearch = True; end;\n\n else\n\n% ----------------------------\n% --- Set the right border ---\n% ----------------------------\n\n endd(i) = reach - lef(i) - 1;\n left(i) = (distl(i,1) + lef(i)) ^ 2;\n\n end\n\n if i == 1;\n\n% -------------------------------------------------------------------\n% --- Collect the integer vectors and corresponding ---\n% --- squared distances, add to vectors \"afixed\" and \"sqnorm\" if: --- ---\n% --- * Less then \"ncands\" candidates found so far ---\n% --- * The squared norm is smaller than one of the previous ones ---\n% -------------------------------------------------------------------\n\n t = Chi2 - (right(1)-left(1)) * Dinv(1);\n endd(1) = endd(1) + 1;\n\n while distl(1) <= endd(1);\n\n if ncan < ncands;\n\n ncan = ncan + 1;\n afixed(1:n,ncan) = distl + afloat;\n sqnorm(ncan) = t;\n\n else\n\n [maxnorm,ipos] = max(sqnorm);\n if t < maxnorm;\n afixed(1:n,ipos) = distl + afloat;\n sqnorm(ipos) = t;\n end;\n\n end;\n\n t = t + (2 * (distl(1) + lef(1)) + 1) * Dinv(1);\n distl(1) = distl(1) + 1;\n\n end;\n\n\n% -------------------------\n% --- And backtrack ... ---\n% -------------------------\n\n cand_n = False;\n c_stop = False;\n\n while (~ c_stop) & (i < n);\n\n i = i + 1;\n\n if distl(i) < endd(i);\n distl(i) = distl(i) + 1;\n left(i) = (distl(i) + lef(i)) ^ 2;\n c_stop = True;\n if i == n; cand_n = True; end;\n end;\n\n end;\n\n if (i == n) & (~ cand_n); endsearch = True; end;\n\n end;\n\nend;\n\n% ----------------------------------------------------------------------\n% --- Sort the resulting candidates, according to the norm\n% ----------------------------------------------------------------------\n\ntmp = sortrows ([sqnorm' afixed']);\nsqnorm = tmp(:,1)';\nafixed = tmp(:,2:n+1)';\n\n% ------------------------\n% --- Check for errors ---\n% ------------------------\n\nif ncan < ncands; ierr = 1; end;\n\n% ----------------------------------------------------------------------\n% End of routine: lsearch\n% ----------------------------------------------------------------------\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/positioning/lambda/lambda_v2/lsearch_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6360568314202708}} {"text": "% Feature sign search\n% code by Wang Jinjun @ NEC Research Lab America\n% reference\n% Efficient sparse coding algorithms\n% Honglak Lee Alexis Battle Rajat Raina Andrew Y. Ng\n% Computer Science Department\n% Stanford University\n% Stanford, CA 94305\n\nfunction [x]=feature_sign(B,y,lambda,init_x)\n\nnbases=size(B,2);\n\nOptTol = 1e-5;\n\nif nargin < 4,\n x=zeros(nbases, 1);\nelse\n x = init_x;\nend;\n\ntheta=sign(x); %sign flag\na=(x~=0); %active set\n\noptc=0; \n\nBy=B'*y;\nB_h=B(:,a);\nx_h=x(a);\nBx_h=B_h*x_h;\nall_d=2*(B'*Bx_h-By);\n[ma mi]=max(abs(all_d).*(~a));\n\nwhile optc==0,\n \n optc=1;\n\n if all_d(mi)>lambda+1e-10,\n theta(mi)=-1;\n a(mi)=1;\n b=B(:,mi);\n x(mi)=(lambda-all_d(mi))/(b'*b*2); \n elseif all_d(mi)<-lambda-1e-10,\n theta(mi)=1;\n a(mi)=1;\n b=B(:,mi);\n x(mi)=(-lambda-all_d(mi))/(b'*b*2); \n else\n if sum(a)==0, \n lambda=ma-2*1e-10;\n optc=0;\n b=B(:,mi);\n x(mi)=By(mi)/(b'*b);\n break;\n end\n end \n\n opts=0;\n B_h=B(:,a);\n x_h=x(a);\n theta_h=theta(a);\n \n while opts==0,\n opts=1;\n\n if size(B_h,2)<=length(y),\n BB=B_h'*B_h;\n x_new=BB\\(B_h'*y-lambda*theta_h/2);\n o_new=L1_cost(y,B_h,x_new,lambda);\n \n %cost based on changing sign\n s=find(sign(x_new)~=theta_h);\n x_min=x_new;\n o_min=o_new;\n for j=1:length(s),\n zd=s(j);\n x_s=x_h-x_h(zd)*(x_new-x_h)/(x_new(zd)-x_h(zd));\n x_s(zd)=0; %make sure it's zero\n o_s=L1_cost(y,B_h,x_s,lambda);\n if o_sOptTol)),\n opts=0;\n end\n end\n \n all_d=2*(B'*Bx_h-By);\n \n [ma mi]=max(abs(all_d).*(~a));\n if ma>lambda+OptTol,\n optc=0;\n end\nend\n\nreturn;\n\nfunction cost=L1_cost(y,B,x,lambda)\n tmp = y-B*x;\n cost = tmp'*tmp+lambda*norm(x,1);\nreturn\n\n\n", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/Aplus/CVPR08-SR/Solver/feature_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6360568308500125}} {"text": "function upsilonjv = lfmjvComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode)\n\n% LFMJVCOMPUTEUPSILONMATRIX Upsilon matrix jolt. vel. with t1, t2 limits\n% FORMAT\n% DESC computes a portion of the LFMJV kernel.\n% ARG gamma : Gamma value for system.\n% ARG sigma2 : length scale of latent process.\n% ARG t1 : first time input (number of time points x 1).\n% ARG t2 : second time input (number of time points x 1).\n% ARG mode : operation mode, according to the derivative (mode 0,\n% derivative wrt t1, mode 1 derivative wrt t2)\n% RETURN upsilon : result of this subcomponent of the kernel for the given values.\n%\n% COPYRIGHT : Mauricio Alvarez, 2010\n%\n% SEEALSO : lfmComputeUpsilonMatrix.F, lfmvpComputeUpsilonMatrix.m\n\n% KERN\n\nsigma = sqrt(sigma2);\ngridt1 = repmat(t1, 1, length(t2));\ngridt2 = repmat(t2', length(t1), 1);\ntimeGrid = gridt1 - gridt2;\n\nif mode==0\n upsilonjv = gamma^2*lfmvvComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode) ...\n - (4/(sqrt(pi)*sigma^3))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + (2*timeGrid)/sigma2).*(1-(2*timeGrid.^2)/sigma2) + 4*timeGrid/sigma2);\nelse\n upsilonjv = gamma^2*lfmvvComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode) ...\n - (4/(sqrt(pi)*sigma^3))*exp(-(timeGrid.^2)./sigma2).* ...\n ((gamma + (2*timeGrid)/sigma2).*(1-(2*timeGrid.^2)/sigma2) + 4*timeGrid/sigma2) ...\n + ((4*gamma)/(sqrt(pi)*sigma^3))*exp(-gamma*t1)*...\n ((t2.*(gamma - 2*t2/sigma2) + 1).*exp(-t2.^2/sigma2)).';\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/lfmjvComputeUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6360568267751776}} {"text": "function [l,L_f,L_lf] = fromFrameIdpLin(F,lf)\n\n% FROMFRAMEIDPLIN Transforms IDP line from local frame to global frame.\n% I = FROMFRAMEIDPLIN(F,LF) transforms the Inverse Depth line LF from the\n% local frame F to the global frame. The frame F must be specified via a\n% structure containing at least the fields F.t, F.q, F.R and F.Rt\n% (translation, quaternion, rotation matrix and its transpose).\n%\n% [I,L_f,L_lf] = FROMFRAMEIDPLIN(...) returns the Jacobians wrt F and IF.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargout == 1\n [p1f,p2f] = idpLin2idpPnts(lf);\n\n p1 = fromFrameIdp(F,p1f);\n p2 = fromFrameIdp(F,p2f);\n\n l = [p1;p2(4:6,:)];\n\nelse\n % idp parts\n xf = lf(1:3);\n w1f = lf(4:5);\n r1 = lf(6);\n w2f = lf(7:8);\n r2 = lf(9);\n \n % dir. vectors\n [m1f, M1F_w1f] = py2vec(w1f); \n [m2f, M2F_w2f] = py2vec(w2f); \n \n % from frame\n [x, X_f, X_xf] = fromFrame(F,xf);\n [m1, M1_f, M1_m1f] = fromFrameVec(F,m1f);\n [m2, M2_f, M2_m2f] = fromFrameVec(F,m2f);\n\n % angle vectors\n [w1, W1_m1] = vec2py(m1);\n [w2, W2_m2] = vec2py(m2);\n \n % partial Jacobians\n W1_f = W1_m1*M1_f;\n W2_f = W2_m2*M2_f;\n W1_w1f = W1_m1*M1_m1f*M1F_w1f;\n W2_w2f = W2_m2*M2_m2f*M2F_w2f;\n R_f = zeros(1,7);\n \n % new idp line\n l = [x;w1;r1;w2;r2];\n \n % Jacobians\n L_f = [X_f;W1_f;R_f;W2_f;R_f];\n L_lf = [...\n X_xf zeros(3) zeros(3)\n zeros(2,3) W1_w1f [0;0] zeros(2,3)\n 0 0 0 0 0 1 0 0 0\n zeros(2,3) zeros(2,3) W2_w2f [0;0]\n 0 0 0 0 0 0 0 0 1 ] ;\n \nend\n\nreturn\n\n%% jac\n\nsyms x y z a b c d X Y Z A1 B1 R1 A2 B2 R2 real\nF.x = [x;y;z;a;b;c;d];\nF = updateFrame(F);\nl_F = [X;Y;Z;A1;B1;R1;A2;B2;R2];\n\n[l,L_f,L_lf] = fromFrameIdpLin(F,l_F);\n\nsimplify(L_f - jacobian(l,F.x))\nsimplify(L_lf - jacobian(l,l_F))\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/Lines/fromFrameIdpLin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6360412050295402}} {"text": "%DEMO_SURVIVAL_COMPARISON Survival model comparison\n%\n% Description: \n% \n% By using kfc-validation and Bayesian bootstrap we compare the\n% predictive ability of different models by estimating various\n% assessment statistics .\n%\n% We will compare two Cox proportional hazars model, the first\n% model will have less covariates than the second model.\n% \n% The censoring indicator ye is\n% \n% ye = 0 for uncensored event\n% ye = 1 for right censored event.\n% \n% Example data set is leukemia survival data in Northwest\n% England presented in (Henderson, R., Shimakura, S., and Gorst,\n% D. (2002). Modeling spatial variation in leukemia survival\n% data. Journal of the American Statistical Association,\n% 97:965–972). Data set was downloaded from\n% http://www.math.ntnu.no/%7Ehrue/r-inla.org/examples/leukemia/leuk.dat\n%\n% See also DEMO_SURVIVAL_COMPARISON2, DEMO_SURVIVAL_COXPH\n\n% Copyright (C) 2012 Ernesto Ulloa, Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n%% First load data\nS = which('demo_survival_weibull');\nL = strrep(S,'demo_survival_weibull.m','demodata/leukemia.txt');\nleukemiadata=load(L);\n\n% leukemiadata consists of:\n% 'time', 'cens', 'xcoord', 'ycoord', 'age', 'sex', 'wbc', 'tpi', 'district'\n\n% survival times\ny=leukemiadata(:,1);\n% scale survival times\ny=y/max(y);\n\nye=1-leukemiadata(:,2); % event indicator, ye = 0 for uncensored event\n % ye = 1 for right censored event\n\n% we choose for the first model: 'age' and 'sex'covariates\nx01=leukemiadata(:,5:6);\nx1=x01;\n\n% we choose for the second model: 'age', 'sex', 'wbc', and 'tpi' covariates\nx02=leukemiadata(:,5:8);\nx2=x02;\n\n% normalize continuous covariates \n\nx1(:,1)=normdata(x01(:,1));\nx2(:,[1 3:4])=normdata(x02(:,[1 3:4]));\n\n[n1, nin1]=size(x1);\n[n2, nin2]=size(x2);\n\n% number of time intervals\nntime=50;\n% create finite partition of time axis\nS=linspace(0,max(y)+0.001,ntime+1);\n\n%% obtain predictions\n\n% Create the covariance functions\npl = prior_t('s2',1, 'nu', 4);\npm = prior_t('s2',1, 'nu', 4); \n\n% covariance for hazard function\ngpcfh1 = gpcf_sexp('lengthScale', 1, 'magnSigma2', 1.1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\ngpcfh2 = gpcf_sexp('lengthScale', 1, 'magnSigma2', 1.1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n\n% covariance for proportional part\ngpcf1 = gpcf_sexp('lengthScale', ones(1,size(x1,2)), 'magnSigma2', 1.2, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\ngpcf2 = gpcf_sexp('lengthScale', ones(1,size(x2,2)), 'magnSigma2', 1.2, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n\n% Create the likelihood structure\nlik = lik_coxph('S', S);\n\ngp1 = gp_set('lik', lik, 'cf', {gpcfh1 gpcf1}, 'jitterSigma2', 1e-6, 'comp_cf', {[1] [2]});\ngp2 = gp_set('lik', lik, 'cf', {gpcfh2 gpcf2}, 'jitterSigma2', 1e-6, 'comp_cf', {[1] [2]});\n\n% Set the approximate inference method to Laplace\ngp1 = gp_set(gp1, 'latent_method', 'Laplace');\ngp2 = gp_set(gp2, 'latent_method', 'Laplace');\n\nopt=optimset('TolFun',1e-2,'TolX',1e-4,'Display','iter','Derivativecheck','off');\n\n% obtain predictions for both models using kfc-validation\n\n%* first we set tau\ntt=0.1:.1:1;\n\n% set D event indicator vector for each time in tt (Di=0 if i experienced\n% the event before tau and Di=1 otherwise)\n% Also we set YY, the observed time vector for each time value in tt \nfor i=1:size(tt,2)\n for i2=1:size(ye,1)\n if y(i2)>tt(i)\n yytemp(i2)=tt(i);\n Dtemp(i2)=1; \n else\n if ye(i2)==1\n Dtemp(i2)=1;\n else \n Dtemp(i2)=0;\n end\n yytemp(i2)=y(i2);\n end\n end\n yyi{i}=yytemp';\n Di{i}=Dtemp';\nend\nfor i=1:size(Di,2)\n D(:,i)=Di{i};\nend\nfor i=1:size(yyi,2)\n yy(:,i)=yyi{i};\nend\n\n\n% set time vector to make predictions\nyt=bsxfun(@times,ones(size(y)),tt);\n\n% Obtain predictions\n% (This takes several minutes)\ncrit1=gp_kfcv_cdf(gp1,x1,y,'z',D,'yt',yt,'opt',opt);\ncrit2=gp_kfcv_cdf(gp2,x2,y,'z',D,'yt',yt,'opt',opt);\n\n%% Calculate statics and compare models \n% MODEL COMPARISON\n\n%% AUC \n% AUC for Binary outcomes P(Pi>Pj | Di=1,Dj=0)\n[auc1,fps1,tps1]=aucs(crit1(:,length(tt)),D(:,length(tt)));\n[auc2,fps2,tps2]=aucs(crit2(:,length(tt)),D(:,length(tt)));\n\nfprintf('AUC at end of study for model 1: %.3f \\n', auc1);\nfprintf('AUC at end of study for model 2: %.3f \\n', auc2);\nhold on\nplot(fps1,tps1,'b')\nplot(fps2,tps2,'r')\ntitle('ROC curve')\nlegend('model 1', 'model 2',4)\nxlabel('False positives')\nylabel('True positives')\nhold off\n\n%% Harrell's C\n% Obtain for both models Binary AUC(t) = P(Pi>Pj | Di(t)=1,Dj(t)=0) and\n% Harrell's C(t) = P(Pi>Pj | Di(ti)=1, ti= J\n error('L must be smaller than dyadic index of x');\n end\n % We will work with row vectors in this function.\n col = false;\n if iscolumn(x)\n col = true;\n % Convert it to row vector\n x = x';\n end\n % Create the storage for wavelet coefficients.\n w = zeros(1, n);\n for j=J-1:-1:L\n % Start from the finest level and keep going down.\n % identify the hipass component of x and downsample it.\n c = spx.wavelet.hi_pass_down_sample(qmf, x);\n % Identify the locations where the hipass component will be stored.\n indices = spx.wavelet.dyad(j);\n w(indices) = c;\n % Replace x with its low pass downsampled version\n x = spx.wavelet.lo_pass_down_sample(qmf, x);\n end\n % Store the remaining contents of x in the beginning of array\n w(1:(2^L)) = x;\n if col\n % Convert the wavelet coefficients to a column vector\n w = w';\n end\n end\n\n function x = inverse_periodized_orthogonal(qmf, w, L)\n % Computes the inverse wavelet transform of x\n %\n % Uses the periodized version of x \n % with an orthogonal wavelet basis\n % length of x must be dyadic.\n if nargin < 3\n % We perform full wavelet composition\n L = 0;\n end\n\n % Let's get the dyadic length of w and verify that\n % length of w is a power of 2.\n [n, J, consistent] = spx.wavelet.dyad_length(w);\n if ~consistent\n error('w must be of dyadic length');\n end\n if L >= J\n error('L must be smaller than dyadic index of w');\n end\n % We will work with row vectors in this function.\n col = false;\n if iscolumn(w)\n col = true;\n % Convert it to row vector\n w = w';\n end\n % initialize x with its coerce approximation\n x = w(1:2^L);\n for j=L:J-1\n % Identify the locations where the hipass component is stored.\n indices = spx.wavelet.dyad(j);\n c = w(indices);\n % Compute the low pass portion of the next level of approximation\n x_low = spx.wavelet.up_sample_lo_pass(qmf, x);\n if iscolumn(x_low)\n x_low = x_low';\n end\n % Compute the high pass portion of the next level of approximation\n x_hi = spx.wavelet.up_sample_hi_pass(qmf, c);\n if iscolumn(x_hi)\n x_hi = x_hi';\n end\n % Compute the next level approximation of x\n x = x_low + x_hi;\n end\n if col\n % Convert the resulting vector to a column vector\n x = x';\n end\n end\n \nend\n\nend\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+wavelet/transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6358077069486342}} {"text": " function [xs, info] = l1_regress_admm1(yi, A, varargin)\n%|function [xs, info] = l1_regress_admm1(yi, A, varargin)\n%|\n%| l1 regression, minimizing cost function\n%| cost(x) = pot( y - A x ) where pot(r) = |r|_1 by default.\n%| minimized via ADMM algorithm with v = A x split.\n%|\n%| in\n%|\tyi\t[M 1]\t\tnoisy data\n%|\tA\t[M N]\t\tmatrix\n%|\n%| options\n%|\tx0\t[N 1]\t\tinitial estimate (default: A \\ yi)\n%|\tshrink\t\t\tshrink function for pot: shrink(x, reg)\n%|\t\t\t\t(default: l1, soft thresholding)\n%|\n%|\tniter\t\t\t# total iterations (default: 1)\n%|\t\t\t\t\t(max # if tol used)\n%|\tisave\t[]\t\tlist of iterations to archive (default: 'last')\n%|\tuserfun\t@\t\tuser defined function handle (see default below)\n%|\t\t\t\t\ttaking arguments (x, iter, userarg{:})\n%|\tuserarg {}\t\tuser arguments to userfun (default {})\n%|\tstop_diff_tol\t\tstop iterations if norm(xnew-xold)/norm(xnew)\n%|\t\t\t\tis less than this unitless value. default: 0\n%|\tstop_diff_norm\t\tuse norm(., type) for stop rule\n%|\t\t\t\tchoices: 1 | 2 (default) | inf\n%|\tchat\t0|1\t\tverbosity (default 0)\n%|\n%| out\n%|\txs\t[N niter]\testimates each iteration\n%|\tinfo\t[niter 1]\ttime each iteration (for default userfun)\n%|\n%| Copyright 2013-03-21, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(yi, 'test'), l1_regress_example, return, end\n\n% defaults\narg.x0 = [];\narg.C = [];\narg.beta = 1; % regularization parameter\narg.shrink = [];\narg.rho = 1; % AL penalty parameter\n\narg.niter = 1;\narg.isave = [];\narg.userfun = @userfun_default;\narg.userarg = {};\narg.stop_diff_tol = 0;\narg.stop_diff_norm = 2;\narg.chat = 0;\n\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.x0)\n\targ.x0 = A \\ yi;\nend\n\nx = arg.x0;\n\nif isempty(arg.shrink)\n\ttmp = potential_fun('l1', 1);\n\tshrink = @(z, reg) tmp.shrink(z, reg);\nelse\n\tshrink = arg.shrink;\nend\n\narg.isave = iter_saver(arg.isave, arg.niter);\nif arg.stop_diff_tol\n\tnorm_diff = @(x) norm(x(:), arg.stop_diff_norm);\nend\n\ncpu etic\n\nnp = numel(x);\nxs = zeros(np, length(arg.isave));\nif any(arg.isave == 0)\n\txs(:, arg.isave == 0) = x(:);\nend\n\neta = 0; % dual variable\n\nrho = arg.rho;\n\n% iterate\nfor iter = 1:arg.niter\n\tticker(mfilename, iter, arg.niter)\n\n\txp = x; % previous\n\n\t% update primal\n\tx = A \\ (yi + eta); \n\n\t% update auxiliary\n\ttmp = A * x - eta - yi;\n\tvv = yi + shrink(tmp, 1 / rho);\n\n\t% update multiplier\n\ttmp = A * x - vv;\n\teta = eta - tmp;\n\n\tif any(arg.isave == iter)\n\t\txs(:, arg.isave == iter) = x;\n\tend\n\tinfo(iter,:) = arg.userfun(x, iter, arg.userarg{:});\n\n\t% check norm(xnew-xold) / norm(xnew) vs threshold\n\tif iter > 1 && arg.stop_diff_tol\n\t\tratio = norm_diff(x - xp) / norm_diff(x);\n\t\tif ratio < arg.stop_diff_tol\n\t\t\tif 1 || arg.chat\n\t\t\t\tprintm('stop at iteration %d, diff %g < %g', ...\n\t\t\t\t\titer, ratio, arg.stop_diff_tol)\n\t\t\tend\n\t\t\tif isequal(arg.isave, arg.niter) % saving only last?\n\t\t\t\txs = x; % save the 'final' iterate\n\t\t\telse % saving many iterates?\n\t\t\t\txs(:, arg.isave > iter) = []; % clear out unused\n\t\t\tend\n\t\tbreak\n\t\tend\n\tend\nend\n\n\n% default user function.\n% using this evalin('caller', ...) trick, one can compute anything of interest\nfunction out = userfun_default(x, iter, varargin)\n%pr minmax(x)\nout = [cpu('etoc')];\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/l1_regress_admm1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6358076960059214}} {"text": "function [FxT_N, FyT_N] = TireModel(lambda_perc, alpha_rad, Fz_N, PacFrontLat, PacRearLat, PacFrontLong, PacRearLong)\n % Pacjeka tire model based on a four coefficient approach\n % evaluates the lateral and longitudinal tire forces using the specified \n % pacjeka models for front and rear \n \n % initialize\n FxT_N = zeros(4, 1); \n FyT_N = zeros(4, 1); \n \n FxT_N(1:2) = PacModel(lambda_perc(1:2)./100, PacFrontLong, Fz_N(1:2)); \n FxT_N(3:4) = PacModel(lambda_perc(3:4)./100, PacRearLong, Fz_N(3:4)); \n FyT_N(1:2) = PacModel(alpha_rad(1:2), PacFrontLat, Fz_N(1:2)); \n FyT_N(3:4) = PacModel(alpha_rad(3:4), PacRearLat, Fz_N(3:4)); \nend\n\nfunction F = PacModel(x, Pac, Fz_N) \n% evaluate the pacejka model for a given slip quantity x and pacejka coefficients Pac\n% http://www.edy.es/dev/docs/pacejka-94-parameters-explained-a-comprehensive-guide/\n\n% in addition, Pac(6) provides a factor load degressivity: eps_load <= 0\n\n F = Fz_N.*(Pac(3)+Pac(6)*((Fz_N-Pac(5))/Pac(5))).*sin(Pac(2).*atan(Pac(1).*x - Pac(4).*(Pac(1).*x - atan(Pac(1).*x)))); \n\nend\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/TireModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.6357524067729212}} {"text": "function [sigma,C] = calcBSImpVol(cp,P,S,K,T,r,q)\n%\n% [sigma,C] = calcBSImpVol(cp,P,S,K,T,r,q)\n%\n% Calculates Black-Scholes Implied Volatility Surface for an Option Price Matrix.\n% Uses Li's Rational Function Approximator for the Initial Estimate, followed by\n% 3rd-Order Householder's Root Finder (i.e. using vega,vomma & ultima) for greater \n% convergence rate and wider domain-of-convergence relative to Newton-Raphson. Both \n% Li's Approximator and the Root Finder are calculated matrix-wise (i.e.\n% fully vectorized) for increased efficiency.\n%\n%\n% Input Parameters\n% cp Call[+1],Put[-1] [m x n],[1 x 1]\n% P Option Price Matrix [m x n]\n% S Underlying Price [1 x 1]\n% K Strike Price [m x n]\n% T Time to Expiry [m x n]\n% r Continuous Risk-Free Rate [m x n],[1 x 1]\n% q Continuos Div Yield [m x n],[1 x 1]\n%\n% Output Parameters\n% sigma Implied Volatility [m x n]\n% C Convergence Flag [m x n]\n%\n%\n%\n% Example 1\n% S = 100; K = (40:25:160)'; T = (0.25:0.25:1)'; % Define Key Variables\n% r = 0.01; q = 0.03;\n% cp = 1; % i.e. call\n% P = ...\n% [[59.3526805861312,34.4154741312210,10.3406451776045,0.501199199160055,0.0101623685145268;];\n% [58.7107005379958,33.8563481863964,10.9917759513981,1.36915029885860,0.143324063090580;];\n% [58.0742593358310,33.3567195106962,11.5012247391034,2.12859686975881,0.400045353619436;];\n% [57.4444414750070,32.9126689586500,11.9027988146544,2.77274776123341,0.708059729236718;];];\n% [mK,mT] = meshgrid(K,T);\n% [sigma,C] = calcBSImpVol(cp,P,S,mK,mT,r,q);\n% mesh(mK,mT,sigma);\n%\n% Example 2\n% S = 100; K = (40:25:160)'; T = (0.25:0.25:1)'; % Define Key Variables\n% cp = [ones(4,3),-ones(4,2)]; % [Calls[4,3],Puts[4,2]]\n% R = 0.01*repmat([1.15;1.10;1.05;1],1,5); % \n% Q = 0.03*repmat([1.3;1.2;1.1;1],1,5);\n% P = ...\n% [[59.1445725607811,34.2167401269277,10.1798771553458,16.1224863211251,40.5779719086946];\n% [58.4355054500906,33.5945826994415,10.7977275764632,17.4776751735401,41.1533978186314];\n% [57.8694061672804,33.1636044111551,11.3636963648521,18.6294544130139,41.7369813312724];\n% [57.4444414750070,32.9126689586500,11.9027988146694,19.5839252875422,42.2704830992694]];\n% [mK,mT] = meshgrid(K,T);\n% [sigma,C] = calcBSImpVol(cp,P,S,mK,mT,R,Q);\n% mesh(mK,mT,sigma);\n% hold on; scatter3(mK(:),mT(:),sigma(:),60,[0,0,0],'filled'); hold off\n% xlabel('Strike'); ylabel('Expiry'); zlabel('Volatility');\n%\n% References:\n% 1) Li, 2006, \"You Don't Have to Bother Newton for Implied Volatility\"\n% http://papers.ssrn.com/sol3/papers.cfm?abstract_id=952727\n% 2) http://en.wikipedia.org/wiki/Householder's_method\n% 3) http://en.wikipedia.org/wiki/Greeks_(finance)\n%\n%% APPLY LI's RATIONAL-FUNCTION APPROXIMATOR\n[g,h] = size(P);\nif isscalar(r); r = r*ones(g,h); end\nif isscalar(q); q = q*ones(g,h); end\nif isscalar(cp); cp = cp*ones(g,h); end\np = [-0.969271876255; 0.097428338274; 1.750081126685];\nm = ones(1,1,14);\nm(:) = [...\n 6.268456292246;\n -6.284840445036;\n 30.068281276567;\n -11.780036995036;\n -2.310966989723;\n -11.473184324152;\n -230.101682610568;\n 86.127219899668;\n 3.730181294225;\n -13.954993561151;\n 261.950288864225;\n 20.090690444187;\n -50.117067019539;\n 13.723711519422];\nm = m(ones(g,1),ones(1,h),:); % Repmat to size [g,h]\nn = ones(1,1,14);\nn(:) = [...\n -0.068098378725;\n 0.440639436211;\n -0.263473754689;\n -5.792537721792;\n -5.267481008429;\n 4.714393825758;\n 3.529944137559;\n -23.636495876611;\n -9.020361771283;\n 14.749084301452;\n -32.570660102526;\n 76.398155779133;\n 41.855161781749;\n -12.150611865704];\nn = n(ones(g,1),ones(1,h),:); % Repmat to size [g,h]\ni = ones(1,1,14);\ni(:) = [0,1,0,1,2,0,1,2,3,0,1,2,3,4];\ni = i(ones(g,1),ones(1,h),:); % Repmat to size [g,h]\nj = ones(1,1,14);\nj(:) = [1,0,2,1,0,3,2,1,0,4,3,2,1,0];\nj = j(ones(g,1),ones(1,h),:); % Repmat to size [g,h]\nx = log(S.*exp((r-q).*(T))./K); % Calculate Normalized Moneyness Measure\nP(cp==-1) = P(cp==-1) + S.*exp(-q(cp==-1).*T(cp==-1)) - K(cp==-1).*exp(-r(cp==-1).*T(cp==-1)); % Convert Put to Call by Parity Relation\nc = P./(S.*exp(-q.*(T))); % Normalized Call Price\nx = x(:,:,ones(1,14)); % Repmat to 3d size 14\nc = c(:,:,ones(1,14)); % Repmat to 3d size 14\n% Rational Function - Eqn(19) of Li 2006\nfcnv = @(p,m,n,i,j,x,c)(p(1).*x(:,:,1) + p(2).*sqrt(c(:,:,1)) + p(3).*c(:,:,1) + (sum(n.*((x.^i).*(sqrt(c).^j)),3))./(1 + sum(m.*((x.^i).*(sqrt(c).^j)),3)));\nv1 = fcnv(p,m,n,i,j,x,c); % D- Domain (x<=-1)\nv2 = fcnv(p,m,n,i,j,-x,exp(x).*c + 1 -exp(x)); % Reflection for D+ Domain (x>1)\nv = zeros(g,h); v(x(:,:,1)<=0)=v1(x(:,:,1)<=0); v(x(:,:,1)>0)=v2(x(:,:,1)>0);\n% Domain-of-Approximation is x={-0.5,+0.5},v={0,1},x/v={-2,2}\ndomainFilter = x(:,:,1)>=-0.5 & x(:,:,1)<=0.5 & v > 0 & v <1 & (x(:,:,1)./v)<=2 & (x(:,:,1)./v)>=-2;\nsigma = v./sqrt(T); % v = sigma.*(sqrt(T));\nsigma(~domainFilter) = 0.8; % use 0.8 arbtrarily as best vol-guess for out-of-domain points\n%% HOUSEHOLDER ROOT-FINDER FOR INCREASED CONVERGENCE \nd1fcn = @(sig,C)((log(S./K(C)) + (r(C)-q(C)+sig(C).^2*0.5).*(T(C)))./(sig(C).*sqrt(T(C))));\nd2fcn = @(sig,C)((log(S./K(C)) + (r(C)-q(C)-sig(C).^2*0.5).*(T(C)))./(sig(C).*sqrt(T(C))));\ncallfcn = @(sig,C)( +exp(-q(C).*T(C)).*S.*fcnN(d1fcn(sig,C)) - exp(-r(C).*T(C)).*K(C).*fcnN(d2fcn(sig,C)) );\nvegafcn = @(sig,C)(S.*exp(-q(C).*(T(C))).*fcnn(d1fcn(sig,C)).*(sqrt(T(C)))); \nvommafcn = @(sig,C)(S.*exp(-q(C).*(T(C))).*fcnn(d1fcn(sig,C)).*(sqrt(T(C))).*d1fcn(sig,C).*d2fcn(sig,C)./sig(C));\nultimafcn = @(sig,C)(-S.*exp(-q(C).*(T(C))).*fcnn(d1fcn(sig,C)).*(sqrt(T(C))).*(d1fcn(sig,C).*d2fcn(sig,C).*(1-d1fcn(sig,C).*d2fcn(sig,C))+d1fcn(sig,C).^2+d2fcn(sig,C).^2)./(sig(C).^2));\ntolMat=1e-12;\nk_max = 10; % 10 Householder Iterations\nobjfcn = @(sig,C)(P(C) - callfcn(sig,C));\nC = true(size(P(:))); err = objfcn(sigma,C); % calculate initial error\nC = abs(err)>tolMat; % Convergence Matrix\nk = 1; % Initialize Count\nwhile any(C) && k<=k_max % Iterate until sooner of Convergence or Count-limit\n \n % Calculate Derivatives (Greeks)\n vega = vegafcn(sigma,C); %f'(x_n)\n vomma = vommafcn(sigma,C); %f''(x_n)\n ultima = ultimafcn(sigma,C); %f'''(x_n)\n% % Newton Raphson Method x_n+1 = x_n + f(x_n)/f'(x_n)\n% sigma = sigma + (err(C)./vega) ;\n% % Halley Method x_n+1 = x_n - f(x_n)/( f'(x_n) - f(x_n)*f''(x_n)/2*f'(x_n))\n% sigma = sigma - err(C)./(-vega-(-err(C).*vomma./(-2.*vega)));\n % Householder Method x_n+1 = x_n - f(x_n)/( f'(x_n) - f(x_n)*f''(x_n)/2*f'(x_n))\n sigma(C) = sigma(C) - (6.*err(C).*vega.^2 + 3.*err(C).^2.*vomma)./(-6.*vega.^3 - 6.*err(C).*vega.*vomma - err(C).^2.*ultima);\n \n % Update Error\n err(C) = objfcn(sigma,C); %\n \n % Ascertain Convergence to Tolerance\n C = abs(err)>tolMat; % Convergence Matrix\n \n % Increment Count\n k = k + 1;\nend\nsigma(C) = NaN; % any remaining sigma are not worth calculating\nend\n%% Gaussian Subfunctions\nfunction p=fcnN(x)\np=0.5*(1.+erf(x./sqrt(2)));\nend\n%\nfunction p=fcnn(x)\np=exp(-0.5*x.^2)./sqrt(2*pi);\nend", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Utils/calcBSImpVol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6357093177008035}} {"text": "function [hl,ht,hp,ha] = visualize_rotations(rotorder,rotangle_deg,axhandle)\n\n% FUNCTION\n% [hl,ht,hp,ha] = visualize_rotations(rotorder,rotangle_deg,axhandle)\n%\n% DESCRIPTION\n% Visualize Euler rotation sequences by displaying rotated axes systems {E_r}\n% and rotation planes, where {E_r} is the orthonormal set of vectors [i_r; j_r; k_r]\n%\n% INPUT ARGUMENTS\n% rotorder = string containing order of rotations, e.g. 'zxy' or 'xyx'\n% rotangle_deg = vector of rotation angles corresponding to rotorder [degrees]\n% axhandle = optional handle to existing axes\n%\n% OUTPUT ARGUMENTS\n% hl = 3-by-n+1 matrix of line handles for the x,y,z-axes for E0 to En\n% ht = same for axis text labels\n% hp = 3-by-n matrix of handles to the colored patches\n% ha = handle to annotation\n%\n% EXAMPLE:\n% visualize_rotations('xzxyz',[25 25 -25 45 10]) \n% \n% or call the function without input arguments to show an example\n%\n%\n% Author: D.J. van Gerwen\n% Created: 22-Feb-2011\n% Revised: 13-Jun-2013\n\n% Process input arguments\nif nargin<2\n rotangle_deg = [25 35 -35]; % [deg]\nend\nif nargin<1\n rotorder = 'yzx';\nend\n\n% Parameters\nlw = 1;\nfs = 9;\nbgc = 'none';\nxyztxt = 'xyz';\nxlim = [-1 1];\nylim = xlim;\nzlim = xlim;\nazel = [135,30]; % Azimuth and elevation of view\n\n% Convert angles\nrotangle_rad = rotangle_deg/180*pi; % [-]\n\n% Define rotation matrices for {E_i+1}=[R]{E_i} as inline functions (based on right-hand rule)\nRx = inline('[1 0 0; 0 cos(x) sin(x); 0 -sin(x) cos(x)]'); % Rotation about x-axis by angle x\nRy = inline('[cos(y) 0 -sin(y); 0 1 0; sin(y) 0 cos(y)]'); % Rotation about y-axis by angle y\nRz = inline('[cos(z) sin(z) 0; -sin(z) cos(z) 0; 0 0 1]'); % Rotation about z-axis by angle z\n\n% Define global reference system\nE = [1 0 0; % i0\n 0 1 0; % j0\n 0 0 1]; % k0 (could use eye(3), but that is less informative)\n\n% Apply transformations: {E1}=[R1]{E0}, {E2}=[R2]{E1}=[R2][R1]{E0}, etc\nfor r = 1:length(rotorder)\n switch rotorder(r)\n case 'x'\n % Evaluate rotation matrix\n Rr(:,:,r) = Rx(rotangle_rad(r));\n % Define patch\n pv(:,:,r) = [[0 1 0].*Rr(2,:,r); Rr(2,:,r); [0 0 1].*Rr(2,:,r);\n [0 0 1].*Rr(3,:,r); Rr(3,:,r); [0 1 0].*Rr(3,:,r)]; % NOTE: to show triangles, set the third and sixth row to zero\n case 'y'\n % Evaluate rotation matrix\n Rr(:,:,r) = Ry(rotangle_rad(r));\n % Define patch\n pv(:,:,r) = [[1 0 0].*Rr(1,:,r); Rr(1,:,r); [0 0 1].*Rr(1,:,r);\n [0 0 1].*Rr(3,:,r); Rr(3,:,r); [1 0 0].*Rr(3,:,r)]; % NOTE: to show triangles, set the third and sixth row to zero\n case 'z'\n % Evaluate rotation matrix\n Rr(:,:,r) = Rz(rotangle_rad(r));\n % Define patch\n pv(:,:,r) = [[1 0 0].*Rr(1,:,r); Rr(1,:,r); [0 1 0].*Rr(1,:,r);\n [0 1 0].*Rr(2,:,r); Rr(2,:,r); [1 0 0].*Rr(2,:,r)]; % NOTE: to show triangles, set the third and sixth row to zero\n end\n % Transformation to E0\n E(:,:,r+1) = Rr(:,:,r)*E(:,:,r);\nend\n\n% Initialize figure\nif ~exist('axhandle','var')\n figure('color','white','numbertitle','off','name','Visualize Euler rotation sequence')\n set(gca,'xlim',xlim,'ylim',ylim,'zlim',zlim,'projection','orthographic') % NOTE: projection is either 'orthographic' or 'perspective'\n view(azel)\n axis off\n title(sprintf(['Rotation sequence: %s (%3.0f\\\\circ' repmat(',%3.0f\\\\circ',1,length(rotorder)-1) ')'],rotorder,rotangle_deg))\nelse\n axes(axhandle)\nend\n%cmp = colormap(lines);\ncmp = [1 0 0; 0 0.5 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1];\n\n% Display global reference system {E0} and rotated reference systems {E.}\nfor r = 1:length(rotorder)+1\n for i = 1:3\n % Axis and label\n hl(i,r) = line([0 E(i,1,r)],[0 E(i,2,r)],[0 E(i,3,r)],'color','k','linewidth',lw);\n ht(i,r) = text('position',E(i,:,r),'string',sprintf('%s_%u',xyztxt(i),r-1),'fontsize',fs,'backgroundcolor',bgc);\n % Create patches\n if r<=length(rotorder)\n pvr = pv(:,:,r);\n for rr = r-1:-1:1\n pvr = pvr*Rr(:,:,rr); % Transform patch vector from local to global reference\n end\n hp(i,r) = patch(pvr(:,1),pvr(:,2),pvr(:,3),cmp(r,:),'edgecolor','none','facealpha',0.1);\n end\n end\nend\n\n% Correct axis labels for the rotation axes\nfor i = 1:3\n for r = strfind(rotorder,xyztxt(i))\n str1 = get(ht(i,r),'string');\n str2 = get(ht(i,r+1),'string');\n set(ht(i,r+1),'string',[str1 ',' str2])\n end\nend\n\n% Text\nha = annotation('textbox',[0.4 0 0.6 0.14],'string',{'Colored patches represent components of the local rotation matrix in the plane of rotation. Definitions are according to right-hand rule.'},'edgecolor','none');", "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/42229-visualize-euler-rotations/visualize_rotations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6356752049702674}} {"text": "function [X_den,P]=denoise_TV_One(Xobs,lambda,l,u,P_init,pars)\n%This function implements the FISTA method for TV denoising problems. \n%\n% INPUT\n% Xobs ..............................an observed noisy image.\n% lambda ........................ parameter\n% pars.................................parameters structure\n% pars.MAXITER ..................... maximum number of iterations\n% (Default=100)\n% pars.epsilon ..................... tolerance for relative error used in\n% the stopping criteria (Default=1e-4)\n% pars.print .......................... 1 if a report on the iterations is\n% given, 0 if the report is silenced\n% pars.tv .................................. type of total variation\n% penatly. 'iso' for isotropic (default)\n% and 'l1' for nonisotropic\n% \n% OUTPUT\n% X_den ........................... The solution of the problem \n% min{||X-Xobs||^2+2*lambda*TV(X)}\n\n\n%Define the Projection onto the box\nif((l==-Inf)&&(u==Inf))\n project=@(x)x;\nelseif (isfinite(l)&&(u==Inf))\n project=@(x)(((l=u)*u));\nelseif ((isfinite(u)&&isfinite(l))&&(l=u)*u)+(l*(x<=l));\nelse\n error('lower and upper bound l,u should satisfy l0 so that the swivel angle\n% is added as an an extra dimension, with phi = \n% median human range +/- step increments up to the\n% human limits. The swivel angle increases with \n% the increasing index of the extra dimension.\n% (4) PHI : PHI uses an explicit value, the number of elements\n% in PHI must be a multiple of the number of hand \n% points/frames\n%\n% See also h2fsu HAL.gikine HAL.wikine\n\n% LICENSE STATEMENT:\n%\n% This file is part of pHRIWARE.\n% \n% pHRIWARE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as \n% published by the Free Software Foundation, either version 3 of \n% the License, or (at your option) any later version.\n%\n% pHRIWARE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public \n% License along with pHRIWARE. If not, see .\n%\n% RTB LIBRARY:\n%\n% Copyright (C) 1993-2014, by Peter I. Corke\n% http://www.petercorke.com\n% Released under the GNU Lesser General Public license,\n% Modified 16/6/2014 (HAL is a subclass of SerialLink)\n\nfunction [q1, q2] = ikine(hal, Th, phi)\n\nif nargin == 2\n [Tf, ~, Tu] = hal.h2fsu(Th);\nelse\n [Tf, ~, Tu] = hal.h2fsu(Th, phi);\nend\n\n[q1g, q2g] = hal.gikine(Tu);\n\nqe = squeeze(pi/2 - acos(dot(Tu(1:3,2,:),Tf(1:3,1,:))));\n\n[q1w, q2w] = wikine(Th, Tf);\n\nq1 = [q1g, qe, q1w];\nq2 = [q2g, qe, q2w];\n\nend\n\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/contrib/pHRIWARE/Classes/@HAL/ikine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6355441943693486}} {"text": "% Figure 4.9 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n% Figure 4.9 PID control of motor speed\n% function [np, dp]= pid(b,J,K,L,R,kp,ki,kd)\n% function to compute the equations of a d.c. motor with inductance.\n% and compute the response under control\nclf;\nK=.0670; L1=0.1; J1=0.0113; R=0.45; b=0.0280;\nkp=3; ki= 15; kd=0.3;\nnp=K;\ndp=[L1*J1 R*J1+b*L1 R*b+K*K];\ndclp=[L1*J1 R*J1+b*L1 R*b+K*K+K*kp];\nnclp=K*kp;\nnclpw=[L1 R];\ndclpi=[L1*J1 R*J1+b*L1 R*b+K*K+K*kp K*ki];\nnclpi=[K*kp K*ki];\nnclpiw=[L1 R 0];\ndclpid=[ L1*J1 R*J1+b*L1+K*kd R*b+K*K+K*kp K*ki];\nnclpid=[K*kd K*kp K*ki];\nnclpidw=[L1 R 0];\nsysp=tf(nclp,dclp);\nsyspw=tf(nclpw,dclp);\nsyspi=tf(nclpi,dclpi);\nsyspiw=tf(nclpiw,dclpi);\nsyspid=tf(nclpid,dclpid);\nsyspidw=tf(nclpidw,dclpid);\nfigure(1)\nt=0:.01:6;\n[y1w,t]=step(syspw,t);\n[y2w,t]=step(syspiw,t);\n[y3w,t]=step(syspidw,t);\nplot(t,y1w,t,y2w,t,y3w);\nxlabel('Time (msec)');\nylabel('Amplitude');\ntitle('Fig. 4.9(a) Response of P,PI, and PID control to a disturbance step')\ngtext('P')\ngtext('PI')\ngtext('PID')\nnicegrid;\n\nfigure(2)\n[y1,t]=step(sysp,t);\n[y2,t]=step(syspi,t);\n[y3,t]=step(syspid,t);\nplot(t,y1,t,y2,t,y3);\nxlabel('Time (msec)');\nylabel('Amplitude');\ntitle('Fig. 4.9 (b) Response of P,PI, and PID control to a reference step')\ngtext('P')\ngtext('PI')\ngtext('PID')\nnicegrid;", "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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig4_09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6355441885187297}} {"text": "function [R]=hist2res(H,fun)\n% Evaluates Histogram data\n% [R]=hist2res(H)\n%\n% [y]=hist2res(H,fun)\n%\testimates fun-statistic\n%\n% fun\t'mean'\tmean\n%\t'std'\tstandard deviation\n%\t'var'\tvariance\n%\t'sem'\tstandard error of the mean\n%\t'rms'\troot mean square\n%\t'meansq' mean of squares\n%\t'sum'\tsum\n%\t'sumsq'\tsum of squares\n%\t'CM#'\tcentral moment of order #\n%\t'skewness' skewness \n%\t'kurtosis' excess coefficient (Fisher kurtosis)\n%\n% see also: NaN/statistic\n%\n% REFERENCES:\n% [1] C.L. Nikias and A.P. Petropulu \"Higher-Order Spectra Analysis\" Prentice Hall, 1993.\n% [2] C.E. Shannon and W. Weaver \"The mathematical theory of communication\" University of Illinois Press, Urbana 1949 (reprint 1963).\n% [3] http://www.itl.nist.gov/\n% [4] http://mathworld.wolfram.com/\n\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n%\t$Id: hist2res.m 2202 2009-10-27 12:06:45Z schloegl $\n%\tCopyright (c) 1996-2002,2006 by Alois Schloegl \n% \tThis is part of the BIOSIG-toolbox http://biosig.sf.net/\n\n\nif strcmp(H.datatype,'HISTOGRAM')\n\nelseif strcmp(H.datatype,'qc:histo')\n\tHDR = H; \n\tif isfield(H,'THRESHOLD'),\n\t\tTH = H.THRESHOLD;\n\telse\n\t\tTH = repmat([-inf,inf],HDR.NS,1); \n\tend;\n\tHIS = H.HIS; \n\n\t% remove overflowing samples\n\tHIS.N = sumskipnan(HIS.H); \n\tfor k = 1:size(HIS.H,2);\n\t\tt = HIS.X(:,min(k,size(HIS.X,2))); \n\t\tHIS.H(xor(t<=min(TH(k,:)), t>=max(TH(k,:))),k) = 0; \n\tend; \n\tNnew = sumskipnan(HIS.H); \n\tR.ratio_lost = 1-Nnew./HIS.N;\n\tHIS.N = Nnew; \n\t \n\t% scale into physical values\n\tif H.FLAG.UCAL,\n\t\t%t = HIS.X;\n\t\t%for k=1:length(HDR.InChanSelect),\n\t\t%\tHIS.X(:,k) = t(:,min(size(t,2),k))*HDR.Calib(k+1,k)+HDR.Calib(1,k);\n\t\t%end;\n\t\tHIS.X = [ones(size(HIS.X,1),1),repmat(HIS.X,1,size(HIS.H,2)./size(HIS.X,2))]*H.Calib;\n\tend; \t\n\tH = HIS; \nelse\n fprintf(2,'ERROR: arg1 is not a histogram\\n');\n return;\nend;\nif nargin<2, fun=[]; end;\n\nglobal FLAG_implicit_unbiased_estimation; \n%%% check whether FLAG was already defined \nif exist('FLAG_implicit_unbiased_estimation')~=1,\n\tFLAG_implicit_unbiased_estimation=[];\nend;\n%%% set DEFAULT value of FLAG\nif isempty(FLAG_implicit_unbiased_estimation),\n\tFLAG_implicit_unbiased_estimation=logical(1);\nend;\n\nsz \t= size(H.H)./size(H.X);\nR.N \t= sumskipnan(H.H,1);\nR.SUM \t= sumskipnan(H.H.*repmat(H.X,sz),1);\nR.SSQ \t= sumskipnan(H.H.*repmat(H.X.*H.X,sz),1);\n%R.S3P \t= sumskipnan(H.H.*repmat(H.X.^3,sz),1);\t% sum of 3rd power\nR.S4P \t= sumskipnan(H.H.*repmat(H.X.^4,sz),1);\t% sum of 4th power\n%R.S5P \t= sumskipnan(H.H.*repmat(H.X.^5,sz),1);\t% sum of 5th power\n\nR.MEAN\t= R.SUM./R.N;\nR.MSQ = R.SSQ./R.N;\nR.RMS\t= sqrt(R.MSQ);\nR.SSQ0 = R.SSQ-R.SUM.*R.MEAN;\t\t% sum square of mean removed\n\nif FLAG_implicit_unbiased_estimation,\n n1 \t= max(R.N-1,0);\t\t\t% in case of n=0 and n=1, the (biased) variance, STD and STE are INF\nelse\n n1\t= R.N;\nend;\n\nR.VAR \t= R.SSQ0./n1;\t \t\t% variance (unbiased) \nR.STD \t= sqrt(R.VAR);\t\t \t% standard deviation\nR.SEM \t= sqrt(R.SSQ0./(R.N.*n1)); \t% standard error of the mean\nR.SEV\t= sqrt(n1.*(n1.*R.S4P./R.N+(R.N.^2-2*R.N+3).*(R.SSQ./R.N).^2)./(R.N.^3)); % standard error of the variance\nR.Coefficient_of_variation = R.STD./R.MEAN;\n\nR.CM2\t= R.SSQ0./n1;\nx = repmat(H.X,sz) - repmat(R.MEAN,size(H.X,1),1);\nR.CM3 \t= sumskipnan(H.H.*(x.^3),1)./n1;\nR.CM4 \t= sumskipnan(H.H.*(x.^4),1)./n1;\n%R.CM5 \t= sumskipnan(H.H.*(x.^5),1)./n1;\n\nR.SKEWNESS = R.CM3./(R.STD.^3);\nR.KURTOSIS = R.CM4./(R.VAR.^2)-3;\nR.MAD = sumskipnan(H.H.*abs(x),1)./R.N; % mean absolute deviation\n\nH.PDF = H.H./H.N(ones(size(H.H,1),1),:);\nstatus=warning('off'); \nR.ENTROPY = -sumskipnan(H.PDF.*log2(H.PDF),1);\nwarning(status); \nR.QUANT = repmat(min(diff(H.X,[],1)),1,size(H.H,2)/size(H.X,2));\nR.MAX = max(H.X); \nR.MIN = min(H.X); \nR.RANGE = R.MAX-R.MIN;\n\nif ~isempty(fun),\n fun=upper(fun);\n if strncmp(fun,'CM',2) \n oo = str2double(fun(3:length(fun)));\n R = sumskipnan(H.PDF.*(x.^oo),1);\n \telse\t \n\t\tR = getfield(R,fun);\n\tend;\nend;\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/external/biosig-partial/t250_ArtifactPreProcessingQualityControl/hist2res.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6355111147956388}} {"text": "function Q=QTaylor(deltaT,xCur,curT,D,dadx,method)\n%%QTAYLOR Get the process noise covariance under a nonlinear continuous-\n% time random process specified by the Langevin equation forward in\n% time by a step-size of deltaT using a Taylor scheme with additive\n% noise.\n%\n%INPUTS: deltaT The size of the single step over which to generate the\n% process noise covariance matrix.\n% xCur The initial target state at time curT.\n% curT The time of the initial state xCur.\n% D The diffusion function in the continuous-time stochastic\n% dynamic model. It takes the state and a time variable as\n% its arguments, D(x,t). Since the process noise must be\n% additive, D(x,t) should not depend on x.\n% dadx A xDimXxDim matrix of the derivative of the drift function\n% with respect to the state at state xCur and time curT.\n% This can also be a function that takes the state and a time\n% variable as its arguments, dadx(x,t).\n% method Set to 0 for the shorter Euler-Maruyama expansion, 1 for\n% the order 1.5 strong Taylor (default), and 2 for the order\n% 2.0 weak Taylor.\n%\n%OUTPUTS: Q The process noise covariance matrix under a nonlinear\n% continuous-time random process specified by the Langevin\n% equation forward in time by a step-size of deltaT using a\n% strong Taylor scheme with additive noise.\n%\n%The process noise covariance matrix is derived from the stochastic order\n%1.5 Taylor scheme with additive noise described in 10.4 of [1].\n%\n%REFERENCES:\n%[1] P. E. Kloeden and E. Platen, Numerical Solution of Stochastic\n% Differential Equations. Berlin: Springer, 1999.\n%\n%April 2015 David Karnick, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isa(dadx,'function_handle'))\n dadx=dadx(xCur,curT);\nend\nif(nargin<6||isempty(method))\n method=1;\nend\n\nDCur=D(xCur,curT);\n\nif(method==0)\n Q=deltaT*(DCur*DCur.');\nelse\n term1=deltaT*(DCur*DCur.');\n term2=(deltaT^2/2)*(DCur*(dadx*DCur).'+(DCur*(dadx*DCur).').');\n if(method==1)\n term3=(deltaT^3/3)*(dadx*DCur)*((dadx*DCur).');\n elseif(method==2)\n term3=(deltaT^3/4)*(dadx*DCur)*((dadx*DCur).');\n end\n \n Q=term1+term2+term3;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Models/Discrete_Time/Process_Noise_Covariance_Matrices/QTaylor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6355111006334841}} {"text": "function [xUpdate,MUpdate,DUpdate,innov,Pzz,W]=reducedStateUpdate(xPred,PPred,MPred,DPred,z,R,H)\n%%REDSTATEFILTERUPDATE Perform the measurement update step in the reduced\n% state estimator. This is a filter that takes measurements\n% in Cartesian coordinates and assumes that the dynamic model\n% includes an unknown parameter that is somehow bounded, but\n% whose contribution is modeled with a mean and covariance\n% matrix. The filter separates contributions due to\n% measurement errors and dynamic model mismatch errors.\n%\n%INPUTS: xPred The xDimX1 predicted state estimate.\n% PPred The xDimXxDim predicted total state covariance estimate.\n% This is provided by the state prediction step.\n% MPred The xDimXxDim matrix contributing to the total predicted\n% state covariance matrix based solely on measurement errors.\n% DPred The xDimXzDim matrix of bias coefficients that are supposed\n% to relate target state errors to dynamic model parameter\n% uncertainty.\n% z The zDimX1 measurement vector.\n% R The zDimXzDim measurement covariance matrix.\n% H The optional zDimXxDim measurement matrix. The measurement\n% is modeled as z=H*x+noise. If this parameter is omitted or\n% an empty matrix is passed, then H will be taken as a\n% zDimXxDim identity matrix followed by columns of zeros\n% (Assuming that zDim<=xDim. Otherwise, H must be provided).\n%\n%OUTPUTS: xUpdate The xDimX1 updated state estimate.\n% MUpdate The xDimXxDim updated state covariance matrix\n% contribution due to measurement errors.\n% DUpdate The xDimXzDim matrix of updated bias coefficients\n% contributing to the state covariance matrix.\n% innov, Pzz The zDimX1 innovation and a zDimXzDim matrix Pzz that is\n% akin to an innovation covariance matrix are returned in\n% case one wishes to analyze the consistency of the\n% estimator or use those values in gating or likelihood\n% evaluation.\n% W The gain used in the update. This can be useful when\n% gating and using the function calcMissedGateCov.\n%\n%The filter is taken from [1]. Other applications are described in [1].\n%Note that the formulation of the dynamic model requires that the\n%dimensionality of the measurements does not vary.\n%\n%In [1] and [2], no clear method of initializing this type of tracking\n%filter is provided. A simple way to initialize the filter would be to use\n%two Cartesian converted measurements to obtain a state estimate and\n%covariance as one would do with a normal Kalman filter (one could, for\n%example, use the KalmanFIRSmoother function) and then set MPrev to the\n%covariance value obtained while setting DPrev to zero.\n%\n%REFERENCES:\n%[1] P. Mookerjee and F. Reifler, \"Reduced state estimator for systems with\n% parametric inputs,\" IEEE Transactions on Aerospace and Electronic\n% Systems, vol. 40, no. 2, pp. 446-461, Apr. 2004.\n%[2] P. Mookerjee and F. Reifler, \"Reduced state estimators for consistent\n% tracking of maneuvering targets,\" IEEE Transactions on Aerospace and\n% Electronic Systems, vol. 41, no. 2, pp. 608-619, Apr. 2005.\n%\n%July 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nxDim=size(xPred,1);\n\nif(nargin<7||isempty(H))\n\tzDim=size(z,1); \n H=[eye(zDim,zDim),zeros(zDim,xDim-zDim)];\nend\n\n%Equation 20 in [1].\nPzz=H*PPred*H'+R;\n\n%Ensure symmetry\nPzz=(Pzz+Pzz')/2;\n\nW=PPred*H'/Pzz;\nL=eye(xDim,xDim)-W*H;\n\n%Equation 23 in [1].\nMUpdate=L*MPred*L'+W*R*W';\n\n%Ensure symmetry\nMUpdate=(MUpdate+MUpdate')/2;\n\n%Equation 24 in [1].\nDUpdate=L*DPred;\n\ninnov=z-H*xPred;\n%Equation 26 in [1].\nxUpdate=xPred+W*innov;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Measurement_Update/Complete_Measurement_Updates/Specialized_Update_Routines/reducedStateUpdate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6355068034312613}} {"text": "function plotsid(t,iflaws,k); \n%PLOTSID Schematic interference diagram of FM signals. \n%\tPLOTSID(T,IFLAWS,K) plots the schematic interference diagram of \n%\t(analytic) FM signals. \n% \n%\tT : time instants, \n%\tIFLAWS : matrix of instantaneous frequencies, \n%\t with as may columns as signal components. \n%\tK : distribution\t\t(default : 2): \n%\t K = 2 : Wigner-Ville \n%\t K = 1/2 : D-Flandrin\n%\t K = 0 : Bertrand (unitary) \n%\t K = -1 : Unterberger (active)\n%\t K = inf : Margenhau-Hill-Rihaczek\n% \n%\tExample : \n%\t Nt=90; [y,iflaw]=fmlin(Nt,0.05,0.25); \n%\t [y2,iflaw2]=fmconst(50,0.4); \n%\t iflaw(:,2)=[NaN*ones(10,1);iflaw2;NaN*ones(Nt-60,1)]; \n%\t plotsid(1:Nt,iflaw,0); \n% \n%\tSee also PLOTIFL, MIDPOINT.\n\n%\tP. Flandrin, September 1995.\n%\tCopyright (c) 1996 by CNRS (France).\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin==1),\n error('at least 2 parameters : t and iflaws');\nelseif (nargin==2),\n k=2; % Wigner-Ville\nend;\n\nindices=find(1-isnan(iflaws));\nif (min(iflaws(indices))<0)|(max(iflaws(indices))>0.5),\n error ('each element of IFLAWS must be between 0 and 0.5');\nend;\n\n[iflawrow,iflawcol]=size(iflaws);\ntcol=length(t);\nclf; figure(gcf); plotifl(t,iflaws); \nhold on;\ncol=['b','m','c','r'];\n\n% auto-terms\nfor j=1:iflawcol,\n indices=find(1-isnan(iflaws(:,j)));\n Nbpoints=length(indices);\n for i=1:Nbpoints-1,\n ta= t(indices(i)) *ones(1,Nbpoints-i); \n fa= iflaws(indices(i),j)*ones(1,Nbpoints-i);\n tb= t(indices(i+1:Nbpoints));\n fb=iflaws(indices(i+1:Nbpoints),j)';\n [ti,fi]=midscomp(ta,fa,tb,fb,k);\n plot(ti,fi,['.',num2str(col(rem(j-1,4)+1))]);\n end;\nend;\n\n% cross-terms\nfor j1=1:iflawcol,\n indices1=find(1-isnan(iflaws(:,j1)));\n Nbpoints1=length(indices1);\n for j2=j1+1:iflawcol,\n indices2=find(1-isnan(iflaws(:,j2)));\n Nbpoints2=length(indices2);\n for i=1:Nbpoints1,\n ta= t(indices1(i)) *ones(1,Nbpoints2); \n fa= iflaws(indices1(i),j1)*ones(1,Nbpoints2);\n tb= t(indices2);\n fb=iflaws(indices2,j2)'; \n [ti,fi]=midscomp(ta,fa,tb,fb,k);\n plot(ti,fi,'.g') \n end;\n end;\nend;\n\nhold off\naxis([t(1) t(tcol) 0 0.5]);\ngrid\nif k==2,\n dist=' of the Wigner-Ville distribution';\nelseif k==1/2,\n dist=' of the D-Flandrin distribution';\nelseif k==0,\n dist=' of the (unitary) Bertrand distribution';\nelseif k==-1,\n dist=' of the (active) Unterberger distribution';\nelseif k>1/sqrt(eps),\n dist=' of the Margenhau-Hill-Rihaczek distribution';\nelse\n dist='';\nend\n\ntitle(['Interference diagram',dist,' (k = ',num2str(k),')']);\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/mfiles/plotsid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.635506789802188}} {"text": "function [x,y] = sample_lds(F, H, Q, R, init_state, T, models, G, u)\n% SAMPLE_LDS Simulate a run of a (switching) stochastic linear dynamical system.\n% [x,y] = switching_lds_draw(F, H, Q, R, init_state, models, G, u)\n% \n% x(t+1) = F*x(t) + G*u(t) + w(t), w ~ N(0, Q), x(0) = init_state\n% y(t) = H*x(t) + v(t), v ~ N(0, R)\n%\n% Input:\n% F(:,:,i) - the transition matrix for the i'th model\n% H(:,:,i) - the observation matrix for the i'th model\n% Q(:,:,i) - the transition covariance for the i'th model\n% R(:,:,i) - the observation covariance for the i'th model\n% init_state(:,i) - the initial mean for the i'th model\n% T - the num. time steps to run for\n%\n% Optional inputs:\n% models(t) - which model to use at time t. Default = ones(1,T)\n% G(:,:,i) - the input matrix for the i'th model. Default = 0.\n% u(:,t) - the input vector at time t. Default = zeros(1,T)\n%\n% Output:\n% x(:,t) - the hidden state vector at time t.\n% y(:,t) - the observation vector at time t.\n\n\nif ~iscell(F)\n F = num2cell(F, [1 2]);\n H = num2cell(H, [1 2]);\n Q = num2cell(Q, [1 2]);\n R = num2cell(R, [1 2]);\nend\n\nM = length(F);\n%T = length(models);\n\nif nargin < 7,\n models = ones(1,T);\nend\nif nargin < 8,\n G = num2cell(repmat(0, [1 1 M]));\n u = zeros(1,T);\nend\n\n[os ss] = size(H{1});\nstate_noise_samples = cell(1,M);\nobs_noise_samples = cell(1,M);\nfor i=1:M\n state_noise_samples{i} = sample_gaussian(zeros(length(Q{i}),1), Q{i}, T)';\n obs_noise_samples{i} = sample_gaussian(zeros(length(R{i}),1), R{i}, T)';\nend\n\nx = zeros(ss, T);\ny = zeros(os, T);\n\nm = models(1);\nx(:,1) = init_state(:,m);\ny(:,1) = H{m}*x(:,1) + obs_noise_samples{m}(:,1);\n\nfor t=2:T\n m = models(t);\n x(:,t) = F{m}*x(:,t-1) + G{m}*u(:,t-1) + state_noise_samples{m}(:,t);\n y(:,t) = H{m}*x(:,t) + obs_noise_samples{m}(:,t);\nend\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/Kalman/sample_lds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6355067868064324}} {"text": "function [ point, seed ] = p05_sample ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% P05_SAMPLE samples points from the region in problem 05.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real POINT(M,N), the coordinates\n% of the points.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n center1 = [ 0.0, 0.0 ];\n center2 = [ -0.4, 0.0 ];\n r1 = 1.00;\n r2 = 0.55;\n\n x1 = center1(1) - r1;\n x2 = center1(1) + r1;\n\n y1 = center1(2);\n y2 = center1(2) + r1;\n\n have = 0;\n%\n% We are going to generate batches of sample points.\n%\n sample_num = min ( 1000, n );\n\n while ( 1 )\n%\n% Generate a batch of points in [0,1]x[0,1].\n%\n [ sample, seed ] = r8mat_uniform_01 ( m, sample_num, seed );\n%\n% Remap the points to the box [X1,X2] x [Y1,Y2].\n%\n sample(1,1:sample_num) = x1 + sample(1,1:sample_num) * ( x2 - x1 );\n sample(2,1:sample_num) = y1 + sample(2,1:sample_num) * ( y2 - y1 );\n%\n% Accept those points which are in the big circle and not in the\n% small circle.\n%\n for j = 1 : sample_num\n \n if ( ... \n ( sample(1,j) - center1(1) ).^2 ...\n + ( sample(2,j) - center1(2) ).^2 <= r1 * r1 & ...\n r2 * r2 <= ( sample(1,j) - center2(1) ).^2 ...\n + ( sample(2,j) - center2(2) ).^2 ) \n\n have = have + 1;\n point(1:m,have) = sample(1:m,j);\n\n if ( have == n )\n return\n end\n\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_triangulation/p05_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6355005253197362}} {"text": "function value = r4_int ( x )\n\n%*****************************************************************************80\n%\n%% R4_INT returns the integer part of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 October 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the integer part of X.\n%\n persistent npart\n persistent scale\n persistent xbig\n persistent xmax\n\n if ( isempty ( npart ) )\n ibase = i4_mach ( 10 );\n xmax = 1.0 / r4_mach ( 4 );\n xbig = min ( i4_mach ( 9 ), xmax );\n expo = floor ( log ( xbig ) / log ( ibase ) - 0.5 );\n scale = ibase ^ expo;\n npart = floor ( log ( xmax ) / log ( scale ) + 1.0 );\n end\n\n if ( x < - xmax )\n\n value = x;\n\n elseif ( x < - xbig )\n\n xscl = - x;\n\n for i = 1 : npart\n xscl = xscl / scale;\n end\n\n value = 0.0;\n for i = 1 : npart\n xscl = xscl * scale;\n ipart = ceil ( xscl );\n part = ipart;\n xscl = xscl - part;\n value = value * scale + part;\n end\n\n value = - value;\n\n else if ( x < 0 )\n\n value = ceil ( x );\n\n elseif ( x < + xbig )\n\n value = floor ( x );\n\n elseif ( x < + xmax )\n\n xscl = x;\n\n for i = 1 : npart\n xscl = xscl / scale;\n end\n\n value = 0.0;\n for i = 1 : npart\n xscl = xscl * scale;\n ipart = floor ( xscl );\n part = ipart;\n xscl = xscl - part;\n value = value * scale + part;\n end\n\n else\n\n value = x;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_int.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6355005157174279}} {"text": "function [coef]=comp_dwiltiv(coef2,a)\n%COMP_DWILTIV Compute Discrete Wilson transform type IV.\n% \n\nM=size(coef2,1)/2;\nN=size(coef2,2);\nW=size(coef2,3);\nL=N*a;\n\ncoef=zeros(M,N,W,assert_classname(coef2));\n\n% --- m is even ---------\ncoef(1:2:M,1:2:N,:)= 1/sqrt(2)*(exp(-i*pi/4)*coef2(1:2:M,1:2:N,:)+exp(-i*pi*3/4)*coef2(2*M:-2:M+1,1:2:N,:));\ncoef(1:2:M,2:2:N,:)= 1/sqrt(2)*(exp(i*pi/4)*coef2(1:2:M,2:2:N,:)+exp(i*pi*3/4)*coef2(2*M:-2:M+1,2:2:N,:));\n\n% --- m is odd ----------\ncoef(2:2:M,1:2:N,:)= 1/sqrt(2)*(exp(i*pi/4)*coef2(2:2:M,1:2:N,:)+exp(i*pi*3/4)*coef2(2*M-1:-2:M+1,1:2:N,:));\ncoef(2:2:M,2:2:N,:)= 1/sqrt(2)*(exp(-i*pi/4)*coef2(2:2:M,2:2:N,:)+exp(-i*pi*3/4)*coef2(2*M-1:-2:M+1,2:2:N,:));\n\ncoef=reshape(coef,M*N,W);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_dwiltiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6354858916397836}} {"text": "function [E,J]=SynthMeasWatsonSHStickTortIsoVIsoDot_B0(x, protocol, fibredir)\n% Substrate: Impermeable sticks (cylinders with zero radius) in a homogeneous\n% background.\n% Orientation distribution: Watson's distribution with SH approximation\n% Signal approximation: Not applicable\n% Notes: This version estimates the hindered diffusivity from the free diffusivity\n% and packing density using Szafer et al's tortuosity model for randomly\n% packed cylinders.\n% This version includes an isotropic diffusion compartment with its own\n% diffusivity.\n% This version includes a stationary water compartment.\n% Includes a free parameter for the measurement at b=0.\n%\n% [E,J]=SynthMeasWatsonSHStickTortIsoV_B0(x, protocol, fibredir)\n% returns the measurements E according to the model and the Jacobian J of the\n% measurements with respect to the parameters. The Jacobian does not\n% include derivates with respect to the fibre direction.\n%\n% x is the list of model parameters in SI units:\n% x(1) is the volume fraction of the intracellular space.\n% x(2) is the free diffusivity of the material inside and outside the cylinders.\n% x(3) is the concentration parameter of the Watson's distribution.\n% x(4) is the volume fraction of the isotropic compartment.\n% x(5) is the diffusivity of the isotropic compartment.\n% x(6) is the volume fraction of the isotropic restriction.\n% x(7) is the measurement at b=0.\n%\n% protocol is the object containing the acquisition protocol.\n%\n% fibredir is a unit vector along the symmetry axis of the Watson's\n% distribution. It must be in Cartesian coordinates [x y z]' with size [3 1].\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nxcyl=[x(1) x(2) 0 x(3) x(4) x(5) x(6) x(7)];\n\nif(nargout == 1)\n E=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(xcyl, protocol, fibredir, 0);\nelse\n [E,Jcyl]=SynthMeasWatsonSHCylSingleRadTortIsoVIsoDot_GPD_B0(xcyl, protocol, fibredir, 0);\nend\n\nif(nargout>1)\n J(:,1) = Jcyl(:,1);\n J(:,2) = Jcyl(:,2);\n J(:,3) = Jcyl(:,4);\n J(:,4) = Jcyl(:,5);\n J(:,5) = Jcyl(:,6);\n J(:,6) = Jcyl(:,7);\n J(:,7) = Jcyl(:,8);\nend\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/SynthMeasWatsonSHStickTortIsoVIsoDot_B0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.635459373813926}} {"text": "% ***************************************************************************\n% Parabolic Interpolation\n% ***************************************************************************\n% Author: Chaobin\n% Email: chaubyZou@163.com\n% Date: October 2020\n% ***************************************************************************\n% Language: Matlab\n% Also available in: Python\n% Required library: None\n% ***************************************************************************\n\nclassdef ParabolicInterpolation < handle\n properties\n name = 'parabolic interpolation';\n q_via = [];\n t_via = [];\n end\n\n methods\n % crate the objective\n % name: string\n % q_via: N x 3 array\n % t_via: N x 1 array\n function obj = ParabolicInterpolation(name, q_via, t_via)\n obj.name = name;\n obj.q_via = q_via;\n obj.t_via = t_via;\n if length(q_via(:,1)) ~= length(t_via)\n error('The q_via and t_via must have a same length');\n end\n end\n\n % parabolic interpolation with two data points\n % q0: the first data point\n % q1: the second data point\n % v0: the velocity of the first data point\n % v1: the velocity of the second data point\n % t0: the time of the first data point\n % t1: the time of the second data point\n % tf: the time of the flex point \n % qf: the position of the flex point \n % a0~a5: parameters\n function [a0, a1, a2, a3, a4, a5] = parabolic(obj, q0, q1, v0, v1, t0, t1, tf, qf)\n if abs(t0 - t1) < 1e-6\n error('t0 and t1 must be different');\n end\n\n if ((tf <= t0) || (tf >= t1))\n error('tf must satisfy t0 < tf < t1');\n end\n\n if ((qf <= min(q0, q1)) || (qf >= max(q0, q1)))\n error('qf must satisfy min(q0, q1) < qf < max(q0, q1)');\n end\n\n T = t1 - t0;\n h = q1 - q0;\n Ta = tf - t0;\n Td = t1 - tf;\n\n a0 = q0;\n a1 = v0;\n a2 = (2*h - v0*(T + Ta) - v1*Td)/(2*T*Ta);\n a3 = (2*q1*Ta + Td*(2*q0 + Ta*(v0 - v1)))/(2*T);\n a4 = (2*h - v0*Ta - v1*Td)/T;\n a5 = -(2*h - v0*Ta - v1*(T+Td))/(2*T*Td);\n end\n\n % parabolic interpolation for all data points\n % t: time\n % q: 1 x 3 array, output of the interpolation at time t\n function q = getPosition(obj, t)\n if (t < obj.t_via(1)) || (t > obj.t_via(end))\n error('The specific time error, time ranges error');\n end\n\n j = find(obj.t_via >= t, 1, 'first'); % find the index of t1\n if j == 1\n i = 1;\n j = 2;\n else\n i = j-1;\n end\n\n % get given position\n q0 = obj.q_via(i, 1);\n v0 = obj.q_via(i, 2);\n t0 = obj.t_via(i);\n\n q1 = obj.q_via(j, 1);\n v1 = obj.q_via(j, 2);\n t1 = obj.t_via(j);\n\n % symmetric acceleration\n tf = (t0 + t1)/2;\n qf = (q0 + q1)/2;\n\n % asymmetric acceleration, specify tf and qf by users\n % tf = ?\n % qf = ?\n\n [a0, a1, a2, a3, a4, a5] = obj.parabolic(q0, q1, v0, v1, t0, t1, tf, qf);\n\n if t <= tf\n q(1, 1) = a0 + a1*(t - t0) + a2*(t-t0)^2;\n q(1, 2) = a1 + 2*a2*(t - t0);\n q(1, 3) = 2*a2;\n else\n q(1, 1) = a3 + a4*(t - tf) + a5*(t-tf)^2;\n q(1, 2) = a4 + 2*a5*(t - tf);\n q(1, 3) = 2*a5;\n end\n end\n end\nend\n", "meta": {"author": "chauby", "repo": "PolynomialInterpolation", "sha": "222dbf804c1e756f51c848631acae3fb1dc172e3", "save_path": "github-repos/MATLAB/chauby-PolynomialInterpolation", "path": "github-repos/MATLAB/chauby-PolynomialInterpolation/PolynomialInterpolation-222dbf804c1e756f51c848631acae3fb1dc172e3/matlab/ParabolicInterpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6354593588630213}} {"text": "function Qb2n = ch_m2q(Cb2n)\n% 姿态阵转四元数\n%\n% Input: Cb2n\n% Output: Qb2n\n%\n C11 = Cb2n(1,1); C12 = Cb2n(1,2); C13 = Cb2n(1,3); \n C21 = Cb2n(2,1); C22 = Cb2n(2,2); C23 = Cb2n(2,3); \n C31 = Cb2n(3,1); C32 = Cb2n(3,2); C33 = Cb2n(3,3); \n if C11>=C22+C33\n q1 = 0.5*sqrt(1+C11-C22-C33);\n q0 = (C32-C23)/(4*q1); q2 = (C12+C21)/(4*q1); q3 = (C13+C31)/(4*q1);\n elseif C22>=C11+C33\n q2 = 0.5*sqrt(1-C11+C22-C33);\n q0 = (C13-C31)/(4*q2); q1 = (C12+C21)/(4*q2); q3 = (C23+C32)/(4*q2);\n elseif C33>=C11+C22\n q3 = 0.5*sqrt(1-C11-C22+C33);\n q0 = (C21-C12)/(4*q3); q1 = (C13+C31)/(4*q3); q2 = (C23+C32)/(4*q3);\n else\n q0 = 0.5*sqrt(1+C11+C22+C33);\n q1 = (C32-C23)/(4*q0); q2 = (C13-C31)/(4*q0); q3 = (C21-C12)/(4*q0);\n end\n Qb2n = [q0; q1; q2; q3];\n \n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/rotation/ch_m2q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6353975445493368}} {"text": "function [ GAMMA ] = Mellin_NIG_European_Gamma( S_0, W, T, r, q, alpha, beta, delta, N1)\n%UNTITLED2 Summary of this function goes here\n% Detailed explanation goes here\n\nf = W*exp(-r*T);\n\ngam = sqrt(alpha^2 - beta^2);\nk0 = log(S_0/W) + (r - q + delta*(sqrt(alpha^2 - (beta + 1)^2) - gam))*T;\nadt = alpha*delta*T;\ndta = 0.5*delta*T/alpha;\n\nsum = 0;\n\nif beta == 0\n % Symmetric Formula\n for n = 0:N1\n cons1 = k0^n / factorial(n);\n term = besselk(n/2 + 1, adt) / gamma((-n+1)/2) * (dta)^(-n/2);\n sum = sum + cons1*term;\n end\nelse\n % Asymmetric Formula\n \nend\n\ncons = f*alpha*exp(alpha*delta*T)/(S_0*S_0*sqrt(pi));\nGAMMA = cons*sum;\n\n\nend\n\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Fourier/MellinTransform/Mellin_NIG_European_Gamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.635397540727545}} {"text": "% dubinsParameters\n% - Find Dubin's parameters between two configurations\n%\n% input is:\n% start_node - [wn_s, we_s, wd_s, chi_s, 0, 0]\n% end_node - [wn_e, wn_e, wd_e, chi_e, 0, 0]\n% R - minimum turn radius\n%\n% output is:\n% dubinspath - a matlab structure with the following fields\n% dubinspath.ps - the start position in re^3\n% dubinspath.chis - the start course angle\n% dubinspath.pe - the end position in re^3\n% dubinspath.chie - the end course angle\n% dubinspath.R - turn radius\n% dubinspath.L - length of the Dubins path\n% dubinspath.cs - center of the start circle\n% dubinspath.lams - direction of the start circle\n% dubinspath.ce - center of the end circle\n% dubinspath.lame - direction of the end circle\n% dubinspath.w1 - vector in re^3 defining half plane H1\n% dubinspath.q1 - unit vector in re^3 along straight line path\n% dubinspath.w2 - vector in re^3 defining position of half plane H2\n% dubinspath.w3 - vector in re^3 defining position of half plane H3\n% dubinspath.q3 - unit vector defining direction of half plane H3\n% \n\nfunction dubinspath = dubinsParameters(start_node, end_node, R)\n\n ell = norm(start_node(1:2)-end_node(1:2));\n if ell<2*R,\n disp('The distance between nodes must be larger than 2R.');\n dubinspath = [];\n else\n \n ps = start_node(1:3);\n chis = start_node(4);\n pe = end_node(1:3);\n chie = end_node(4);\n\n crs = ps' + R*rotz(pi/2)*[cos(chis); sin(chis); 0];\n cls = ps' + R*rotz(-pi/2)*[cos(chis); sin(chis); 0];\n cre = pe' + R*rotz(pi/2)*[cos(chie); sin(chie); 0];\n cle = pe' + R*rotz(-pi/2)*[cos(chie); sin(chie); 0];\n \n % compute L1\n connecting_line = cre-crs;\n north_unit = [1; 0; 0];\n% theta = acos(dot(connecting_line,north_unit)/norm(connecting_line));\n theta = atan2(connecting_line(2), connecting_line(1));\n L1 = norm(crs-cre) + R*mod(2*pi + mod(theta-pi/2, 2*pi) - mod(chis-pi/2, 2*pi), 2*pi) ...\n + R*mod(2*pi + mod(chie-pi/2, 2*pi) - mod(theta-pi/2, 2*pi), 2*pi);\n % compute L2\n connecting_line = cle-crs;\n ell = norm(connecting_line);\n% theta = acos(dot(connecting_line,north_unit)/norm(connecting_line));\n theta = atan2(connecting_line(2), connecting_line(1));\n theta2 = theta - pi/2 + asin(2*R/ell);\n if isreal(theta2)==0, \n L2 = 9999; \n else\n L2 = sqrt(ell^2-4*R^2) + R*mod(2*pi + mod(theta2, 2*pi) - mod(chis-pi/2, 2*pi), 2*pi) ...\n + R*mod(2*pi + mod(theta2+pi, 2*pi) - mod(chie+pi/2, 2*pi), 2*pi);\n end\n % compute L3\n connecting_line = cre-cls;\n ell = norm(connecting_line);\n% theta = acos(dot(connecting_line,north_unit)/norm(connecting_line));\n theta = atan2(connecting_line(2), connecting_line(1));\n theta2 = acos(2*R/ell);\n if isreal(theta2)==0,\n L3 = 9999;\n else\n L3 = sqrt(ell^2-4*R^2) + R*mod(2*pi + mod(chis+pi/2, 2*pi) - mod(theta+theta2, 2*pi), 2*pi) ...\n + R*mod(2*pi + mod(chie-pi/2, 2*pi) - mod(theta+theta2-pi, 2*pi), 2*pi);\n end\n % compute L4\n connecting_line = cle-cls;\n% theta = acos(dot(connecting_line,north_unit)/norm(connecting_line));\n theta = atan2(connecting_line(2), connecting_line(1));\n L4 = norm(cls-cle) + R*mod(2*pi + mod(chis+pi/2, 2*pi) - mod(theta+pi/2, 2*pi), 2*pi) ...\n + R*mod(2*pi + mod(theta+pi/2, 2*pi) - mod(chie+pi/2, 2*pi), 2*pi);\n % L is the minimum distance\n [L,idx] = min([L1,L2,L3,L4]);\n e1 = [1; 0; 0]; % north unit vector\n switch(idx),\n case 1,\n cs = crs;\n lams = 1;\n ce = cre;\n lame = 1;\n q1 = (ce-cs)/norm(ce-cs);\n w1 = cs + R*rotz(-pi/2)*q1;\n w2 = ce + R*rotz(-pi/2)*q1;\n case 2, \n cs = crs;\n lams = 1;\n ce = cle;\n lame = -1;\n ell = norm(ce-cs);\n connecting_line = ce - cs;\n theta = atan2(connecting_line(2), connecting_line(1));\n% theta = acos(dot(ce-cs,e1)/ell);\n theta2 = theta - pi/2 + asin(2*R/ell);\n q1 = rotz(theta2+pi/2)*e1;\n w1 = cs + R*rotz(theta2)*e1;\n w2 = ce + R*rotz(theta2+pi)*e1;\n case 3,\n cs = cls;\n lams = -1;\n ce = cre;\n lame = 1;\n ell = norm(ce-cs);\n connecting_line = ce - cs;\n% theta = acos(dot(ce-cs,e1)/ell);\n theta = atan2(connecting_line(2), connecting_line(1));\n theta2 = acos(2*R/ell);\n q1 = rotz(theta+theta2-pi/2)*e1;\n w1 = cs + R*rotz(theta+theta2)*e1;\n w2 = ce + R*rotz(theta+theta2-pi)*e1;\n case 4,\n cs = cls;\n lams = -1;\n ce = cle;\n lame = -1;\n q1 = (ce-cs)/norm(ce-cs);\n w1 = cs + R*rotz(pi/2)*q1;\n w2 = ce + R*rotz(pi/2)*q1;\n end\n w3 = pe';\n q3 = rotz(chie)*e1;\n \n % assign path variables\n dubinspath.ps = ps;\n dubinspath.chis = chis;\n dubinspath.pe = pe;\n dubinspath.chie = chie;\n dubinspath.R = R;\n dubinspath.L = L;\n dubinspath.cs = cs;\n dubinspath.lams = lams;\n dubinspath.ce = ce;\n dubinspath.lame = lame;\n dubinspath.w1 = w1;\n dubinspath.q1 = q1;\n dubinspath.w2 = w2;\n dubinspath.w3 = w3;\n dubinspath.q3 = q3;\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% rotz(theta)\n%% rotation matrix about the z axis.\nfunction R = rotz(theta)\n R = [...\n cos(theta), -sin(theta), 0;...\n sin(theta), cos(theta), 0;...\n 0, 0, 1;...\n ];\nend\n", "meta": {"author": "chengji253", "repo": "Multiple-fixed-wing-UAVs-flight-simulation-platform", "sha": "7c1fa69d9033355461c0753c2a7408a9bcf1e3e7", "save_path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform", "path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform/Multiple-fixed-wing-UAVs-flight-simulation-platform-7c1fa69d9033355461c0753c2a7408a9bcf1e3e7/platform_code/uavA1/dubinsParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6353623433441401}} {"text": "function [n,dndr,T,P]=SinclairAtmos(h,phl0,Rh,P0,T0,wl,ht)\n%SINCLAIRATMOS Compute atmospheric parameters for the Sinclair\n% atmospheric model. This simple model is often used for\n% computing atmospheric refraction when viewing stars. The\n% index of refraction in the model depends on the height\n% above mean sea level. In this implementation, mean sea\n% level is approximated by the surface of the WGS-84\n% reference ellipsoid. The model is not sufficiently precise\n% that geoid undulations should matter and it also shouldn't\n% matter if a geocentric latitude is substituted for the\n% geodetic latitude.\n%\n%INPUTS: h The vector or matrix of heights above sea level where the\n% indices of refraction and other parameters are desired.\n% phl0 The location of an observer in WGS-84 ellipsoidal coordinates\n% [latitude;longitude;ellipsoidal height] in the troposphere\n% measuring the relative humidity, ambient air pressure and the\n% temperature. Only the latitude in radians and the ellipsoidal\n% height in meters matter; the longitude is ignored.\n% Rh The relative humidity at the observer (between 0 and 1). If\n% this parameter is omitted or an empty matrix is passed, then\n% Constants.standardRelHumid is used.\n% P0 The atmospheric pressure at the observer in Pascals (N/m^2). If\n% this parameter is omitted or an empty matrix is passed, then\n% Constants.standardAtmosphericPressure is used.\n% T0 The air temperature at the observer in degrees Kelvin. If this\n% parameter is omitted or an empty matrix is passed, then\n% Constants.standardTemp is used.\n% wl The wavelength at which the observation is made in units of\n% meters. If this parameter is omitted or an empty matrix is\n% passed, then a wavelength of 0.574 micrometers is used, which\n% is in the visible spectrum (a rather yellow color). This\n% parameter only matters for determining the narrowband index of\n% refraction at a given .\n% ht The assumed height of the troposphere in meters. This parameter\n% specifies when a stratospheric model begins being used. If this\n% parameter is omitted, then the default value of 11000m is used.\n%\n%OUTPUTS: n A matrix providing the index of refraction at all of the\n% distances given in r.\n% dndr A matrix providing the derivative of the index of refraction\n% with respect to r evaluated at all of the values given in r.\n% T A matrix giving the temperature in degrees Kelvin in the\n% atmospheric model at the distances given in r.\n% P A matrix giving the barometric pressures in Pascals in the\n% atmospheric model at the distances given in r.\n%\n%The Sinclair atmospheric model is described in Chapter 7.2 of [1] and in\n%[2]. The original source is cited in [2] as being [3]. Reference 3 was not\n%consulted in implementing this algorithm.\n%\n%In the references, the atmosphere is defined in terms of radial\n%distances from the center of the Earth. However, the radials distances\n%only appear as differences, so heights above mean sea level (MSL) can be\n%substituted. MSL in this implementations is just taken to be the surface\n%of the WGS-84 reference ellipsoid. The model makes a number of local\n%spherical Earth approximations.\n%\n%REFERENCES:\n%[1] S. E. Urban and K. P.Seidelmann, Eds.,Explanatory Supplement to the\n% Astronomical Almanac, 3rd ed. Mill Valley, CA: University Science\n% Books, 2013.\n%[2] C. Y. Hohenkerk and A. T. Sinclair, \"The computation of angular\n% atmospheric refraction at large zenith angles,\" United Kingdom\n% Hydrographic Office, HM Nautical Almanac, Tech. Rep. 63, Apr. 1985.\n% http://astro.ukho.gov.uk/data/tn/naotn63.pdf\n%[3] A. T. Sinclair, \"The effect of atmospheric refraction on laser ranging\n% data,\" United Kingdom Hydrographic Office, HM Nautical Almanac, Tech.\n% Rep. 59, 1982.\n%\n%April 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(nargin<7||isempty(ht))\n ht=11000;%Assumed top of the troposphere in meters.\n end\n\n if(nargin<6||isempty(wl))\n wl=0.574e-6; \n end\n\n if(nargin<5||isempty(T0))\n T0=Constants.standardTemp; \n end\n \n if(nargin<4||isempty(P0))\n P0=Constants.standardAtmosphericPressure;\n end\n \n if(nargin<3||isempty(Rh))\n Rh=Constants.standardRelHumid;\n end\n\n %The geodetic latitude in radians.\n phi=phl0(1);\n %The height above the reference ellipsoid in meters is used in\n %place of the height above the geoid.\n h0=phl0(3);\n phi=ellips2Sphere(phi);\n \n %%SET ATMOSPHERIC MODEL PARAMETERS.\n %Convert the pressure from Pascals to millibars.\n P0=P0*0.01;\n %Convert the wavelength from meters to micrometers.\n lambda=wl*1e6;\n %The set of constants is from Equation 7.82 in [1].\n R=1000*Constants.molarGasConstant;%(R) J/(kilomol K)\n Md=28.966;%Assumed molecular mass (im amu) of dry air.\n %The molecular mass (in amu) of water.\n Mw=2*Constants.elementAMU(1)+Constants.elementAMU(8);\n %Exponent of the temperature dependence of water vapor pressure.\n %This is used in an approximate conversion to get the partial\n %pressure of water vapor from the relative humidity.\n delta=18.36;\n alpha=0.0065;%Tropospheric lapse rate of temperature in K/m.\n \n %The following set of Equations is from Equation 7.83 in [1].\n %The partial pressure of water vapor at the observer in millibars.\n Pw0=Rh*(T0/247.1)^delta;\n gBar=9.784*(1-0.0026*cos(2*phi)-0.00000028*h0);\n A=(287.604+1.6288/lambda^2+0.0136/lambda^4)*(273.15/1013.25)*1e-6;\n C2=gBar*Md/R;\n gamma=C2/alpha;\n C5=Pw0*(1-Mw/Md)*gamma/(delta-gamma);\n C6=A*(P0+C5)/T0;\n C7=(A*C5+11.2684e-6*Pw0)/T0;\n C8=alpha*(gamma-1)*C6/T0;\n C9=alpha*(delta-1)*C7/T0;\n \n %Allocate space for the return variables.\n n=zeros(size(h));\n dndr=zeros(size(h));\n T=zeros(size(h));\n P=zeros(size(h));\n\n %First, deal with all of the points that are in the stratosphere.\n sel=h>ht;\n \n %First, compute the refraction and temperature at the top of the\n %troposphere using Equation 7.85 in [1].\n Tt=T0-alpha*(ht-h0);\n T(sel)=Tt;\n TRat=Tt/T0;\n nt=1+(C6*TRat^(gamma-2)-C7*TRat^(delta-2))*TRat;\n %Approximate partial vapor pressure of water at the tropopause,\n %taken from page 4 of [2].\n Pwt=Pw0*TRat^delta;\n %Air pressure at the tropopause taken from page 4 of [2].\n Pt=(P0+C5)*TRat^(gamma)-Pwt*(1-Mw/Md)*gamma/(delta-gamma);\n\n %The modelled refraction in the stratosphere.\n %Equation 7.86 in [1].\n n(sel)=1+(nt-1).*exp(-C2*(h(sel)-ht)./Tt);\n dndr(sel)=-(C2./Tt).*(nt-1).*exp(-C2*(h(sel)-ht)./Tt);\n\n %Stratospheric air pressure, taken from page 5 of [2]. The 0.01\n %term converts the pressure from millibars to Pascals.\n P(sel)=Pt.*exp(-C2*(h(sel)-ht)./Tt)/0.01;\n \n %Next, deal with the points in the troposphere.\n sel=~sel;\n %The modelled refraction in the troposphere.\n %Equation 7.85 in [1].\n T(sel)=T0-alpha*(h(sel)-h0);\n TRat=T(sel)/T0;\n n(sel)=1+(C6*TRat.^(gamma-2)-C7*TRat.^(delta-2)).*TRat;\n dndr(sel)=-C8*TRat.^(gamma-2)+C9*TRat.^(delta-2);\n\n %Approximate partial vapor pressure of water at altitude, taken\n %from page 4 of [2].\n Pw=Pw0*TRat.^delta;\n %Air pressure at altitude taken from page 4 of [2]. The 0.01 term\n %converts the pressure from millibars to Pascals.\n P(sel)=((P0+C5).*TRat.^(gamma)-Pw*(1-Mw/Md)*gamma/(delta-gamma))/0.01;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Atmosphere_and_Refraction/SinclairAtmos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6352674185344326}} {"text": "function [GWpos,GWneg] = gateway_coef_sign(W,Ci,centtype)\n\n% Gateway coefficient\n%\n% [Gpos,Gneg] = gateway_coef_sign(W,Ci,centtype);\n%\n% Gateway coefficient is a variant of participation coefficient. Similar\n% to participation coefficient, gateway coefficient measures the\n% diversity of intermodular connections of individual nodes, but this is\n% weighted by how critical these connections are to intermodular\n% connectivity (e.g., if a node is the only connection between it's\n% module and another module, it will have a higher gateway coefficient).\n%\n% Inputs: W, undirected connection matrix with positive and\n% negative weights\n%\n% Ci, community affiliation vector\n%\n% centtype, centrality measure to use\n% 1 = Node Strength\n% 2 = Betweenness Centrality\n%\n% Output: Gpos, gateway coefficient for positive weights\n% Gneg, gateway coefficient for negative weights\n%\n% Reference: Vargas ER, Wahl LM. Eur Phys J B (2014) 87:1-10.\n%\n% Jeff Spielberg, University of Delaware\n\n% Modification History:\n% May 2015: Original (originally adapted from participation_coef_sign.m)\n% July 2018: Bugfix, change in how weighted matrices are handled,\n% improvements for efficiency, additional line documentation\n\n[~,~,Ci] = unique(Ci); % Remap module indices to consecutive numbers\nn = length(W); % Number of nodes\nW(1:(n+1):end) = 0; % Ensure diagonal is zero\nGWpos = gcoef(W.*(W>0)); % Compute gateway coefficient for positive weights\nGWneg = gcoef(-W.*(W<0)); % Compute gateway coefficient for negative weights\n\n function GW = gcoef(W_)\n k = sum(W_,2); % Compute node strength\n Gc = (W_~=0)*diag(Ci); % Create neighbor community affiliation matrix\n nmod = max(Ci); % Find # of modules\n ks = zeros(n,nmod); % Preallocate space\n kjs = zeros(n,nmod); % Preallocate space\n cs = zeros(n,nmod); % Preallocate space\n switch centtype % Which centrality measure to use?\n case 1 % Node Strength\n cent = sum(W_,2);\n case 2 % Betweenness Centrality\n L = weight_conversion(W_,'lengths');\n cent = betweenness_wei(L);\n end\n mcn = 0; % Set max summed centrality per module to 0\n for i = 1:nmod % For each module\n if sum(cent(Ci==i))>mcn % If current module has a higher sum\n mcn = sum(cent(Ci==i)); % Reassign value\n end\n ks(:,i) = sum(W_.*(Gc==i),2); % Compute the total weight of the connections per node to each module\n end\n for i = 1:nmod % For each module\n if sum(Ci==i)>1 % If there is more than 1 node in a module\n kjs(Ci==i,:) = ones(sum(Ci==i),1)*sum(ks(Ci==i,:)); % Compute total module-module connections\n kjs(Ci==i,i) = kjs(Ci==i,i)/2; % Account for redundancy due to double counting within-network work weights\n end\n end\n for i = 1:n % For each node\n if k(i)>0 % If node is connected\n for ii = 1:nmod % For each module\n cs(i,ii) = sum(cent((Ci.*(W_(:,i)>0))==ii)); % Sum of centralities of neighbors of a node within a module\n end\n end\n end\n ksm = ks./kjs; % Normalize by total connections\n ksm(kjs==0) = 0; % Account for division by 0\n csm = cs./mcn; % Normalize by max summed centrality\n gs = (1-(ksm.*csm)).^2; % Calculate total weighting\n GW = 1-sum((ks.^2)./(k.^2).*gs,2); % Compute gateway coefficient\n GW(isnan(GW)) = 0; % Account for division by 0\n GW(~GW) = 0; % Set to 0 if no neighbors\n end\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/gateway_coef_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6352656697382129}} {"text": "function legendre_symbol_test ( )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_SYMBOL_TEST tests LEGENDRE_SYMBOL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n ntest = 4;\n ptest = [ 7, 11, 13, 17 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_SYMBOL_TEST\\n' );\n fprintf ( 1, ' LEGENDRE_SYMBOL computes the Legendre\\n' );\n fprintf ( 1, ' symbol (Q/P) which records whether Q is \\n' );\n fprintf ( 1, ' a quadratic residue modulo the prime P.\\n' );\n\n for i = 1 : ntest\n p = ptest(i);\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Legendre Symbols for P = %d\\n', p );\n fprintf ( 1, '\\n' );\n for q = 0 : p\n l = legendre_symbol ( q, p );\n fprintf ( 1, ' %6d %6d %6d\\n', p, q, l );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/legendre_symbol_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6352105449341078}} {"text": "function [xVals,tVals,dxdtVals,exitCode,numRejections]=RosenbrockAdaptiveOverRange(xStart,tSpan,f,order,JacobianFun,dfdtFun,initStepSize,RelTol,AbsTol,maxSteps)\n%%ROSENBROCKADAPTIVEOVERRANGE Integrate an ordinary differential equation\n% using a modified Rosenbrock method with an adaptive\n% step size. That is, integrating dx/dt=f(x,t) given\n% initial conditions (xStart,tSpan(1)). Rosenbrock\n% methods are better then Runge-Kutta methods when the\n% differential equations are stiff. However, Rosenbrock\n% methods require a derivative. More information\n% on the algorithms used with different orders is given\n% in the comments to the function RosenbrockStep.\n%\n%INPUTS: xStart The NX1 state vector at time tSpan(1).\n% tSpan A 2X1 or 1X2 vector where tSpan(1) is the starting time\n% and tSpan2 is the desired stopping time for the\n% integration.\n% f The function handle for f(x,t)=dxdt over which integration\n% is to be performed.\n% order The order of the main Rosenbrock routine to use. See the\n% function RosenbrockStep for possible values and algorithms\n% used as this function calls RosenbrockStep. If omitted or\n% an empty matrix is passed, the default value of 2 is used.\n% initStepSize An optional initial step size (in t) to use for the\n% integration. If omitted or an empty matrix is passed, an\n% ad-hoc method described below is used to find an initial\n% step size.\n% JacobianFun This is either a function handle having the form\n% JacobianFun(x,t) that provides the Jacobian of the\n% function f --the derivatives with respect to the parameter\n% x-- or this is a matrix that is the constant Jacobian\n% matrix. If this parameter is omitted or an empty matrix is\n% passed, then the NXN Jacobian matrix is computed using the\n% numjac function with the tolerance set to AbsTol.\n% dfdtFun This is either a function handle having the form\n% dfdtFun(x,t) that provides the derivative of f with\n% respect to the scalar parameter t, or this is a constant\n% NX1 vector for the derivative of f with respect to t. In\n% autonomous problems, a zero matrix should be passed. If\n% omitted, a central difference formula is used to\n% numerically approximate the derivative vector.\n% initStepSize An optional initial step size (in t) to use for the\n% integration. If omitted or an empty matrix is passed, an\n% ad-hoc method described below is used to find an initial\n% step size.\n% RelTol The maximum relative error tolerance allowed, a\n% positive scalar (its use is explained in more detail\n% below). If omitted or an empty matrix is passed, the\n% default value of 1e-3 is used.\n% AbsTol The absolute error tolerance allowed, a positive scalar,\n% of the same for all components of x, or a positive NX1\n% vector. If omitted or an empty matrix is passed, the\n% default value of 1e-6 is used.\n% maxSteps The maximum allowable number of steps to perform the\n% integration. If omitted, the default of 4096 is used.\n%\n%OUTPUTS:xVals The NXnumSteps set of values of x along the path.\n% xVals(:,1) is xStart and xVals(:,end) is the value at\n% final time tSpan(2). If the integration failed, e.g. due\n% to encountering a NaN or being unable to get a sufficient\n% step size, an empty matrix is returned.\n% tVals A numStepsX1 vector of values of t corresponding to\n% the values of x in xVals. tVals(1) is equal to tSpan(1)\n% and tVals(end) is equal to tSpan(2). If integration\n% fails, an empty matrix is returned.\n% dxdtVals A numStepsX1 array containing deivatives of x evaluated\n% at the times in tVals. The derivatives are just the\n% result of evaluating f(x,t) at each point in\n% (xVals,tVals). This combined with xVals and tVals could\n% be used in functions to perform Hermite interpolation.\n% If integration fails, an empty matrix is returned.\n% exitCode A code indicating how the algorithm terminated. Possible\n% values are\n% 0: Integration was successful.\n% 1: Unable to get a small enough step size.\n% 2: Maximum number of steps reaced without completion.\n% 3: Non-finite number encountered.\n% numRejections The number of times a stepsize hypothesis was rejected.\n%\n%The same type of adaptive stepsize control is used with the Rosenbrock\n%algorithm (a diagonal implicit Runge-Kutta routine) as with standard\n%Runge-Kutta methods. Thus, the comments to the stepsize adaptation routine\n%in RKAdaptiveOverRange explain how the stepsize is adjusted here. The onyl\n%notable change is that a certain matrix has to be inverted for each of the\n%Rosenbrock methods. The matrix depends on the stepsize. Thus, if the\n%matrix is singular, this function has an additional rejection of the step\n%and the stepsize is halved.\n%\n%The central difference formula used for the numeric derivative of f with\n%respect to t if dfdtFun is not provided is taken from Chapter 4.1 of [1],\n%whereby the three-point midpoint formula is used.\n%\n%REFERENCES:\n%[1] R. L. Burden and J. D. Faires, Numerical Analysis, 9th ed. Boston, MA:\n% Brooks/ Cole, 2011.\n%\n%February 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<10)\n maxSteps=4096;\nend\n\nif(nargin<9||isempty(AbsTol))\n AbsTol=1e-6;\nend\n\nif(nargin<8||isempty(RelTol))\n RelTol=1e-3;\nend\n\nxDim=size(xStart,1);\ntStart=tSpan(1);\ntEnd=tSpan(2);\ntDiff=diff(tSpan);\ntDiffMag=abs(tDiff);\ndeltaTSign=sign(tDiff);\n%The sign is separated out so that one can use the algorithm running\n%backwards as well as forwards in time.\n\n%The maximum step size is arbitraily set to 1/3 the total distance.\nmaxStepSize=tDiffMag/3;\n\nif(nargin<7||isempty(initStepSize))\n %If no initial step size is given, then just use the smallest uniform\n %step size for the given value of maxSteps.\n initStepSize=tDiffMag/maxSteps;\nelseif(initStepSizetEnd*deltaTSign)\n deltaTMag=abs(tEnd-tCur);\n deltaT=deltaTMag*deltaTSign;\n %Allow the last step to be very small.\n deltaTMinMag=min(deltaTMinMag,deltaTMag);\n end\n \n if(JacobianType==0)\n %Numerically find the Jacobian. The numjac function is used.\n fRev=@(t,x)f(x,t);\n [J,FAC] = numjac(fRev,tCur,xCur,dxdtCur,AbsTol,FAC,false);\n elseif(JacobianType==1)\n %User-provided function\n J=JacobianFun(xCur,tCur);\n end\n\n %The first time the choice in step size fails, it is adjusted the\n %\"optimal\" way in the Runge-Kutta-Fehlberg method. Additional times,\n %the step size is just halved in the hope that it will reach an\n %accepted value more quickly.\n failedReducingStepSize=false;\n moveOnToNextStep=false;\n while(moveOnToNextStep==false)\n %If an explicit function (or matrix) for the derivative with\n %respect to time is provided.\n if(isempty(dfdtFun))\n %Just use a central finite-difference formula with a set being\n %a quarter of the current step size.\n dfdt=(f(xCur,tCur+deltaT/8)-f(xCur,tCur-deltaT/8))/(2*8);\n elseif(isa(dfdtFun,'function_handle'))\n dfdt=dfdtFun(xCur,tCur);\n else%It is a constant matrix.\n dfdt=dfdtFun;\n end\n\n [xPredMain,xPredSubsid,k]=RosenbrockStep(xCur,tCur,f,deltaT,dxdtCur,J,dfdt,order); \n %If the step failed because the W matrix was singular, reduce the\n %step size and the matrix should not stay singular.\n if(isempty(xPredMain))\n numRejections=numRejections+1;\n \n if(deltaTMagRelTol)\n %The step should be rejected.\n numRejections=numRejections+1;\n\n if(deltaTMag thres),opts);\n % Pathfinder update\n if fit(i) < fitP\n fitP = fit(i);\n Xpf = X(i,:);\n end\nend\n% Set previous pathfiner\nXpf_old = Xpf; \n% Pre\nXpf_new = zeros(1,dim);\nXnew = zeros(N,dim);\n\ncurve = zeros(1,max_Iter);\ncurve(1) = fitP;\nt = 2;\n% Iterations\nwhile t <= max_Iter\n % Alpha & beta in [1,2]\n alpha = 1 + rand();\n beta = 1 + rand();\n for d = 1:dim \n % Define u2 in [-1,1]\n u2 = -1 + 2 * rand();\n % Compute A (2.6)\n A = u2 * exp(-(2 * t) / max_Iter);\n % Update pathfinder (2.4) \n r3 = rand();\n Xpf_new(d) = Xpf(d) + 2 * r3 * (Xpf(d) - Xpf_old(d)) + A;\n end\n % Boundary\n Xpf_new(Xpf_new > ub) = ub; Xpf_new(Xpf_new thres),opts);\n % Greedy selection\n if Fnew < fitP\n fitP = Fnew; \n Xpf = Xpf_new;\n end\n % Sort member\n [fit, idx] = sort(fit,'ascend');\n X = X(idx,:); \n % Update first solution \n if Fnew < fit(1)\n fit(1) = Fnew; \n X(1,:) = Xpf_new;\n end\n % Update \n for i = 2:N\n % Distance (2.5)\n Dij = norm(X(i,:) - X(i-1,:));\n for d = 1:dim\n % Define u1 in [-1,1]\n u1 = -1 + 2 * rand(); \n % Compute epsilon (2.5)\n eps = (1 - (t / max_Iter)) * u1 * Dij;\n % Define R1, R2\n r1 = rand(); \n r2 = rand(); \n R1 = alpha * r1; \n R2 = beta * r2;\n % Update member (2.3)\n Xnew(i,d) = X(i,d) + R1 * (X(i-1, d) - X(i,d)) + ...\n R2 * (Xpf(d) - X(i,d)) + eps;\n end\n % Boundary\n XB = Xnew(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n Xnew(i,:) = XB;\n end\n % Fitness\n for i = 2:N\n % Fitness\n Fnew = fun(feat,label,(Xnew(i,:) > thres),opts);\n % Selection\n if Fnew < fit(i)\n fit(i) = Fnew; \n X(i,:) = Xnew(i,:);\n end\n % Pathfinder update\n if fit(i) < fitP\n fitP = fit(i);\n Xpf = X(i,:);\n end\n end\n curve(t) = fitP;\n fprintf('\\nIteration %d Best (PFA)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features\nPos = 1:dim;\nSf = Pos((Xpf > thres) == 1); \nsFeat = feat(:,Sf);\n% Store results\nPFA.sf = Sf;\nPFA.ff = sFeat; \nPFA.nf = length(Sf);\nPFA.c = curve; \nPFA.f = feat;\nPFA.l = label;\nend\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jPathFinderAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6351778993361573}} {"text": "function [DIP, teta, hr]= DipoleGeneratorAbnormal(N,fs,rr,alphai,bi,tetai,teta0)\n%\n% [DIP teta]= DipoleGeneratorAbnormal(N,fs,rr,alphai,bi,tetai,teta0)\n% Synthetic cardiac dipole generator using the 'differential form' of the\n% dipole equations. Refer to references of the toolbox for further details.\n%\n% inputs:\n% N: signal length\n% fs: sampling rate\n% rr: rr interval time series\n% alphai: structure contaning the amplitudes of Gaussian functions used for\n% modeling the x, y, and z coordinates of the cardiac dipole\n% bi: structure contaning the widths of Gaussian functions used for\n% modeling the x, y, and z coordinates of the cardiac dipole\n% tetai: structure contaning the phase of Gaussian functions used for\n% modeling the x, y, and z coordinates of the cardiac dipole\n% teta0: initial phase of the synthetic dipole\n\n\n%\n% output:\n% DIP: structure contaning the x, y, and z coordinates of the cardiac dipole\n% teta: vector containing the dipole phase\n%\n%\n% Open Source ECG Toolbox, version 2.0, April 2008\n% Released under the GNU General Public License\n% Copyright (C) 2008 Reza Sameni\n% Sharif University of Technology, Tehran, Iran -- GIPSA-Lab, Grenoble, France\n% reza.sameni@gmail.com\n\n% This program is free software; you can redistribute it and/or modify it\n% under the terms of the GNU General Public License as published by the\n% Free Software Foundation; either version 2 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\n% Last update Shamim Nemati Feb 13 2009\n\nrr = rr(:); t = [cumsum(rr)]; tp = linspace(0,sum(rr),N);\nrrp = spline(t,rr,tp);\nf=1./rrp; % make a heart rate (per second) time-series from rr intervals resampled to the current sampling frequency\nhr = f*60;\nw = 2*pi*f; dt = 1/fs;\nteta = zeros(1,N); X = zeros(1,N); Y = zeros(1,N); Z = zeros(1,N);\n\nteta(1) = teta0;\n\nfor i = 1:N-1\n teta(i+1) = teta(i) + w(i)*dt; %dtheta/dt = w\n if(teta(i+1)>pi) % beat transition ------------------------------------\n teta(i+1) = teta(i+1) - 2*pi;\n end\n %------------------------------------------\n dtetaix = mod(teta(i) - tetai.x + pi , 2*pi) - pi;\n dtetaiy = mod(teta(i) - tetai.y + pi , 2*pi) - pi;\n dtetaiz = mod(teta(i) - tetai.z + pi , 2*pi) - pi;\n \n \n if(i==1),\n X(i) = sum(alphai.x .* exp(-dtetaix .^2 ./ (2*bi.x .^ 2)));\n Y(i) = sum(alphai.y .* exp(-dtetaiy .^2 ./ (2*bi.y .^ 2)));\n Z(i) = sum(alphai.z .* exp(-dtetaiz .^2 ./ (2*bi.z .^ 2)));\n end\n %------ Eq.(1) in Clifford et al. CinC2008 ------\n X(i+1) = X(i) - dt*sum(w(i)*alphai.x ./ (bi.x) .^ 2 .* dtetaix .* exp(-dtetaix .^2 ./ (2* bi.x .^ 2))); % x state variable\n Y(i+1) = Y(i) - dt*sum(w(i)*alphai.y ./ (bi.y) .^ 2 .* dtetaiy .* exp(-dtetaiy .^2 ./ (2* bi.y .^ 2))); % y state variable\n Z(i+1) = Z(i) - dt*sum(w(i)*alphai.z ./ (bi.z) .^ 2 .* dtetaiz .* exp(-dtetaiz .^2 ./ (2* bi.z .^ 2))); % z state variable\n %------------------------------------------------\n \n \nend\nDIP.x = X;\nDIP.y = Y;\nDIP.z = Z;\n", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/Tools/ECG_Analysis_Tools/MV/Tools/TWA_generator/DipoleGeneratorAbnormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6351778992666597}} {"text": "function [mu,dmu,k,gamma] = sparse_learning(Phi,T,lambda,iters,flag1,flag2,flag3)\n% *************************************************************************\n% \n% *** PURPOSE *** \n% Implements generalized versions of SBL and FOCUSS for learning sparse\n% representations from possibly overcomplete dictionaries.\n%\n%\n% *** USAGE ***\n% [mu,dmu,k,gamma] = sparse_learning(Phi,T,lambda,iters,flag1,flag2,flag3);\n%\n%\n% *** INPUTS ***\n% Phi = N X M dictionary\n% T = N X L data matrix\n% lambda = scalar trade-off parameter (balances sparsity and data fit)\n% iters = maximum number of iterations\n%\n% flag1 = 0: fast Mackay-based SBL update rules\n% flag1 = 1: fast EM-based SBL update rule\n% flag1 = 2: traditional (slow but sometimes better) EM-based SBL update rule\n% flag1 = [3 p]: FOCUSS algorithm using the p-valued quasi-norm\n%\n% flag2 = 0: regular initialization (equivalent to min. norm solution)\n% flag2 = gamma0: initialize with gamma = gamma0, (M X 1) vector\n%\n% flag3 = display flag; 1 = show output, 0 = supress output\n%\n% *** OUTPUTS ***\n% mu = M X L matrix of weight estimates\n% dmu = delta-mu at convergence\n% k = number of iterations used\n% gamma = M X 1 vector of hyperparameter values\n%\n%\n% *************************************************************************\n% Written by: David Wipf, david.wipf@mrsc.ucsf.edu\n% *************************************************************************\n \n\n% *** Control parameters ***\nMIN_GAMMA = 1e-16; \nMIN_DMU = 1e-12; \nMAX_ITERS = iters;\nDISPLAY_FLAG = flag3; % Set to zero for no runtime screen printouts\n\n\n% *** Initializations ***\n[N M] = size(Phi); \n[N L] = size(T);\n\nif (~flag2) gamma = ones(M,1); \nelse gamma = flag2; end; \n \nkeep_list = [1:M]';\nm = length(keep_list);\nmu = zeros(M,L);\ndmu = -1;\nk = 0;\n\n\n% *** Learning loop ***\nfor k=0:MAX_ITERS-1\n \n % *** Prune things as hyperparameters go to zero ***\n if (min(gamma) < MIN_GAMMA )\n\t\tindex = find(gamma > MIN_GAMMA);\n\t\tgamma = gamma(index);\n\t\tPhi = Phi(:,index);\n\t\tkeep_list = keep_list(index);\n m = length(gamma);\n \n if (m == 0) break; end;\n end;\n \n \n % *** Compute new weights ***\n G = repmat(sqrt(gamma)',N,1);\n PhiG = Phi.*G; \n [U,S,V] = svd(PhiG,'econ');\n \n [d1,d2] = size(S);\n if (d1 > 1) diag_S = diag(S); \n else diag_S = S(1); end;\n \n U_scaled = U(:,1:min(N,m)).*repmat((diag_S./(diag_S.^2 + lambda + 1e-16))',N,1); \n Xi = G'.*(V*U_scaled'); \n \n mu = Xi*T; \n \n % *** Update hyperparameters ***\n gamma_old = gamma;\n mu2_bar = sum(mu.^2,2);\n \n if (flag1(1) == 0)\n % MacKay fixed-point SBL\n R_diag = real( (sum(Xi.'.*Phi)).' );\n gamma = mu2_bar./(L*R_diag); \n \n elseif (flag1(1) == 1)\n % Fast EM SBL\n R_diag = real( (sum(Xi.'.*Phi)).' );\n gamma = sqrt( gamma.*real(mu2_bar./(L*R_diag)) ); \n \n elseif (flag1(1) == 2)\n % Traditional EM SBL\n PhiGsqr = PhiG.*G;\n Sigma_w_diag = real( gamma - ( sum(Xi.'.*PhiGsqr) ).' );\n gamma = mu2_bar/L + Sigma_w_diag;\n \n else\n % FOCUSS\n p = flag1(2);\n gamma = (mu2_bar/L).^(1-p/2);\n end;\n \n % *** Check stopping conditions, etc. ***\n if (DISPLAY_FLAG) disp(['iters: ',num2str(k),' num coeffs: ',num2str(m), ...\n ' gamma change: ',num2str(max(abs(gamma - gamma_old)))]); end; \nend;\n\n\n% *** Expand weights, hyperparameters ***\ntemp = zeros(M,1);\nif (m > 0) temp(keep_list,1) = gamma; end;\ngamma = temp;\n\ntemp = zeros(M,L);\nif (m > 0) temp(keep_list,:) = mu; end;\nmu = temp;\n \nreturn;\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/sparse_learning_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6351778991971618}} {"text": "function [dat, W, A, r_values] = proc_cspoc(dat, maxmin_flag, varargin)\n% PROC_CSPOC - Canonical Source Power Co-modulation Analysis (cSPoC)\n%\n% Optimizes spatial filters such that the power of the filtered signals are\n% maximally positively (or negatively) correlated. The function can be used\n% in two ways:\n% (1) The data of a single subject are bandpass filtered in multiple\n% frequency bands, using the function proc_filterbank\n% (2) The data of multiple subjects are bandpass filtered in a single\n% frequency band\n%\n%Synopsis:\n% [DAT, SPOC_W, SPOC_A, R_VALUES]= proc_cspoc(DAT, MINMAX_FLAG, )\n%\n%Arguments:\n% DAT - either a data structure of epoched data of one subject,\n% containing multiband filtered channels (obtained via\n% proc_filterbank), or a cell array, each cell containing a\n% data structure of epoched data that has been multiband\n% filtered\n% MINMAX_FLAG - either 1 for maximizing or -1 for minimizing correlation\n% OPT - struct or property/value list of optional properties:\n% .nComponentPairs - either the string 'all' or an integer, determining\n% the number of components pairs to be returned,\n% default: 'all'\n% .nRepeats - number of re-starts per component pair, default: 10\n% .maxIter - maximum number of optimizer iterations, default: 200\n% .averageOverEpochs - when optimizing the correlations, average the\n% source envelopes within epochs, default: false\n%\n%Returns:\n% DAT - updated data structure\n% SPOC_W - SPOC projection matrix (spatial filters, in the columns)\n% SPOC_A - estimated mixing matrix (activation patterns, in the columns)\n% LAMBDA - eigenvalue score of SPOC projections \n\nprops= {'nComponentPairs' 'all' 'STRING|DOUBLE[1]'\n 'nRepeats' 10 'DOUBLE[1]'\n 'averageOverEpochs' 0 'BOOLE'\n 'maxIter' 200 'DOUBLE[1]'\n };\n\nif nargin==0,\n dat = props; return\nend\n\ndat = misc_history(dat);\nmisc_checkType(dat, 'STRUCT(x clab y)|CELL');\n\nopt = opt_proplistToStruct(varargin{:});\nopt = opt_setDefaults(opt, props);\nopt_checkProplist(opt, props);\n\n%% contruct data cells\n% cSPoC is performed on one multi bandpass filtered data set\nif not(iscell(dat))\n % check that all clabs contain the string 'flt'\n if any(cellfun(@(x) isempty(x),cellfun(@(x) strfind(x,'flt'),dat.clab,'UniformOutput',0)))\n error('data are not band-pass filtered by proc_filterbank')\n end\n N = length(unique(str2mat(cellfun(@(x) x(end),dat.clab)')));\n X = cell(1,N);\n for ii = 1:N\n dat2 = proc_selectChannels(dat,sprintf('*flt%d',ii));\n X{ii} = dat2.x;\n end\n% cSPoC is performed on multiple single bandpass filtered data sets\nelse\n N = length(dat);\n X = cell(1,N);\n for ii = 1:N\n X{ii} = dat{ii}.x;\n end\nend\n \n%% run cSPoC\nopt = renameStructField(opt,'nComponentPairs','n_component_sets');\nopt = renameStructField(opt,'nRepeats','n_repeats');\nopt = renameStructField(opt,'averageOverEpochs','average_over_epochs');\n\n[W,A,r_values] = cspoc(X,maxmin_flag,opt);\n\n%% project the data onto cSPoC filters\ndatnew = [];\nfor ii = 1:N\n if not(iscell(dat))\n dat2 = proc_selectChannels(dat,sprintf('*flt%d',ii));\n else\n dat2 = dat{ii};\n end\n dat2 = proc_linearDerivation(dat2,W{ii},'prependix',sprintf('cspoc%d_',ii));\n datnew = proc_appendChannels(datnew,dat2);\nend\n\ndat = datnew;\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/processing/proc_cspoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6351765151813531}} {"text": "function [ fea, out ] = ex_spanner( varargin )\n%EX_SPANNER STL geometry import and stress calculation of a spanner.\n%\n% [ FEA, OUT ] = EX_SPANNER( VARARGIN ) Example to import a STL CAD\n% geometry and calculate displacements on a fixed spanner. The load\n% force may be distributed in the tangential load direction with the\n% force fraction parameter FRAC.\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% E scalar {190e3} Modulus of elasticity [N/mm^2]\n% nu scalar {0.29} Poissons ratio\n% force scalar {1000} Load force [N]\n% frac scalar {0} Fraction of stress against pulling direction\n% sfun string {sflag1} Shape function for displacements\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { 'E', 190e3;\n 'nu', 0.29;\n 'force', 1000;\n 'frac', 0;\n 'sfun', 'sflag1';\n 'iplot', 1;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\n\n\n% Define scaling factor m to mm.\nUSE_METERS = true;\ns = double( ~USE_METERS + USE_METERS*1e-3 );\n\n\n% Import (and scale) grid.\nfea.sdim = {'x','y','z'};\nfea.geom = impexp_stl( 'spanner1.stl', 'import', [], 'solid', 2, 'extend', 0 );\nfea.grid = gridgen( fea, 'hmax', 5, 'gridgen', 'robust', 'fid', opt.fid );\nfea.grid.p = fea.grid.p*s;\n\n\n% Add linear elasticity physics mode and define material parameters.\nfea = addphys( fea, @linearelasticity );\nfea.phys.el.sfun = { opt.sfun opt.sfun opt.sfun };\nfea.phys.el.eqn.coef{1,end} = { opt.nu };\nfea.phys.el.eqn.coef{2,end} = { opt.E/s^2 };\n\n\n% Set all boundaries to no load per default.\nn_bdr = max(fea.grid.b(3,:));\nbc_sel = cell(3,n_bdr);\n[bc_sel{:}] = deal(0);\n\n\n% Fix all displacements on mandible boundaries.\ni_fix = [13 14];\ni_force = [3 1];\nfaxis = [1 3];\n[bc_sel{:,i_fix}] = deal(1);\nfea.phys.el.bdr.coef{5} = bc_sel;\n\n\n% Apply force for x > 140 mm.\nforce = opt.force/(6*s*80*s);\nfea.phys.el.bdr.coef{7}{faxis(1),i_force(1)} = ['-',num2str((1-opt.frac)*force),'*(y>140*',num2str(s),')'];\nfea.phys.el.bdr.coef{7}{faxis(2),i_force(2)} = [num2str(opt.frac*force),'*(y>140*',num2str(s),')'];\n\n\n% Parse and solve problem.\nfea = parsephys(fea);\nfea = parseprob(fea);\nfea.sol.u = solvestat( fea, 'fid', opt.fid, 'icub', 1+str2num(strrep(opt.sfun,'sflag','')) );\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n subplot(1,2,1)\n postplot( fea, 'surfexpr', ['sqrt(u^2+v^2+w^2)/',num2str(s)] )\n view([30 20])\n title('Total displacement (mm)')\n\n subplot(1,2,2)\n DSCALE = 5;\n dp = zeros(size(fea.grid.p));\n for i=1:3\n dp(i,:) = DSCALE*evalexpr( fea.dvar{i}, fea.grid.p, fea );\n end\n fea_disp.grid = fea.grid;\n fea_disp.grid.p = fea_disp.grid.p + dp;\n plotgrid( fea_disp )\n title(['Displacement plot'])\n view([30 20])\nend\n\n\n% Error checking.\nu = fea.sol.u(unique(fea.eqn.dofm{1}(:)))/s;\nv = fea.sol.u(unique(fea.eqn.ndof(1)+fea.eqn.dofm{2}(:)))/s;\nw = fea.sol.u(unique(sum(fea.eqn.ndof(1:2))+fea.eqn.dofm{3}(:)))/s;\nout.disp = sqrt( u.^2 + v.^2 + w.^2 );\nout.pass = nan;\nif( ~(got.frac || got.E || got.nu || got.force) )\n out.pass = abs( max(out.disp) - 2.5 )/2.5 < 0.1;\nend\n\n\nif( nargout==0 )\n clear fea out\nelse\n fea.grid.p = fea.grid.p/s;\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_spanner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6351765151813531}} {"text": "function spm_MDP_urn\n% Demo for active inference with the urn task\n%__________________________________________________________________________\n%\n% This demonstration uses the Urn or Beads Task to illustrate how choice\n% behaviour can be simulated using active inference - in the context of\n% Markov decision processes. In the urn task, a succession of draws\n% from one of two urns are made and the agent has to decide whether the\n% balls are being drawn from an urn with predominantly red or green balls.\n% We model this in terms of a state-space with four dimensions: number of\n% balls drawn (n), number of green balls drawn (k), choice (undecided, red \n% or green)and the true (hidden) state of the urn (red or green). With\n% this relatively simple state-space, the utility of any hidden state is\n% simply quantified by the log-odds ratio of making a correct\n% decision. From binomial theory this is (2k - n)*log(p/(1 - p)), where p\n% is the proportion of red or green balls. Having defined the utility\n% function of states, we can then use the MDP formulation of active\n% inference using variational Bayes to simulate choice behaviour. \n%\n% This routine first provides an illustration of a game in which a decision\n% is delayed until the last draw to look at inferences during successive\n% draws - with a special focus on precision. The illustration here shows\n% a decrease in precision when an unexpected (green ball) is drawn during a\n% sequence of red balls.\n%\n% We then characterise changes in choice probability (and latency to the\n% decision) in terms of its dependency on threshold criteria (on the odds\n% ratio) and hyperpriors about precision (alpha or the scale parameter of a \n% standard gamma distribution). The routine concludes with an illustration \n% of how to estimate model parameters using the likelihood of observed\n% (simulated) choices.\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_MDP_urn.m 6592 2015-11-06 16:20:48Z guillaume $\n \n% set up and preliminaries\n%==========================================================================\nrng('default')\n\nT = 8; % number of trials in each game\nPa = .85; % proportion of red or green goals\n \n% hidden (and initial) states (a red urn with no drawers)\n%--------------------------------------------------------------------------\nD = zeros(T,T,3,2); % #balls - 1 x #green - 1 x #u x #urns\nD(1,1,1,1) = 1;\nS = spm_vec(D);\nD(1,1,1,2) = 1;\nD = spm_vec(D);\n\n \n% likelihood - everything is seen apart from the hidden states of the urn\n%--------------------------------------------------------------------------\nA = kron([1 1],eye(3*T*T));\n\n \n% transition probabilities (B{1} - wait; B{2} - red; B{3} - green)\n%--------------------------------------------------------------------------\nfor i = 1:6\n Bn{i,i} = kron(spm_speye(T,T),spm_speye(T,T));\nend\nBr = spm_speye(T,T,0)*Pa + spm_speye(T,T,-1)*(1 - Pa);\nBg = spm_speye(T,T,0)*(1 - Pa) + spm_speye(T,T,-1)*Pa;\nBn{1,1} = kron(Br,spm_speye(T,T,-1));\nBn{4,4} = kron(Bg,spm_speye(T,T,-1));\n \nB{1} = spm_cat(Bn);\nB{2} = kron(eye(2),kron([0 0 0;1 1 0;0 0 1],eye(T*T)));\nB{3} = kron(eye(2),kron([0 0 0;0 1 0;1 0 1],eye(T*T)));\n\n\n% priors over final state (exp(utility))\n%--------------------------------------------------------------------------\nL = zeros(T,T,3,2);\nW = zeros(T,T,3,2);\nrho = log(Pa/(1 - Pa));\nfor n = 0:(T - 1)\n W(n + 1,:,:,:) = - n/8;\n for k = 0:n\n L(n + 1,k + 1,2,1) = (n - 2*k)*rho;\n L(n + 1,k + 1,3,2) = (2*k - n)*rho;\n end\nend\nC = spm_softmax(spm_vec((L > 3) + W)*4);\n\n \n% allowable policies (one decision before the game ends)\n%--------------------------------------------------------------------------\nV = [ones(T,T) + eye(T,T), ones(T,T) + 2*eye(T,T)];\n \n \n% MDP Structure\n%==========================================================================\nMDP.T = T; % process depth (the horizon)\nMDP.S = S; % initial state\nMDP.A = A; % likelihood\nMDP.B = B; % transition probabilities (priors)\nMDP.C = C; % terminal cost probabilities (priors)\nMDP.D = D; % prior over initial states\nMDP.V = V; % allowable policies\n \n% Solve - an example game (with high offer at t = 10)\n%==========================================================================\nspm_figure('GetWin','Figure 1'); clf\n \n% create a sequence of draws (outcomes) - with and oddball on the 4th\n%--------------------------------------------------------------------------\nk = cumsum([0 0 0 1 0 0 0 0]);\na = [1 1 1 1 1 1 2];\no = zeros(1,length(a) - 1);\nfor n = 1:length(o)\n o(n) = sub2ind([T,T,3],n,k(n) + 1,1);\nend\n \n% Active inference (precluding a decision until the last trial)\n%--------------------------------------------------------------------------\nMDP.o = o; \nMDP.a = a;\nMDP.plot = gcf;\nMDP.N = 8;\nMDP = spm_MDP_game(MDP);\n \n% plot convergence and precision\n%--------------------------------------------------------------------------\nsubplot(4,2,7)\nplot(MDP.d)\nxlabel('Latency (updates)','FontSize',12)\nylabel('Precision of beliefs','FontSize',12)\ntitle('Expected precision','FontSize',16)\nspm_axis tight\n \n% deconvolve to simulate dopamine responses\n%--------------------------------------------------------------------------\nnd = length(MDP.d);\nK = tril(toeplitz(exp(-((1:nd) - 1)'/8)));\n \nsubplot(4,2,8)\nplot(pinv(K)*MDP.d(:)), hold on\nxlabel('Latency (updates)','FontSize',12)\nylabel('Precision of beliefs','FontSize',12)\ntitle('Simulated dopamine responses','FontSize',16)\nspm_axis tight\n\n\n% Illustrate dependency on parameters\n%==========================================================================\nspm_figure('GetWin','Figure 2'); clf\n\n% create a sequence of draws (outcomes) - no oddballs\n%--------------------------------------------------------------------------\nk = cumsum([0 0 0 0 0 0 0 0]);\no = zeros(1,length(k));\nfor n = 1:length(k)\n o(n) = sub2ind([T,T,3],n,k(n) + 1,1);\nend\n\n \n% probability distribution over time: P(1,:) is no action\n%--------------------------------------------------------------------------\nPrT = @(P) [1 cumprod(P(1,1:end - 1))].*(1 - P(1,:));\nMDP.plot = 0; % plot convergence\nMDP.N = 4; % number of variational iterations\nMDP.a = ones(1,T); % and action\nMDP.o = o; % and outcomes\n\n% beliefs about final state - decision threshold (log likelihood)\n%--------------------------------------------------------------------------\nDP = MDP;\nPF = [];\nDF = [];\np = linspace(0,8,8);\nfor i = 1:length(p)\n DP.C = spm_softmax(spm_vec((L > p(i)) + W)*4);\n DP = spm_MDP_game(DP);\n PF(i,:) = 1 - DP.P(1,:);\n DF(i,:) = PrT(DP.P);\nend\n \n% probability of accepting\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nplot(PF')\nxlabel('Latency (trials)','FontSize',12)\nylabel('Probability of deciding','FontSize',12)\ntitle('Increasing decision threshold','FontSize',16)\naxis square xy\n \n% distribution of acceptance latencies\n%--------------------------------------------------------------------------\nsubplot(2,2,2)\nplot(DF')\nxlabel('Latency (trials)','FontSize',12)\nylabel('Latency of decision','FontSize',12)\ntitle('Latency of decision','FontSize',16)\naxis square xy\n \n \n% Hyperpriors - prior precision (alpha)\n%--------------------------------------------------------------------------\nDP = MDP;\nPF = [];\nDF = [];\np = linspace(2,16,8);\nfor i = 1:length(p)\n DP.alpha = p(i);\n DP = spm_MDP_game(DP);\n PF(i,:) = 1 - DP.P(1,:);\n DF(i,:) = PrT(DP.P);\nend\n \n% probability of accepting\n%--------------------------------------------------------------------------\nsubplot(2,2,3)\nplot(PF')\nxlabel('Latency (trials)','FontSize',12)\nylabel('Probability of deciding','FontSize',12)\ntitle('Increasing prior precision','FontSize',16)\naxis square xy\n \n% distribution of acceptance latencies\n%--------------------------------------------------------------------------\nsubplot(2,2,4)\nplot(DF')\nxlabel('Latency (trials)','FontSize',12)\nylabel('Latency of decision','FontSize',12)\ntitle('Latency of decision','FontSize',16)\naxis square xy\n \n \n% Simulate multiple trials and try to infer prior precision (alpha)\n%==========================================================================\nspm_figure('GetWin','Figure 3'); clf\n \n \n% Simulate multiple trials and record likelihood\n%--------------------------------------------------------------------------\nMDP.plot = 0;\nMDP.N = 4;\n \np = linspace(2,16,8);\nfor t = 1:8\n \n % run game\n %----------------------------------------------------------------------\n MDP.s = [];\n MDP.o = [];\n MDP.a = [];\n MDP = spm_MDP_game(MDP);\n \n % place outcomes in DP\n %----------------------------------------------------------------------\n DP = MDP;\n [a j] = find(MDP.U);\n [o j] = find(MDP.O);\n DP.o = o;\n DP.a = a;\n y(t) = find(a > 1);\n \n % get log-likelihood for different parameter values\n %----------------------------------------------------------------------\n for i = 1:length(p);\n DP.alpha = p(i);\n DP = spm_MDP_game(DP);\n LL(i,t) = sum(log(DP.P(find(DP.U))));\n end\n \nend\n \n% approximate the MAP with the ML and use the Laplace assumption\n%--------------------------------------------------------------------------\nLp = sum(LL,2);\ndp = mean(diff(p,1));\ndLdpp = diff(Lp,2)/(dp^2);\n[l i] = max(Lp(2:end - 1) + (dLdpp < 0)*1024);\nCp = inv(-dLdpp(i));\nEp = p(i + 1);\n \n\n% plot responses\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nhist(y,1:T)\nxlabel('Latency','FontSize',12)\nylabel('Probability','FontSize',12)\ntitle('Distribution of responses','FontSize',16)\naxis square\n \n% plot log likelihood over trials\n%--------------------------------------------------------------------------\nsubplot(2,2,2)\nplot(p,LL - min(LL(:)))\nxlabel('Parameter','FontSize',12)\nylabel('Probability','FontSize',12)\ntitle('Log-likelihood over games','FontSize',16)\naxis square\n \n% plot likelihood\n%--------------------------------------------------------------------------\nsubplot(2,2,3)\nplot(p,Lp - min(Lp))\nxlabel('Parameter','FontSize',12)\nylabel('Log-likelihood','FontSize',12)\ntitle('Log-likelihood','FontSize',16)\naxis square\n \n% plot posterior\n%--------------------------------------------------------------------------\nsubplot(2,2,4)\ntp = 8;\npp = linspace(p(1),p(end),64);\nplot(pp,spm_Npdf(pp,Ep,Cp)), hold on\nplot([tp tp],[0 1/8],':'), hold off\nxlabel('Parameter','FontSize',12)\nylabel('Probability','FontSize',12)\ntitle('Posterior probability','FontSize',16)\naxis square\n \n \nreturn\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_urn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.63516326053847}} {"text": "function [ux,ispos] = psdfactor(x,K)\n% [ux,ispos] = psdfactor(x,K)\n%\n% PSDFACTOR UX'*UX Cholesky factorization\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%\n% disp('The SeDuMi binaries are not installed.')\n% disp('In Matlab, launch \"install_sedumi\" in the folder you put the SeDuMi files.')\n% disp('For more information see the file Install.txt.')\n% error(' ')\n\nKs = K.s;\nif isempty(Ks),\n ux = zeros(0,1);\n ispos = true;\n return\nend\nKq = Ks .* Ks;\nnr = K.rsdpN;\nnc = length(Ks);\nN = sum(Kq) + sum(Kq(nr+1:end));\nux = zeros(N,1);\nxi = length(x) - N;\nui = 0;\nfor i = 1 : nc,\n ki = Ks(i);\n qi = Kq(i);\n XX = x(xi+1:xi+qi);\n xi = xi + qi;\n if i > nr,\n XX = XX + 1j*x(xi+1:xi+qi);\n xi = xi + qi;\n end\n XX = reshape(XX,ki,ki);\n [XX,flag]=chol(XX,'lower');\n if flag,\n ispos = false;\n return\n end\n XX = XX + tril(XX,-1)';\n ux(ui+1:ui+qi) = real(XX);\n ui = ui + qi;\n if i > nr,\n ux(ui+1:ui+qi) = imag(XX);\n ui = ui + qi;\n end\nend\nispos = true;\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/sedumi/psdfactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6351632529645633}} {"text": "classdef TP3 < PROBLEM\n% \n% Test problem for robust multi-objective optimization\n% delta --- 0.05 --- Maximum disturbance degree\n% H --- 50 --- Number of disturbances\n\n%------------------------------- Reference --------------------------------\n% A. Gaspar-Cunha, J. Ferreira, and G. Recio, Evolutionary robustness\n% analysis for multi-objective optimization: benchmark problems, Structural\n% and Multidisciplinary Optimization, 2014, 49: 771-793.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n delta; % Maximum disturbance degree\n H; % Number of disturbances\n end\n methods\n %% Default settings of the problem\n function Setting(obj)\n [obj.delta,obj.H] = obj.ParameterSet(0.05,50);\n obj.M = 2;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n PopObj(:,1) = 1 - PopDec(:,1).^2;\n g = 1 + 10*mean(PopDec(:,2:end),2);\n PopObj(:,2) = sin(pi/2*PopDec(:,1)).*g;\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(~,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = sin(pi/2*sqrt(1-R(:,1)));\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n %% Calculate the metric value\n function score = CalMetric(obj,metName,Population)\n switch metName\n case {'Mean_IGD','Mean_HV','Worst_IGD','Worst_HV'}\n score = feval(metName,Population,obj);\n otherwise\n score = feval(metName,Population,obj.optimum);\n end\n end\n %% Perturb solutions multiple times\n function PopX = Perturb(obj,PopDec,N)\n if nargin < 3; N = obj.H; end\n Delta = repmat(obj.delta.*(obj.upper-obj.lower),N*size(PopDec,1),1);\n w = UniformPoint(N,obj.D,'Latin');\n Dec = 2*Delta.*w(reshape(repmat(1:end,size(PopDec,1),1),1,[]),:) + repmat(PopDec,N,1) - Delta;\n Dec = obj.CalDec(Dec);\n PopX = SOLUTION(Dec,obj.CalObj(Dec),obj.CalCon(Dec));\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/TP/TP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656671, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6350899206113725}} {"text": "function [vertices, faces] = curveToMesh(curve, varargin)\n%CURVETOMESH Create a mesh surrounding a 3D curve.\n%\n% [V, F] = curveToMesh(CURVE)\n% Computes the vertices and the faces of the mesh surrounding the\n% specified 3D curve.\n%\n% [V, F] = curveToMesh(CURVE, THICKNESS)\n% Specifies the thickness of the mesh (distance between mesh vertices and\n% curve vertices). Default is 0.5.\n%\n% [V, F] = curveToMesh(CURVE, THICKNESS, NCORNERS)\n% Also specifies the number of mesh vertices around each curve vertex.\n% Default is 8.\n%\n%\n% Example\n% % Creates a tubular mesh around a trefoil knot curve\n% t = linspace(0, 2*pi, 200)';\n% x = sin(t) + 2 * sin(2 * t);\n% y = cos(t) - 2 * cos(2 * t);\n% z = -sin(3 * t);\n% curve = [x, y, z];\n% [v2, f2] = curveToMesh(curve, .5, 16);\n% figure; \n% drawMesh(v2, f2);\n% axis equal; view(3);\n% axis([-4 4 -4 4 -2 2]);\n% \n% See also\n% meshes3d, torusMesh, surfToMesh\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2015-01-07, using Matlab 8.4.0.150421 (R2014b)\n% Copyright 2015 INRA - Cepia Software Platform.\n\nradius = .1;\nif nargin > 1\n radius = varargin{1};\nend\n\nnCorners = 8;\nif nargin > 2\n nCorners = varargin{2};\nend\n\nnNodes = size(curve, 1);\nnVerts = nNodes * nCorners;\n\nvertices = zeros(nVerts, 3);\n\n% create reference corners, that will be rotated and translated\nt = linspace(0, 2*pi, nCorners + 1)';\nt(end) = [];\nbaseCorners = radius * [cos(t) sin(t) zeros(size(t))];\n\nfor iNode = 1:nNodes\n % coordinate of current node\n node = curve(iNode, :);\n \n % compute local tangent vector\n iNext = mod(iNode, nNodes) + 1;\n tangentVector = normalizeVector3d(curve(iNext, :) - node);\n\n % convert to spherical coordinates\n [theta, phi, rho] = cart2sph2(tangentVector); %#ok\n \n % apply transformation to place corners around current node\n rotY = createRotationOy(theta);\n rotZ = createRotationOz(phi);\n trans = createTranslation3d(node);\n transformMatrix = trans * rotZ * rotY;\n corners = transformPoint3d(baseCorners, transformMatrix);\n \n % concatenate with other corners\n vertices( (1:nCorners) + (iNode - 1) * nCorners, :) = corners;\nend\n\n% indices of vertices\ninds = (1:nVerts)';\nadd1 = repmat([ones(nCorners-1, 1) ; 1-nCorners], nNodes, 1);\n\n% generate faces\nfaces = [inds ...\n mod(inds + add1 - 1, nVerts) + 1 ...\n mod(inds + nCorners + add1 - 1, nVerts) + 1 ...\n mod(inds + nCorners - 1, nVerts) + 1];\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/curveToMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6350757658702363}} {"text": "function fl = luflops (L, U)\n%LUFLOPS compute the flop count for sparse LU factorization\n%\n% Example:\n% fl = luflops (L,U)\n%\n% Given a sparse LU factorization (L and U), return the flop count required\n% by a conventional LU factorization algorithm to compute it. L and U can\n% be either sparse or full matrices. L must be lower triangular and U must\n% be upper triangular. Do not attempt to use this on the permuted L from\n% [L,U] = lu (A). Instead, use [L,U,P] = lu (A) or [L,U,P,Q] = lu (A).\n%\n% Note that there is a subtle undercount in this estimate. Suppose A is\n% completely dense, but during LU factorization exact cancellation occurs,\n% causing some of the entries in L and U to become identically zero. The\n% flop count returned by this routine is an undercount. There is a simple\n% way to fix this (L = spones (L) + spones (tril (A))), but the fix is partial.\n% It can also occur that some entry in L is a \"symbolic\" fill-in (zero in\n% A, but a fill-in entry and thus must be computed), but numerically\n% zero. The only way to get a reliable LU factorization would be to do a\n% purely symbolic factorization of A. This cannot be done with\n% symbfact (A, 'col').\n%\n% See NA Digest, Vol 00, #50, Tuesday, Dec. 5, 2000\n%\n% See also symbfact\n\n% Copyright 1998-2007, Timothy A. Davis\n\n\nLnz = full (sum (spones (L))) - 1 ;\t% off diagonal nz in cols of L\nUnz = full (sum (spones (U')))' - 1 ;\t% off diagonal nz in rows of U\nfl = 2*Lnz*Unz + sum (Lnz) ;\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/COLAMD/MATLAB/luflops.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6350757658702361}} {"text": "% runBenchmarkSuccessRate.m\n% \n% This example benchmarks algorithms based on their ability to reconstruct\n% a synthetic signal (random Gaussian) using synthetic measurements \n% (random Gaussian). The benchmark shows how the\n% different methods behave as the number of measurements increases. The\n% y-axis plots the success rate (rate of exact signal recovery). This is\n% done by setting params.policy='successrate'.\n%\n% The algorithms currently used in this implementation are all instances of\n% PhaseMax, but with different levels of accuracy in the initializer. To\n% control the level of initialization accuracy, we set the initializer to\n% \"angle\", and specify the angle between the true signal, and the initial\n% guess.\n% \n% This script does the following:\n% \n% 1. Set up parameters and create a list of algorithm structs. \n%\n% 2. Invoke the general benchmark function benchmarkPR. A graph of errors\n% (under specified error metrics) of different algorithms will be shown.\n%\n% The benchmark program compares the performance of specified algorithms on\n% 1D gaussian measurements that have different m/n ratio(i.e. the ratio\n% between the number of measurements and the number of unknowns).\n%\n%\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n%% -----------------------------START----------------------------------\n\n\nclc\nclear\nclose all\n\n%% 1.Set up parameters\n% Choose x label (values shown on the x axis of the benchmark plot) and \n% y label (values shown on the y-axis). The value on the x axis is the m/n\n% ratio. The value on the y axis is 'reconerror', which is the relative\n% 2-norm difference between the true and recovered signal.\nxitem = 'm/n';\nxvalues = 2:.5:12; \nyitem = 'reconerror';\n\n% Choose Dataset and set up dataSet '1DGaussian' specific parameters\ndataSet = '1DGaussian';\n\n% Set up general parameters\nparams.verbose = false;\nparams.numTrials = 20; % run several random trials for each scenario, and report average results\nparams.n = 500; % num of unknown elements\nparams.isComplex = true; % use complex matrices? or just stick to real?\nparams.policy = 'successrate';\t% use the successrate\nparams.successConstant = 1e-4;\n\n% Each of these algorithm is an instance of PhaseMax. However, they each \n% are initialized with starting points of different accuracies. The \n% \"angle\" initializer grabs the \"initAngle\" entry from the options, and\n% produces an initializer that makes this angle with the true signal.\npmax25 = struct('algorithm','phasemax','initMethod','angle'); \npmax25.tol=1e-6;\npmax25.initAngle=25/360*2*pi;\n\npmax36 = struct('algorithm','phasemax','initMethod','angle'); \npmax36.tol=1e-6;\npmax36.initAngle=36/360*2*pi;\n\npmax45 = struct('algorithm','phasemax','initMethod','angle'); \npmax45.tol=1e-6;\npmax45.initAngle=45/360*2*pi;\n\n% Grab your pick of algorithms.\nalgorithms = {pmax25,pmax36,pmax45};\n\n\n% Run benchmark\nresults = benchmarkSynthetic(xitem, xvalues, yitem, algorithms, dataSet, params);\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/benchmarks/runBenchmarkSuccessRate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6350757437021137}} {"text": "function [NF,NL,NQc,NH,NPinf,NdF,NdQc,NdPinf,T] = ss_balance(F,L,Qc,H,Pinf,dF,dQc,dPinf)\n% SS_BALANCE - Balance state space model for improved numerical stability\n%\n% Syntax:\n% [F,L,Qc,H,Pinf,dF,dQc,dPinf,T] = ss_balance(F,L,Qc,H,Pinf,dF,dQc,dPinf)\n%\n% In:\n% F - Feedback matrix\n% L - Noise effect matrix\n% Qc - Spectral density of white noise process w(t)\n% H - Observation model matrix\n% Pinf - Covariance of the stationary process\n% dF - Derivatives of F w.r.t. parameters\n% dQc - Derivatives of Qc w.r.t. parameters\n% dPinf - Derivatives of Pinf w.r.t. parameters\n%\n% Out:\n% (...) - As above, but balanced\n% T - T is the balancing matrix from 'balance'\n%\n% Description:\n% This function takes the SDE state space model matrices as inputs and\n% outputs the same matrices, but in a numerically more stable form. \n% This balancing is based on the Matlab 'balance' function (see the\n% reference).\n%\n% The state space model is given as follows in terms of a stochastic \n% differential equation\n%\n% df(t)/dt = F f(t) + L w(t),\n%\n% where w(t) is a white noise process with spectral denisty Qc. The \n% observation model matrix is denoted by matrix H.\n%\n% References:\n% [1] Beresford N. Parlett and Christian Reinsch (1969). Balancing \n% a matrix for calculation of eigenvalues and eigenvectors. \n% Numerische Mathematik, 13(4): 293-304.\n%\n% See also:\n% BALANCE\n%\n% Copyright:\n% 2014 Arno Solin and Simo Sarkka\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%% Balance the state space model\n\n % This is based on the following:\n %\n % dx/dt = F x + L w\n % y = H x\n %\n % Let T z = x, which gives\n %\n % dz/dt = inv(T) F T z + inv(T) L w\n % y = H T z\n %\n % See also: [A,B,C,E,S,P] = aebalance(A,B,C,E)\n \n % Balance the dynamic model matrix\n [T,NF] = balance(F);\n \n % Balance noise effect matrix\n NL = T\\L;\n \n % Balance the measurement model\n NH = H*T;\n \n % Balance spectral density\n NQc = Qc;\n \n % Balance stationary state covariance matrix\n if nargin < 5\n NPinf = [];\n else\n L = chol(Pinf,'lower');\n LL = T\\L;\n NPinf = LL*LL';\n %NPinf = T\\Pinf/T;\n end\n \n % Balance partial derivatives in F\n if nargin < 6\n NdF = [];\n else\n NdF = dF;\n for j=1:size(dF,3)\n NdF(:,:,j) = T\\dF(:,:,j)*T;\n end\n end\n \n % Balane partial derivatives in dQc;\n if nargin < 7\n NdQc = [];\n else\n NdQc = dQc;\n end\n \n % Balance partial derivatives in dF\n if nargin < 8\n NdPinf = [];\n else\n NdPinf = dPinf;\n for j=1:size(dF,3)\n NdPinf(:,:,j) = T\\dPinf(:,:,j)/T;\n end\n end\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/ss_balance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6350474716833202}} {"text": "function exact = p04_exact ( )\n\n%*****************************************************************************80\n%\n%% P04_EXACT returns the exact integral for problem 4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the value of the integral.\n%\n exact = ( sqrt ( 32.0 ) / 3.0 ) * ( sqrt ( 27.0 ) - sqrt ( 8.0 ) - 1.0 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int_2d/p04_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.635033603530958}} {"text": "function g = p14_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P14_G evaluates the gradient for problem 14.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n for j = 1 : n\n\n if ( mod ( j, 2 ) == 1 )\n g(j) = - 2.0 * ( 1.0 - x(j) );\n else\n g(j) = 200.0 * ( x(j) - x(j-1) * x(j-1) );\n g(j-1) = g(j-1) - 400.0 * x(j-1) * ( x(j) - x(j-1) * x(j-1) );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p14_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.6349332461333863}} {"text": "%% Ellipse Based Shape Parameters\n%\n%%\n% In this section we discuss geometric properties of grains that are\n% related to ellipses fitted to the grains. Additionally to the orientation\n% |omega|, and the lengths |a|, |b| of the long axis and short axes that\n% are computed by the command the following properties based on the fitted\n% ellipses are avaiable.\n%\n% || || long axis as @vector3d || || short axis as @vector3d ||\n% || || midpoint || || long axis / short axis ||\n%\n% In order to demonstrate these properties we start by reconstructing the\n% grain structure from a sample EBSD data set.\n\n% load sample EBSD data set\nmtexdata forsterite silent\n\n% reconstruct grains and smooth them \n[grains, ebsd.grainId] = calcGrains(ebsd('indexed'),'angle',5*degree);\nebsd(grains(grains.grainSize<10)) = [];\n[grains, ebsd.grainId] = calcGrains(ebsd('indexed'),'angle',5*degree);\ngrains(grains.isBoundary) = [];\n\ngrains=smooth(grains('indexed'),10,'moveTriplePoints');\n\n% plot the grains\nplot(grains,'micronbar','off','lineWidth',2)\n\n%% Fit Ellipses\n%\n% The basic command for fitting ellipses is \n\n[omega,a,b] = grains.fitEllipse;\n\nplotEllipse(grains.centroid,a,b,omega,'lineColor','w','linewidth',2)\n\n%%\n% The returned variable |omega| is the angle describing the rotation of the\n% ellipses and |a| and |b| are the length of the longest and shortest half\n% axis. The midpoints of the ellipses can be computed by the command\n% . Note, that the ellipses are\n% scaled such that the area of the ellipse coincides with the actual grain\n% area. Alternatively, one can also scale the ellipse to fit the boundary\n% length by using the option |boundary|.\n%\n%% Long and Short Axes\n%\n% The direction of the long and the short axis of the fitted ellipse can be\n% obtained by the comands and\n% . These directions are only\n% well defined if the fitted ellipse is not to close to a perfect circle. A\n% measure for how distinct the ellipse is from a perfect circle is the\n% which is defined as the quotient\n% $a/b$ between the longest and the shortest axis. For a perfect circle\n% the apect ratio is $1$ and increases to infinity when the ellipse becomes\n% more and more elongated.\n%\n% Lets colorize the grains by their apect ratio and plot on top the long\n% axis directions:\n\n% visualize the aspect ratio\nplot(grains,grains.aspectRatio,'linewidth',2,'micronbar','off')\nsetColorRange([0,4])\nmtexColorbar('title','aspect ratio')\n\n% and on top the long axes\nhold on\nquiver(grains,grains.longAxis,'Color','white')\nhold off\n\n%% Shape perfered orientation\n%\n% If we look at grains, we might wonder if there is a characteristic\n% difference in the grain shape fabric between e.g. Forsterite and\n% Enstatite. In contrast to crystal prefered orientations which which\n% describe on the alignment of the atome lattices the shape prefered\n% orientation (SPO) describes the algnment of the grains by shape in the\n% bulk fabric. \n%\n% *Long Axis Distribution*\n% \n% The most direct way to analyse shape prefered orientations are rose\n% diagrams of the distribution of the grain long axes. For those diagrams\n% it is useful to weight the long axis by the grain area such that larger\n% grains have a bigger impact on the distribution and by the aspect ratio\n% as for grains with a small aspect ratio the long axis is not so well\n% defined.\n\nnumBin = 50;\n\nsubplot(1,2,1)\nweights = grains('forsterite').area .* (grains('forsterite').aspectRatio-1);\nhistogram(grains('forsterite').longAxis,numBin, 'weights', weights)\ntitle('Forsterite')\n\nsubplot(1,2,2)\nweights = grains('enstatite').area .* (grains('enstatite').aspectRatio - 1);\nhistogram(grains('enstatite').longAxis,numBin,'weights',weights)\ntitle('Enstatite')\n\n%% \n% Instead of the histogram we may also fit a circular density distribution\n% to the to the long axes using the command .\n\ntdfForsterite = calcDensity(grains('forsterite').longAxis,...\n 'weights',norm(grains('forsterite').longAxis),'halfwidth');\n\ntdfEnstatite = calcDensity(grains('enstatite').longAxis,...\n 'weights',norm(grains('enstatite').longAxis));\n\nplotSection(tdfForsterite, vector3d.Z, 'linewidth', 3)\n\nhold on\nplotSection(tdfEnstatite, vector3d.Z, 'linewidth', 3)\nhold off\n\n%%\n% \n\nclose all\n[freq,bc] = calcTDF(grains('fo'),'binwidth',3*degree);\nplotTDF(bc,freq/sum(freq));\n\n[freq,bc] = calcTDF(grains('en'),'binwidth',3*degree);\nhold on\nplotTDF(bc,freq/sum(freq));\nhold off\nlegend('Forsterite','Enstatite','Location','eastoutside')\nmtexTitle('long axes')\n\n%% *Shortest Caliper Distribution*\n%\n% Alternatively, we may wonder if the common long axis of grains is does\n% suitably represented by the direction normal to the shortest caliper of\n% the grains. This can particularly be the case for aligned rectangular\n% particles. The command also takes a list of\n% angles and a list of weights or lengths as input\n\ncPerpF = caliper(grains('fo'),'shortestPerp');\ncPerpE = caliper(grains('en'),'shortestPerp');\n\n[freqF,bcF] = calcTDF(cPerpF.rho, 'weights',cPerpF.norm, 'binwidth',3*degree);\n[freqE,bcE] = calcTDF(cPerpE.rho, 'weights',cPerpE.norm, 'binwidth',3*degree);\n\nplotTDF(bcF,freqF/sum(freqF));\nhold on\nplotTDF(bcE,freqE/sum(freqE));\nhold off\nlegend('Forsterite','Enstatite','Location','eastoutside')\n\n\n%%\n% We can also smooth the functions with a wrapped Gaussian\n\npdfF = circdensity(bcF, freqF, 5*degree,'sum');\npdfE = circdensity(bcE, freqE, 5*degree,'sum');\n\nplotTDF(bcF,pdfF);\nhold on\nplotTDF(bcE,pdfE);\nhold off\nmtexTitle('n.t.s. density estimate')\nlegend('Forsterite','Enstatite','Location','eastoutside')\n\n%%\n% Because best fit ellipses are always symmetric and the projection\n% function of an entire grain always only consider the convex hull, grain\n% shape fabrics can also be characterized by the the length weighted rose\n% diagram of the directions of grain boundary segments.\n \n[freqF,bcF] = calcTDF(grains('fo').boundary);\nplotTDF(bcF,freqF/sum(freqF));\npdfF = circdensity(bcF, freqF, 5*degree,'sum');\nhold on\nplotTDF(bcF,pdfF);\nhold off\nmtexTitle('Forsterite grain boundaries')\nnextAxis\n[freqE,bcE] = calcTDF(grains('en').boundary);\nplotTDF(bcE,freqE/sum(freqE));\npdfE = circdensity(bcE, freqE, 5*degree,'sum');\nhold on\nplotTDF(bcE,pdfE);\nhold off\nmtexTitle('Enstatite grain boundaries')\n\n%% Characteristic Shape\n%\n% Note that this distribution is very prone to inherit artifacts based on\n% the fact that most EBSD maps are sampled on a regular grid. We tried to\n% overcome this problem by heavily smoothing the grain boundary. The little \n% peaks at 0 and 90 degree are very likely still related to this sampling\n% artifact.\n%\n% If we just add up all the individual elements of the rose diagram in\n% order of increasing angles, we derive the characteristic shape. It can be\n% regarded as to represent the average grain shape.\n\n[csAngleF, csRadiusF] = characteristicShape(bcF,freqF);\n[csAngleE, csRadiusE] = characteristicShape(bcE,freqE);\n\nclose all\nplotTDF(csAngleF,csRadiusF,'nolabels');\nhold on\nplotTDF(csAngleE,csRadiusE,'nolabels');\nhold off\nlegend('Forsterite','Enstatite','Location','eastoutside')\n\n%%\n% We may wonder if these results are significantly different or not\n% TODO: get deviation from an ellipse etc", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/Grains/EllipseBasedParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.6349332356778021}} {"text": " % Diferite reprezentari grafice speciale\n % **************************************\n\t\t\t% ***** Grafica nr.1. *****\n\tsubplot(4,2,1)\n\t\t\t% Desenarea unui poligon\n\t\t\t% - desemnarea coordonatelor varfurilor\n\tx=[0 2 4 3 1 0];\n\ty=[0 1 2 4 3 0];\n\t\t\t% - reprezentarea poligonului\n\tfill(x,y,'y')\n\t\t\t% - plasarea unui titlu\n\ttitle('FILL')\n\t\t\t% ***** Grafica nr.2. *****\n\tsubplot(4,2,2)\n\tx=0:pi/10:2*pi;\n\ty=sin(x);\n\t\t\t% Reprezentarea grafica utilizand comanda bar\n\tbar(x,y)\n\ttitle('BAR')\n\t\t\t% - fixarea limitelor axelor de coordonate\n\taxis([0 2*pi -1.1 1.1])\n\t\t\t% ***** Grafica nr.3. *****\n\tsubplot(4,2,3)\n\t\t\t% Reprezentarea grafica utilizand comanda stem\n\tstem(x,y)\n\ttitle('STEM')\n\taxis([0 2*pi -1.1 1.1])\n\t\t\t% ***** Grafica nr.4. *****\n\tsubplot(4,2,4)\n\t\t\t% Reprezentarea grafica utilizand comanda stairs\n\tstairs(x,y)\n\ttitle('STAIRS')\n\taxis([0 2*pi -1.1 1.1])\n\t\t\t% ***** Grafica nr.5. *****\n\tsubplot(4,2,5)\n\t\t\t% Generarea unui vector de eroare aleatoare \n\te=rand(size(x)).*y./5;\n\t\t\t% Reprezentarea grafica utilizand comanda errorbar\n\terrorbar(x,y,e)\n\ttitle('ERRORBAR')\n\taxis([0 2*pi -1.1 1.1])\n\t\t\t% ***** Grafica nr.6. *****\n\tsubplot(4,2,6)\n\t\t\t% Regenerarea vectorului x cu un pas mai mic\n\tx=0:pi/100:2*pi;\n\t\t\t% Reincarcarea vectorului y\n\ty=sin(x);\n\t\t\t% Reprezentarea grafica utilizand comanda hist\n\thist(y,20)\n\ttitle('HIST')\n % ***** Grafica nr.7. *****\n\tsubplot(4,2,7)\n\t\t\t% Reprezentarea grafica utilizand comanda pie\n\tpie([2 4 3 6],{'Nord','Sud','Est','Vest'})\n\ttitle('PIE')\n % ***** Grafica nr.8. *****\n\tsubplot(4,2,8)\n\t\t\t% Reprezentarea grafica utilizand comanda area\n\tz = [1,5,6;3,4,7;2,8,3;2,6,10];\n\tarea(z)\n\ttitle('AREA')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8416-widely-used-programming-environments-in-electrical-engineering-matlab/6/Ex_6_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6349332317141153}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% PARAMETERS Returns a data structure containing the parameters of the\n% example 3 DOF planar robot.\n%\n% Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche. \n% email: arturo.gil@umh.es date: 05/03/2012\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction robot = parameters()\n\nrobot.name='Example 3DOF planar arm';\n\n%kinematic data DH parameters\nrobot.DH.theta='[q(1) q(2) q(3)]';\nrobot.DH.d='[0 0 0]';\nrobot.DH.a='[1 1 1]';\n%robot.DH.a='[3 1 0.5]';\nrobot.DH.alpha='[0 0 0]';\n\n%number of degrees of freedom\nrobot.DOF = 3;\n\n%Jacobian matrix\nrobot.J=[];\n\nrobot.J=['[-a(1)*sin(q(1))-a(2)*sin(q(1)+q(2))-a(3)*sin(q(1)+q(2)+q(3)) -a(2)*sin(q(1)+q(2))-a(3)*sin(q(1)+q(2)+q(3)) -a(3)*sin(q(1)+q(2)+q(3));' ... \n 'a(1)*cos(q(1))+a(2)*cos(q(1)+q(2))+a(3)*cos(q(1)+q(2)+q(3)) a(2)*cos(q(1)+q(2))+a(3)*cos(q(1)+q(2)+q(3)) a(3)*cos(q(1)+q(2)+q(3));' ...\n ' 0 0 0;' ...\n ' 0 0 0;' ...\n ' 0 0 0;' ...\n ' 1 1 1]'];\n\n\nrobot.kind=['R' 'R' 'R'];\n\n\n%Function name to compute inverse kinematic\nrobot.inversekinematic_fn = 'inversekinematic_3dofplanar(robot, T)';\nrobot.directkinematic_fn = 'directkinematic(robot, q)';\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n deg2rad(-180) deg2rad(180);\n deg2rad(-180) deg2rad(180)]; %Axis 2, minimum, maximum\n \n \n \n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = []; %empty, not available\n\nrobot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time\n% end effectors maximum velocity\nrobot.linear_velmax = 0; %m/s, example, not available\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.path = pwd;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%GRAPHICS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%read graphics files\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [255 20 40]./255;\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis=[-3.5 3.5 -3.5 3.5 0 1];\nrobot = read_graphics(robot);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%DYNAMIC PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction in the computations\nrobot.dynamics.friction=0;\n\n%link masses (kg)\nrobot.dynamics.masses=[1 1 1];\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[-0.5 0 0; %(rx, ry, rz) link 1\n -0.5 0 0;\n -0.5 0 0];%(rx, ry, rz) link 2\n\n%link masses\nm1 = robot.dynamics.masses(1);\nm2 = robot.dynamics.masses(2);\nm3 = robot.dynamics.masses(3);\n\na=eval(robot.DH.a);\nL1 = a(1);\nL2 = a(2);\nL3 = a(3);\n\n%Momentos de inercia de cada eslabon.\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, por cada fila\nrobot.dynamics.Inertia=[0 m1*L1^2/3 m1*L1^2/3 0\t0\t0;\n 0 m2*L2^2/3 m2*L2^2/3 0\t0\t0;\n 0 m3*L3^2/3 m3*L3^2/3 0\t0\t0];\n \n%Actuator rotor inertia\nrobot.motors.Inertia=[0 0 0];\n%Reduction ratio motor/joint speed\nrobot.motors.G=[1 1 1];\n%consider friction\nrobot.friction=0;\n%Viscous friction factor, motor referred\n%robot.B = [1e-3 1e-3 1e-3];\nrobot.motors.Viscous = [10 10 10];\n%Coulomb friction, motor referred\nrobot.motors.Coulomb = [0 0;\n 0 0;\n 0 0];\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/example/3dofplanar/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6348979804859382}} {"text": "function c = gsp_lanczos_op(G,fi,s,param)\n%GSP_LANCZOS_OP Perform the lanczos approximation of the signal s\n\nif nargin < 4, param = struct; end\nif ~isfield(param,'verbose'), param.verbose = 1; end;\nif ~isfield(param,'order'), param.order = 30; end\n\n\nNf = numel(fi);\nNv = size(s,2);\nc = zeros(G.N*Nf,Nv);\n\nfor jj = 1:Nv\n \n if sum(abs(s(:,jj)))>eps\n [V,H] = lanczos(G.L, param.order, s(:,jj));\n\n [Uh, Eh] = eig(H);\n\n\n Eh = diag(Eh);\n Eh(Eh<0) = 0;\n fie = gsp_filter_evaluate(fi,Eh);\n V = V*Uh;\n\n\n for ii=1:Nf\n c((1:G.N) + G.N*(ii-1),jj) = V * (fie(:, ii) .* (V'*s(:,jj)));\n end\n else\n c(:,jj) = 0;\n end\nend\n\n% [V,H] = lanczos(G.L, k, s);\n% \n% for jj = 1:Nv\n% ind = (1:size(H,1))+size(H,1)*(jj-1);\n% [Uh, Eh] = eig(H(:,ind));\n% \n% \n% Eh = diag(Eh);\n% fie = gsp_filter_evaluate(fi,Eh);\n% V(:,ind) = V(:,ind)*Uh;\n% \n% \n% for ii=1:Nf\n% c((1:G.N) + G.N*(ii-1),jj) = V(:,ind) * fie(:, ii) .* (V(:,ind)'*s(:,jj));\n% end\n% end\n\nend\n\n\n\n\nfunction [V,H,orth] = lanczos(A,order,x)\n\n[N,M] = size(x);\n\n% normalization\nnorm2vec = @(x) (sum(x.^2,1)).^0.5;\nq = x./repmat(norm2vec(x),N,1);\n\n% Initialization\nhiv =0:order:(order*M-1); % helping indice vector\n\nV = zeros(N,M*order);\nV(:,1+hiv) = q;\n\n\nH = zeros(order+1,order*M);\n\nr = A*q;\nH(1,1+hiv) = sum(q .* r, 1 );\nr = r - repmat(H(1,1+hiv),N,1).*q; \nH(2,1+hiv) = norm2vec(r);\n\nif (nargout > 2)\n orth = zeros(M,1);\n orth(1) = norm(V'*V - M);\nend\n\nfor k = 2:order\n \n if (sum(abs(H(k,k-1+hiv))) <= eps)\n H = H(1:k-1,sum_ind(1:k-1,hiv));\n V = V(:,sum_ind(1:k-1,hiv));\n if (nargout > 2)\n orth = orth(1:k-1);\n end\n return;\n end\n \n H(k-1,hiv+k) = H(k,hiv+k-1);\n v = q;\n q = r./repmat(H(k-1,k+hiv),N,1);\n V(:,k+hiv) = q;\n \n r = A*q;\n r = r - repmat(H(k-1,k+hiv),N,1).*v;\n H(k,k+hiv) = sum(q .* r, 1 );\n \n r = r - repmat(H(k,k+hiv),N,1).*q;\n % The next line has to be checked\n r = r - V*(V'*r); % full reorthogonalization\n H(k+1,k+hiv) = norm2vec(r);\n \n if (nargout > 2)\n orth(k) = [orth, norm(V'*V - M)];\n end\nend\n \nH = H(1:order,1:order);\n\n\n% H = zeros(order+1,order);\n% \n% q = x/norm(x);\n% V(:,1) = q;\n% \n% r = A*q;\n% \n% H(1,1) = q'*r;\n% r = r - H(1,1)*q ; \n% H(2,1) = norm(r);\n% \n% if (nargout > 2)\n% orth = norm(V'*V - 1);\n% end\n% \n% for k = 2:order\n% \n% if (abs(H(k,k-1)) <= 1e-15)\n% H = H(1:k-1,1:k-1);\n% return;\n% end\n% \n% H(k-1,k) = H(k,k-1);\n% v = q;\n% q = r/H(k-1,k);\n% V(:,k) = q;\n% \n% r = A*q;\n% r = r - H(k-1,k)*v;\n% H(k,k) = q'*r;\n% \n% r = r - H(k,k)*q;\n% r = r - V*(V'*r); % full reorthogonalization\n% H(k+1,k) = norm(r);\n% \n% if (nargout > 2)\n% orth = [orth, norm(V'*V - eye(k))];\n% end\n% end\n% \n% H = H(1:order,1:order);\n% \nend\n\nfunction ind = sum_ind(ind1,ind2)\n ind = repmat(ind1(:),1,numel(ind2)) + repmat((ind2(:))',numel(ind1),1);\n ind = (ind(:))';\nend\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/utils/gsp_lanczos_op.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6348979728784334}} {"text": "function value = r8_tan ( x )\n\n%*****************************************************************************80\n%\n%% R8_TAN evaluates the tangent of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the tangent of X.\n%\n persistent nterms\n persistent pi2rec\n persistent sqeps\n persistent tancs\n persistent xmax\n persistent xsml\n\n pi2rec = 0.011619772367581343075535053490057;\n\n if ( isempty ( nterms ) )\n tancs = [ ...\n +0.22627932763129357846578636531752, ...\n +0.43017913146548961775583410748067E-01, ...\n +0.68544610682565088756929473623461E-03, ...\n +0.11045326947597098383578849369696E-04, ...\n +0.17817477903926312943238512588940E-06, ...\n +0.28744968582365265947529646832471E-08, ...\n +0.46374854195902995494137478234363E-10, ...\n +0.74817609041556138502341633308215E-12, ...\n +0.12070497002957544801644516947824E-13, ...\n +0.19473610812823019305513858584533E-15, ...\n +0.31417224874732446504614586026666E-17, ...\n +0.50686132555800153941904891733333E-19, ...\n +0.81773105159836540043979946666666E-21, ...\n +0.13192643412147384408951466666666E-22, ...\n +0.21283995497042377309866666666666E-24, ...\n +0.34337960192345945292800000000000E-26, ...\n +0.55398222121173811200000000000000E-28, ...\n +0.89375227794352810666666666666666E-30, ...\n +0.14419111371369130666666666666666E-31 ]';\n nterms = r8_inits ( tancs, 19, 0.1 * r8_mach ( 3 ) );\n xmax = 1.0 / r8_mach ( 4 );\n xsml = sqrt ( 3.0 * r8_mach ( 3 ) );\n sqeps = sqrt ( r8_mach ( 4 ) );\n end\n\n y = abs ( x );\n\n if ( xmax < y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_TAN - Warning!\\n' );\n fprintf ( 1, ' No precision because |X| is big.\\n' );\n value = 0.0;\n return\n end\n\n ainty = r8_aint ( y );\n yrem = y - ainty;\n prodbg = 0.625 * ainty;\n ainty = r8_aint ( prodbg );\n y = ( prodbg - ainty ) + 0.625 * yrem + pi2rec * y;\n ainty2 = r8_aint ( y );\n ainty = ainty + ainty2;\n y = y - ainty2;\n\n ifn = r8_aint ( mod ( ainty, 2.0 ) );\n\n if ( ifn == 1 )\n y = 1.0 - y;\n end\n\n if ( 1.0 - y < abs ( x ) * sqeps )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_TAN - Warning!\\n' );\n fprintf ( 1, ' Answer < half precision.\\n' );\n fprintf ( 1, ' |X| big or X near pi/2 or 3*pi/2.\\n' );\n end\n\n if ( y == 1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_TAN - Fatal error!\\n' );\n fprintf ( 1, ' X is pi/2 or 3*pi/2.\\n' );\n value = 0.0\n error ( 'R8_TAN - Fatal error!' )\n end\n\n if ( y <= 0.25 )\n\n value = y;\n if ( xsml < y )\n value = y * ( 1.5 + r8_csevl ( 32.0 * y * y - 1.0, tancs, nterms ) );\n end\n\n elseif ( y <= 0.5 )\n\n value = 0.5 * y * ( 1.5 + r8_csevl ( ...\n 8.0 * y * y - 1.0, tancs, nterms ) );\n value = 2.0 * value / ( 1.0 - value * value );\n\n else\n\n value = 0.25 * y * ( 1.5 + r8_csevl ( ...\n 2.0 * y * y - 1.0, tancs, nterms ) );\n value = 2.0 * value / ( 1.0 - value * value );\n value = 2.0 * value / ( 1.0 - value * value );\n\n end\n\n if ( x < 0.0 )\n value = - abs ( value );\n elseif ( 0.0 < x )\n value = + abs ( value );\n end\n\n if ( ifn == 1 )\n value = - value;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_tan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6348979545060032}} {"text": "function [bler, ber] = simulation(N, K, design_epsilon, max_runs, max_err, resolution, ebno_vec, list_size_vec, g, crc_length)\nR = (K - crc_length)/N;\nlambda_offset = 2.^(0 : log2(N));\nllr_layer_vec = get_llr_layer(N);\nbit_layer_vec = get_bit_layer(N);\n[G_crc, H_crc] = crc_generator_matrix(g, K - crc_length);\ncrc_parity_check = G_crc';\n \n%beta expansion Code Construction, proposed by Huawei\n% beta = sqrt(sqrt(2));\n% % channels = PW(N, beta);\n% % channels = HPW(N, beta);\n% channels = EPW(N, beta);\n% [~, channel_ordered] = sort(channels, 'descend');\n% info_bits = sort(channel_ordered(1 : K));\n% frozen_bits = ones(N , 1);\n% frozen_bits(info_bits) = 0;\n\n%Bhattacharyya Code (BEC) Construction\n% channels = get_BEC_IWi(N, design_epsilon);\n% [~, channel_ordered] = sort(channels, 'descend');\n% info_bits = sort(channel_ordered(1 : K), 'ascend');\n% frozen_bits = ones(N , 1);\n% frozen_bits(info_bits) = 0;\n% info_bits_logical = logical(mod(frozen_bits + 1, 2));\n\n%Gaussian approximation Code Construction\ndesign_snr = 2.5;\nsigma_cc = 1/sqrt(2 * R) * 10^(-design_snr/20);\n[channels, ~] = GA(sigma_cc, N);\n[~, channel_ordered] = sort(channels, 'descend');\ninfo_bits = sort(channel_ordered(1 : K), 'ascend');\nfrozen_bits = ones(N, 1);\nfrozen_bits(info_bits) = 0;\nfrozen_bits = logical(frozen_bits);\n\n%Following MATLAB code is used for matrix-multiplication based systematic polar encoding\nFN = get_GN(N);\nGAA = FN(info_bits, info_bits);\nGAAC = FN(info_bits, frozen_bits);\nGenerate_xAC = mod(GAAC' * GAA', 2);\nsystematic_encoding_algorithm = 1; \n\n%This value can be 1, 2, 3, and 4.\n%1 : 'Matrix_multiplication_systematic_encoder' \n%!!!!But when N is large,the Generator matrix will be large, too. The computer may not have such large storage.\n%2 : 'Sarkis_Two_step_systematic_encoder'\n%3 : 'Arikan_SC_style_systematic_encoder'\n%4 : 'Arikan_Recursive_systematic_encoder'. This one is slow.\n\n%Special constituent nodes\nnode_type_matrix = get_node_structure(frozen_bits);\npsi_vec = get_psi_for_advanced_sc_decoder(node_type_matrix);\n\n%Results Stored\nbler = zeros(length(ebno_vec), length(list_size_vec));\nnum_runs = zeros(length(ebno_vec), length(list_size_vec));\nber = zeros(length(ebno_vec), length(list_size_vec));\n%Loop starts\ntic\nfor i_run = 1 : max_runs\n if mod(i_run, max_runs/resolution) == 1\n disp(' ');\n disp(['Sim iteration running = ' num2str(i_run)]);\n disp(['N = ' num2str(N) ' K = ' num2str(K)]);\n disp(['List size = ' num2str(list_size_vec)]);\n disp('Current block error performance');\n disp(num2str([ebno_vec' bler./num_runs]));\n disp('Current bit error performance');\n disp(num2str([ebno_vec' ber./num_runs/K]));\n disp(' ')\n end\n info = rand(K - crc_length, 1) > 0.5;\n info_with_crc = [info; mod(crc_parity_check * info, 2)];\n switch systematic_encoding_algorithm\n case 1\n parity_check_bits = mod(Generate_xAC * info_with_crc, 2);\n x = zeros(N, 1);\n x(info_bits) = info_with_crc;\n x(frozen_bits) = parity_check_bits;\n case 2\n x = sarkis_systematic_polar_encoder(info_with_crc, info_bits, frozen_bits, N, lambda_offset, llr_layer_vec);\n case 3\n x = arikan_sc_systematic_polar_encoder(info_with_crc, frozen_bits, info_bits, lambda_offset, llr_layer_vec, bit_layer_vec);\n case 4\n x = zeros(N, 1);\n x(info_bits) = info_with_crc;\n x = arikan_recursive_systematic_polar_encoder(x, mod(frozen_bits + 1, 2));\n end\n bpsk = 1 - 2 * x;\n noise = randn(N, 1);\n prev_decoded = zeros(length(ebno_vec), length(list_size_vec));\n for i_ebno = 1 : length(ebno_vec)\n sigma = 1/sqrt(2 * R) * 10^(-ebno_vec(i_ebno)/20);\n y = bpsk + sigma * noise;\n llr = 2/sigma^2*y;\n %*******Simulaion Accelaration*********\n for i_list = 1 : length(list_size_vec)\n if i_list ~= 1\n if bler(i_ebno, i_list) == max_err\n continue;\n end\n else\n if all(bler(i_ebno, 2 : end) == max_err)\n continue\n end\n end\n num_runs(i_ebno, i_list) = num_runs(i_ebno, i_list) + 1;\n run_sim = 1;\n for i_ebno2 = 1 : i_ebno\n for i_list2 = 1 : i_list\n if prev_decoded(i_ebno2, i_list2)\n run_sim = 0;\n end\n end\n end\n if run_sim == 0\n continue;\n end\n %*******Simulaion Accelaration*********\n if list_size_vec(i_list) == 1\n polar_info_esti = SC_decoder(llr, frozen_bits, lambda_offset, llr_layer_vec, bit_layer_vec, info_bits);\n% polar_info_esti = FastSCdecoder(llr, info_bits, node_type_matrix, lambda_offset, llr_layer_vec, psi_vec, bit_layer_vec);\n else\n polar_info_esti = FastSCL_decoder(llr, list_size_vec(i_list), info_bits, lambda_offset, llr_layer_vec, bit_layer_vec, psi_vec, node_type_matrix, H_crc);\n end\n if any(polar_info_esti ~= info_with_crc)\n bler(i_ebno, i_list) = bler(i_ebno, i_list) + 1;\n ber(i_ebno, i_list) = ber(i_ebno, i_list) + sum(polar_info_esti(1 : K - crc_length) ~= info_with_crc(1 : K - crc_length));\n %Caution, this is data bits error rate, regardless of CRC\n %bits.\n else\n prev_decoded(i_ebno, i_list) = 1;\n end\n \n end\n end\nend\ntoc\nend\n\n", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarFastSCL/simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6348319480973021}} {"text": "\n% [covmatrix] = covfunc(theta)\n% [covmatrix, theta] = rand_theta(theta, covmatrix, Y, covfunc,\n% logposterior)\n% [rand_y] = get_randfunc_y(covmatrix)\n% Y = rand_y(covmatrix, Y, I)\n% [y, dy] = logprior_theta(theta)\n% [y, dy] = loglikelihood_theta(Y, covmatrix)\n\n% COVMATRIX:\n% L1/LD1\n% L2/LD2\n% linsolve1\n% linsolve2\n% K1\n% K2\n% logdet1\n% logdet2\n\nfunction res = test_gp_kron(N1,N2,N_samples,seed)\n\n%\n% DATA\n%\n\n%randn('state', 10)\n%rand('state', 10)\n\nif nargin == 0\n N1 = 200;\n N2 = 300;\nend\nif nargin < 3\n N_samples = 100;\nend\nif nargin >= 4\n randn('state', seed);\n rand('state', seed);\nelse\n randn('state', 10);\n rand('state', 10);\nend\n \n\n% Inputs\nx1 = 1:N1;\nx2 = 1:N2;\n\n% Covariance models\n\nd1 = sqrt(sq_dist(x1(1), x1));\ncovfunc1 = gp_cov_pp(d1,1);\ncovfunc1 = gp_cov_toeplitz(covfunc1);\ntheta1 = 10;\nK1 = covfunc1(theta1);\n\nd2 = sqrt(sq_dist(x2(1), x2));\ncovfunc2 = gp_cov_pp(d2,1);\ncovfunc2 = gp_cov_toeplitz(covfunc2);\ntheta2 = 10;\nK2 = covfunc2(theta2);\n\n% $$$ nz1 = nnz(K1)\n% $$$ nz2 = nnz(K2)\n% $$$ K = kron(K1,K2);\n% $$$ whos\n% $$$ t = cputime();\n% $$$ LD = ldlchol(K);\n% $$$ ldlsolve(LD,randn(N1*N2,1));\n% $$$ time = cputime() - t\n% $$$ return\n\n% $$$ % Plot gradients\n% $$$ [K1, dK1] = covfunc1(theta1);\n% $$$ figure\n% $$$ subplot(3,1,1)\n% $$$ imagesc(K1)\n% $$$ subplot(3,1,2)\n% $$$ imagesc(dK1{1})\n% $$$ subplot(3,1,3)\n% $$$ imagesc(dK1{2})\n% $$$ return\n\ndisp('Generate data..')\n\n% Generate noisy data\na = 1;\ns = 1;\nY = a * kronprod(lchol(K1), lchol(K2), randn(N2,N1));\n% $$$ Y = a * (lchol(K2) * randn(N2,N1) * lchol(K1)');\nsave('Y_noiseless', 'Y');\nY = Y + s*randn(N2,N1);\nsave('Y_noisy', 'Y');\n\n% Missing values\npmv = 0.5;\n%Imv = randperm(N2*N1);\n%Imv = Imv(1:floor(pmv*(N2*N1)));\nImv = rand(N2,N1) < pmv;\n%Imv = (rand(N2,N1) < 0.2);\nind1 = ceil(N1/2) + (1:(2*theta1));\nind2 = ceil(N2/2) + (1:(2*theta2));\nImv(ind2,ind1) = true;\nY(Imv) = nan;\n\n%\n% INFERENCE\n%\n\na = 1e-3;\nb = 1e-3;\nlogprior_theta = @(theta) sum(gamma_logpdf(theta, a, b));\ndlogprior_theta = @(theta) gamma_dlogpdf(theta, a, b);\n\n% Gibbs sampling for Y(missing) and covariance parameters\nburnin = floor(N_samples/2);\n\n% Initial guess for covariance parameters\ntheta_init = [2.0 ... % total magnitude\n 2.0*theta1 ... % 1) length scale\n 0.5*theta2 ... % 2) length scale\n 2.0]'; % noise magnitude\n\nres = gp_kron(Y, covfunc1, covfunc2, N_samples, theta_init, ...\n logprior_theta, dlogprior_theta, burnin)\n\nsave(sprintf('/home/jluttine/matlab/gp/results_test_gp_kron_%s', ...\n datestr(now,'yyyymmdd')), ...\n '-struct', 'res');\n\ncl = max(abs(Y(:))) + 0.1;\nclim = [-cl cl];\n\nY(Imv) = cl;\n\nfigure()\nclf\n\nsubplot(2,3,1)\nimagesc(Y,clim)\n\nload('Y_noiseless')\n\nsubplot(2,3,4)\nimagesc(Y,clim)\ntitle('true')\n\nsubplot(2,3,5)\nimagesc(res.F,clim)\ntitle('mean')\n\nsubplot(2,3,6)\nF_var = sqrt(res.FF - res.F.*res.F);\nclim_var = [0, max(F_var(:))];\nimagesc(F_var,clim_var)\ntitle('std')\n\nmap_colormap();\ncm = colormap();\ncm(end,:) = [0.5 0.5 0.5];\ncolormap(cm);\n\nrmse_F = rmse(Y,res.F)\n\nsubplot(2,3,2)\nsemilogy(res.theta');\n\nsubplot(2,3,3)\n%lag = 200;\nplot(acorr(res.theta(:,burnin:end)'));\n\nfigure()\nplot_scatterhist(res.theta(:,burnin:end)');\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gp/test_gp_kron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.634831943902434}} {"text": "function triangulation_test026 ( )\n\n%*****************************************************************************80\n%\n%% TEST026 tests DIAEDG.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n node_num = 4;\n triangle_num = 2;\n triangle_order = 3;\n seed = 123456789;\n test_num = 10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST026\\n' );\n fprintf ( 1, ' DIAEDG determines whether two triangles\\n' );\n fprintf ( 1, ' with a common edge need to \"swap\" diagonals.\\n' );\n fprintf ( 1, ' If swapping is indicated, then ALPHA_MIN should increase.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Swap ALPHA_MIN ALPHA_MIN\\n' );\n fprintf ( 1, ' Unswapped Swapped\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n%\n% Generate a random quadrilateral (1,2,3,4).\n%\n [ node_xy, seed ] = quad_convex_random ( seed );\n%\n% Does it need swapping?\n%\n value = diaedg ( ...\n node_xy(1,1), node_xy(2,1), ...\n node_xy(1,2), node_xy(2,2), ...\n node_xy(1,3), node_xy(2,3), ...\n node_xy(1,4), node_xy(2,4) );\n\n if ( value == 1 )\n swap = 0;\n else\n swap = 1;\n end\n%\n% Compute ALPHA_MIN unswapped.\n%\n triangle_node(1:3,1) = [ 1, 2, 3 ]';\n triangle_node(1:3,2) = [ 1, 3, 4 ]';\n\n [ alpha_min_unswapped, alpha_ave, alpha_area ] = alpha_measure ( ...\n node_num, node_xy, triangle_order, triangle_num, triangle_node );\n%\n% Compute ALPHA_MIN swapped.\n%\n triangle_node(1:3,1) = [ 1, 2, 4 ]';\n triangle_node(1:3,2) = [ 2, 3, 4 ]';\n\n [ alpha_min_swapped, alpha_ave, alpha_area ] = alpha_measure ( ...\n node_num, node_xy, triangle_order, triangle_num, triangle_node );\n\n if ( 0 )\n r8mat_transpose_print ( 2, node_num, node_xy, ' Quadrilateral' );\n end\n\n fprintf ( 1, ' %1d %10f %10f\\n', ...\n swap, alpha_min_unswapped, alpha_min_swapped );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangulation/triangulation_test026.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6347827492903383}} {"text": "function value = r8_round_i4 ( x )\n\n%*****************************************************************************80\n%\n%% R8_ROUND_I4 rounds an R8 to the nearest integral value, returning an I4.\n%\n% Discussion:\n%\n% In MATLAB, it is essentially true that there is little difference between\n% this function and R8_ROUND, because we store our integers in what amounts\n% to a real variable.\n%\n% Example:\n%\n% X R8_ROUND_I4\n%\n% 1.3 1\n% 1.4 1\n% 1.5 1 or 2\n% 1.6 2\n% 0.0 0\n% -0.7 -1\n% -1.1 -1\n% -1.6 -2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the value.\n%\n% Output, integer R8_ROUND_I4, the rounded value.\n%\n if ( x < 0.0 )\n value = - floor ( - x + 0.5 );\n else\n value = floor ( + x + 0.5 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_round_i4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6347827412665031}} {"text": " function ekin\n% ***************************************************************\n% P r o g r a m EKIN\n% ***************************************************************\n%\n% PURPOSE:\n% Derive differential equation of motion of a mechanical\n% system with one degree of freedom by means of the theo-\n% rem of Kinetic Energy dEk/dt = N(t,q,qt)\n% Resolve the equation numerically and plots the graphics\n% of the coordinate, velocity and phase plane.\n% If possible, the program could solve the problem analytically.\n%\n% INPUT DATA:\n% Ek - expression of the kinetic energy Ek = Ek(q,qt);\n% N - power of the forces and moments N = N(t,q,qt);\n% q0 - initial value of the coordinate;\n% qt0 - initial value of the velocity;\n% Tend - upper bound of the integration;\n% eps - precision of the calculations;\n% np - number of parameters .\n% P{1}, P{2}, ..., P{np} - names of the parameters (array of cells);\n%\n% NOTES:\n% 1. The coordinate is designed by the symbol 'q' and velocity by 'qt';\n% 2. The physical names of the parameters are assigned to the\n% cells of the array P like this: P{1}='m', P{2}='c',...;\n% 3. For analytical solution the values of Tend, eps, np and P are not\n% needed.\n% 4. Initial values q0, qt0 must to be entered as strings, even though\n% they represent numbers!\n% 5. All the data can be input from file or in interactive mode.\n% \n% EXAMPLE of DATA FILE:\n% % Data for problem ...\n% Ek = '1/2*a*qt^2';\n% N = '-(k*qt + 9.81*sin(q))*qt';\n% q0 = 'q0'; ( or q0 = '0.12';)\n% qt0 = 'qt0'; ( or qt0 = '7.5';)\n% Tend = 20;\n% eps = 1.e-8;\n% np = 2;\n% P{1} = 'a';\n% P{2} = 'k';\n\n% ---------------------------------------------------------\n% DATA INPUT OF THE PROBLEM\n% =========================================================\n\n clear\n disp(' ');\n disp(' How will you input the data ? ');\n disp(' 1. From a data file; ');\n disp(' 2. In interactive mode. ');\n ans = input(' Number of Your choice : ' );\n flag = 0;\n if ans == 1\n while 1\n disp(' ');\n indat = input(' Input the name of the data file :', 's');\n if exist([cd,'\\',indat]) % Search only in current directory\n eval(indat);\n flag = 1; break % Successful\n else % Unsuccessful\n disp(' ');\n disp([' File ',indat,' not exist!'])\n disp(' You have to:')\n disp(' 1. Enter another DATA file name, or')\n disp(' 2. Input the DATA interactively !')\n ans2 = input(' Your choice, please: ');\n if ans2 == 2, break , end\n end\n end\n end\nif flag == 0 \n %Input of the data in-line mode\n Ek = input(' Expression of the kinetic energy Ek : ','s');\n N = input(' Power of the forces and moments N : ','s' );\n q0 = input(' Initial value of the coordinate q0 : ' );\n qt0 = input(' Initial value of the velocity qt0 : ' );\n Tend = input(' Upper bound of the integration Tend : ' );\n eps = input(' Precision of the calculations eps : ' );\n np = input(' Number of parameters np : ' );\n % Asigning names of the parameters\n if np > 0\n disp(' ');\n disp(' Enter names of the parameters:')\n for i = 1:np\n ii = num2str(i);\n P{i} = input([' Name of parameter P',ii,': '],'s');\n end\n end \n end\n \n% ---------------------------------------------------------\n% Differential Equation of Motion\n% =========================================================\n\n syms q qt qtt Dq D2q\n dEkdt = diff(Ek,q)*qt + diff(Ek,qt)*qtt;\n deq = (dEkdt - N)/qt;\n deq = subs(deq,{qt,qtt},{Dq,D2q});\n deq = simplify(deq)\n\n% ---------------------------------------------------------\n% ANALYTICAL SOLUTION\n% =========================================================\n\n disp(' ');\n ans = input(' Would you like analytical solution? (Y/N): ','s');\n if ans =='Y' | ans == 'y'\n if ~isstr(q0) , q0 = num2str(q0) ; end % Repairing user\n if ~isstr(qt0), qt0 = num2str(qt0); end % input errors! \n inicond = ['q(0)=',q0,',Dq(0)=',qt0];\n q = dsolve(char(deq), inicond, 't');\n if ~isempty(q)\n disp(' ');\n disp(' Low of Motion ');\n disp(' ***************** ');\n disp(' '); \n disp('q = '); pretty(q)\n disp(' ');\n fname = input(' Name of file to write solution: ','s');\n save(fname, 'q');\n end\n disp(' ');\n ans = input(' Would you like numerical solution? (Y/N): ','s');\n if ans == 'N' | ans == 'n', return, end \n q = 'q'; % Clear analitical solution from q ! \n end\n\n% ---------------------------------------------------------\n% NUMERICAL SOLUTION\n% ========================================================= \n\n% Input the name of the file-function\ndisp(' ');\nfname = input(' Name of the File-function to be generated: ','s');\nflag1 = 'Y';\nif exist([cd,'\\',fname]) % Search only in curent directory!\n disp(' ');\n disp([' A file-function with name ',fname,' already exist !'])\n flag1 = input(' Overwrite it ? (Y/N): ', 's');\nend\n\n% ---------------------------------------------------------\n% GENERATING THE FILE-FUNCTION\n% ---------------------------------------------------------\n\nif ( flag1 == 'Y' | flag1 == 'y' )\n qtt = solve(deq,'D2q');\n qtt = subs(qtt,{q,Dq},{'y(1)','y(2)'});\n% Opening the file to write file-function\n [Fid,mes] = fopen([fname,'.m'],'wt');\n% Generating the string with physical parameters: m, c ...\n strpar = '';\n for j = 1:np\n strpar = [strpar,',',P{j}];\n end\n disp(' ');\n titl = input(' Denomination of the Problem: ','s');\n% Writing the headline of the File-function\n fprintf(Fid,['function yt = ',fname,'(t,y',strpar,')\\n']);\n fprintf(Fid,['%% ',titl]);\n% Writing the first derivatives\n fprintf(Fid,'\\n%% The first derivatives\\n');\n fprintf(Fid, ' yt(1) = y(2); \\n');\n fprintf(Fid,[' yt(2) = ',char(qtt),'; \\n']);\n fprintf(Fid,' yt = yt''; \\n');\n fprintf(Fid,['%% *** End of File-function ',fname,' ***']);\n fclose(Fid);\n edit(fname)\nend\n\n% ---------------------------------------------------------\n% INTEGRATION AND VISUALIZATION OF THE REZULTS\n% ---------------------------------------------------------\n\nflag2 = 0;\n% Initial entering values of the parameters and generating\n% the string with parameters 'P{1}, P{2}, ..., P{np}' to be\n% passed to the File-function as actual arguments \nif np > 0\n PP = P; % Saving the physical names of the parameters in PP \n parameters = ' ';\n disp(' ');\n disp(' Input the numerical values of the parameters: ')\n for i = 1:np\n i = num2str(i);\n eval(['P{',i,'}=input(['' '',P{',i,'},'' = '']);']);\n parameters = [parameters,',P{',i,'}'];\n end \n else\n parameters = [];\nend\n% Check-up type of q0 and qt0 and correct\n% it if needed\nif ischar(q0)\n q0 = str2num(q0);\n if isempty(q0), q0 = input(' q0 = '); end\nend\nif ischar(qt0)\n qt0 = str2num(qt0);\n if isempty(qt0), qt0 = input(' qt0 = '); end\nend\nwhile 1\n if flag2 == 1\n disp(' ');\n eps = input(' Precision of the computations eps: ');\n Tend = input(' Upper bound of the integration Tend: ');\n q0 = input(' Initial coordinate q0: ');\n qt0 = input(' Initial velocity qt0: ');\n if np > 0\n P = PP; % Restoring the names of the parameters !\n disp(' ');\n disp(' Input the numerical values of the parameters: ')\n for i = 1:np\n i = num2str(i);\n eval(['P{',i,'}=input(['' '',P{',i,'},'' = '']);']);\n end \n end\n end\n y0 = [q0 qt0]; % initial conditions\n options = odeset('AbsTol',eps,'RelTol',100*eps);\n % Choosing of the Solver\n disp(' ');\n disp(' Choose the proper Solver: ');\n disp(' ------------------------------- ');\n disp(' A. Non stiff differential equations ');\n disp(' 1. ode45 - middle precision; ');\n disp(' 2. ode23 - low precision; ');\n disp(' 3. ode113 - from low to upper. ');\n disp(' ');\n disp(' B. Stiff differential equations ');\n disp(' 1. ode15s - from low to upper; ');\n disp(' 2. ode23s - low precision; ');\n disp(' 3. ode23t - middle precision; ');\n disp(' 4. ode23tb - low precision. ');\n disp(' ');\n solver = input(' The name of the Solver: ','s');\n \n % Integration of the Differential Equations\n \n eval(['[t,y] = feval(solver,eval([''@'',fname]),',...\n '[0 Tend],y0,options',parameters,');']);\n % Plotting graphs\n tmin = min(t); \n tmax = max(t);\n y1min = min(y(:,1)); \n y1max = max(y(:,1));\n y2min = min(y(:,2)); \n y2max = max(y(:,2));\n dy1 = y1max - y1min;\n dy2 = y2max - y2min;\n xmin = y1min - 0.1*dy1;\n xmax = y1max + 0.1*dy1;\n ymin = y2min - 0.1*dy2;\n ymax = y2max + 0.1*dy2;\n % Coordinate q = q(t)\n figure % 1\n comet(t,y(:,1))\n plot(t,y(:,1),[tmin tmax],[0 0],'k'), grid on\n axis([tmin, tmax, xmin, xmax]);\n set(gca,'FontName','Arial Cyr','FontSize',12);\n title('Low of motion {\\itq} = {\\itq}({\\itt})')\n xlabel('{\\itt}'); ylabel('{\\itq}'); pause\n % Velocity qt = qt(t)\n figure % 2\n comet(t,y(:,2))\n plot(t,y(:,2),[tmin tmax],[0 0],'k'), grid on\n axis([tmin, tmax, ymin, ymax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Velocity {\\it qt} = {\\it qt}({\\itt})')\n xlabel('{\\itt}'); ylabel('{\\it qt}'); pause\n % Coordinate and Velocity\n figure % 3\n subplot(2,1,1), plot(t,y(:,1),[tmin tmax],[0 0],'k')\n grid on, axis([tmin, tmax, xmin, xmax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Low of motion {\\itq} = {\\itq}({\\itt})')\n subplot(2,1,2), plot(t,y(:,2),[tmin tmax],[0 0],'k')\n grid on, axis([tmin, tmax, ymin, ymax]);\n set(gca,'FontName','Arial','FontSize',12);\n title('Velocity {\\it qt} = {\\it qt}({\\itt})')\n pause\n % Phase Plane\n figure % 4\n subplot(1,1,1)\n comet(y(:,1),y(:,2))\n plot(y(:,1),y(:,2), [xmin,xmax],[0 0],'k',...\n [0 0],[ymin,ymax],'k'), grid on\n axis([xmin, xmax, ymin, ymax]); \n set(gca,'FontName','Arial Cyr','FontSize',12);\n title(' Phase Plane {\\it qt} = {\\it qt}({\\itq})')\n xlabel('{\\itq}'), ylabel('{\\it qt}'), pause\n flag2 = 1;\n close all\n disp(' ');\n ans = input(' Would you like to continue? (Y/N): ','s');\n if ans == 'n' | ans == 'N', break, end\nend\n\n% **************** End of Program EKIN ******************\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/SORCE Files/EKIN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6347436842660874}} {"text": "function [sigma2,Sigma,didOverflow]=spherHarmonicCov(CStdDev,SStdDev,point,a,c,scalFactor)\n%%SPHERHARMONICCOV Evaluate the variance of a potential or the covariance\n% matrix of a gradient that one might compute using a\n% spherical harmonic coefficient model with\n% spherHarmonicEval. Here, one provides the standard\n% deviations associated with the coefficients in the\n% model, such as those obtained using the function\n% getEGMGravCoeffs for the EGM2008 gravity model.\n%\n%INPUTS: CStdDev A length (M+2)*(M+1)/2 array holding the standard\n% deviations of the coefficient terms that are multiplied by\n% cosines in the harmonic expansion. The coefficients must be\n% fully normalized using the type of full normalization that\n% is used in the EGM2008 model. Their normalization type can\n% be changed using the changeSpherHarmonicNorm function. If\n% given to a CountingClusterSet class, C(n+1,m+1) is the\n% coefficient of degree n and order m. When a maximum degree\n% of M is used, all C must have values for all n from 0 to M\n% and for all m from 0 to n for each n. If coefficients are\n% not present for certain degrees, then insert a 0. It is\n% assumed that M>=3. For magnetic field models, the units of\n% C should generally be Tesla. For gravitational models, C is\n% generally unitless with the units being determined entirely\n% by the parameters a and c.\n% SStdDev A length (M+2)*(M+1)/2 array holding the standard\n% deviations of the coefficient terms that are multiplied by\n% sines in the harmonic expansion. The requirements on\n% SStdDev are the same as those on CStdDev.\n% point The 3XN set of N points at which the potential and/or\n% gradient should be evaluated given in SPHERICAL, ECEF \n% coordinates consisting of [r;azimuth;elevation]; When\n% evaluating points on a grid, the algorithm will be fastest\n% if the points are provided presorted by range and then by\n% azimuth. This reduces the amount of recomputation of\n% certain values. Alternatively, if C and S are for\n% evaluating terrain heights, then points are 2XN having the\n% format [azimuth;elevation] and it is best if the points are\n% sorted by azimuth.\n% a The numerator in the (a/r)^n term in the spherical harmonic\n% sum. Normally, this is some type of a reference radius. For\n% example, when using most gravitational models, a is the\n% semi-major axis of the reference ellipsoid. If this\n% parameter is omitted, it is assumed that one is using the\n% spherical harmonics with something like the National\n% Geospatial Intelligence Agency's (NGA's) EGM96 or EGM2008\n% models, in which case a=Constants.EGM2008SemiMajorAxis is\n% used unless point is 2D, in which case c=1 is used.\n% c The constant value by which the spherical harmonic series\n% is multiplied. For example, for gravitational potentials,\n% the value is usually GM where G is the universal\n% gravitational constant and M is the mass of the Earth. When\n% using the International Geomagnetic Reference Field (IGRF),\n% the constant is a^2, where a is the same as the numerator\n% in the a/r term. If this parameter is omitted, it is\n% assumed that one is using the spherical harmonics with\n% something like the NGA's EGM96 or EGM2008 models, in which\n% case c=Constants.EGM2008GM is used unless point is 2D, in\n% which case c=1 is used.\n% scalFactor An optional scale factor used in computing the normalized\n% associated Legendre polynomials if fullyNormalized=true.\n% Generally, the default value (is if the scalFactor\n% parameter is omitted) of 2^(-470) is sufficient. When very\n% high-order models are used, this scale factor prevents\n% overflows. However overflows (and a loss of precision) are\n% unavoidable when using the full EGM2008 model. These\n% effects are worse near the poles.\n%\n%OUTPUTS: sigma2 The NX1 vector of variances (squared standard deviations)\n% of the potential estimate at the given points.\n% Sigma The covariance matrix of the gradient of the potential at\n% the given points.\n% didOverFlow This indicates whether during the computation of sigma2 or\n% Sigma there were any overflow errors leading to term\n% being dropped. Note that this does not indicate potential\n% losses of precision due to underflow errors making terms\n% zero, which becomes more common the smaller scalFactor is.\n% Also, if scaling is extremely bad, it is possible for\n% NaNs or Inf terms to still be returned in sigma2 and\n% Sigma.\n%\n%The algorithm used here is described in [1].\n%\n%Since Matlab uses double precision arithmetic, when using high degree and\n%order models, such as the full 2190 degree EGM2008 model, the precision of\n%Sigma will be reduced as higher-order terms can experience overflow\n%problems and are thus discarded to avoid NaNs from occurring. Lower-order\n%models will not suffer from the same problem.\n%\n%EXAMPLE:\n%Here, we evaluate the function at a point on the reference ellipsoid and\n%then at a point at the pole using the full degree 2190 EGM2008 model. Note\n%that the Matlab implementation will bee too slow for this high a degree\n%and the C++ implementation should be compiled.\n% latLongAlt=[-30*(pi/180);45*(pi/180);0];\n% spherLoc=Cart2Sphere(ellips2Cart(latLongAlt));\n% \n% [C,S,a,c,CStdDev,SStdDev]=getEGMGravCoeffs(2190,false);\n% [sigma21,Sigma1,didOverflow1]=spherHarmonicCov(CStdDev,SStdDev,spherLoc,a,c)\n% spherLoc(end)=pi/2;%90 degree elevation --the pole.\n% [sigma22,Sigma2,didOverflow2]=spherHarmonicCov(CStdDev,SStdDev,spherLoc,a,c)\n%One will see that in both instances, finite values are returned, but for\n%the point at the pole, overflows are flagged indicating the loss of\n%prevision due to some terms being dropped due to overflows. A model with\n%fewer spherical harmonic coefficients would not be as susceptible to such\n%overflow problems.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"An Overview of Major Terrestrial, Celestial, and\n% Temporal Coordinate Systems for Target Tracking,\" Formal Report, Naval\n% Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173\n% pages.\n%\n%April 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(scalFactor))\n scalFactor=2^(-470);\nend\n\nif(nargin<5||isempty(c))\n if(size(point,1)==2)\n c=1;\n else\n c=Constants.EGM2008GM;\n end\nend\n\nif(nargin<4||isempty(a))\n if(size(point,1)==2)\n a=1;\n else\n a=Constants.EGM2008SemiMajorAxis;\n end\nend\n\nM=(1/2)*(sqrt(1+8*length(CStdDev))-1)-1;\n\nif(M<3)\n error('The coefficients must be provided to at least degree 3. To use a lower degree, one can insert zero coefficients.');\nend\n\nnumPoints=size(point,2);\n%If we are evaluating terrain heights.\nswitch(size(point,1))\n case 2\n point=[ones(1,numPoints);point(1,:);point(2,:)];\n case 3\n otherwise\n error('Invalid point length');\nend\n\nCStdDev=CountingClusterSet(CStdDev);\nSStdDev=CountingClusterSet(SStdDev);\n\nsigma2=zeros(numPoints,1);\nSigma=zeros(3,3,numPoints);\n\ndidOverflow=false;\nrPrev=Inf;\nthetaPrev=Inf;\nfor curPoint=1:numPoints\n r=point(1,curPoint);\n thetaCur=point(3,curPoint);\n \n rChanged=r~=rPrev;\n rPrev=r;\n\n if(rChanged)\n nCoeff=zeros(M+1,1);\n nCoeff(1)=1;\n for n=1:M\n nCoeff(n+1)=nCoeff(n)*(a/r);\n end\n end\n\n %The non-singular algorithm of Pines using the fully normalized\n %Helmholtz equations from Fantino and Casotto is used. The algorithm\n %has been slightly modified so that the c/r term is out front and the\n %fully normalized Helmholtz polynomials can be scaled. Also, lumped\n %coefficients are not used. The Pines algorithm can suffer a loss of\n %precision near the equator. However, it is simple to just square the\n %terms in the sum.\n CartPoint=spher2Cart(point(:,curPoint));\n\n x=CartPoint(1);\n y=CartPoint(2);\n z=CartPoint(3);\n\n %Get the direction cosines used by Pines' algorithm.\n s=x/r;\n t=y/r;\n u=z/r;\n\n %Compute the fully normalized Helmholtz polynomials.\n if(thetaPrev~=thetaCur)\n [HBar,dHBardu]=normHelmholtz(u,M,scalFactor);\n thetaPrev=thetaCur;\n end\n\n %Recursively compute the rm and im terms for the sums.\n rm=zeros(M+1,1);\n im=zeros(M+1,1);\n rm(0+1)=1;\n im(0+1)=0;\n for m=1:M\n %These are equation 49 in the Fantino and Casotto paper.\n rm(m+1)=s*rm(m-1+1)-t*im(m-1+1);\n im(m+1)=s*im(m-1+1)+t*rm(m-1+1);\n end\n\n %Perform the sum for the potential from Equation 44 in the Fantino and\n %Casotto paper, but square all of the terms to represent a sigma.\n %All cross terms are expected to be zero, so the sum is very similar to\n %the sum for the potential in spherHarmonicEval.\n sigma2(curPoint)=0;\n for n=0:M\n innerTerm=0;\n for m=0:n\n innerTerm=innerTerm+(CStdDev(n+1,m+1)*rm(m+1)*HBar(n+1,m+1))^2+(SStdDev(n+1,m+1)*im(m+1)*HBar(n+1,m+1))^2;\n end\n if(isfinite(innerTerm))\n sigma2(curPoint)=sigma2(curPoint)+nCoeff(n+1)^2*innerTerm;\n else\n didOverflow=true;\n end\n end\n\n sigma2(curPoint)=(c/r)^2*sigma2(curPoint)/scalFactor^2;\n\n %Now, compute the cosigma matrix of the gradient, if requested.\n if(nargout>1)\n a11=0;\n a22=0;\n a33=0;\n a44=0;\n a12=0;\n a13=0;\n a14=0;\n a23=0;\n a24=0;\n a34=0;\n \n %The equations in these loops are from Table 10.\n for n=0:M\n a11Loop=0;\n a22Loop=0;\n a12Loop=0;\n a13Loop=0;\n a14Loop=0;\n a23Loop=0;\n a24Loop=0;\n\n %The m=0 case only applies to a3 and a4, so that means only to\n %a33, a34, and a44.\n m=0;\n HVal=HBar(n+1,m+1);\n dHVal=dHBardu(n+1,m+1);\n CProdMN=CStdDev(n+1,m+1)^2*rm(m+1)^2+SStdDev(n+1,m+1)^2*im(m+1)^2;\n Lmn=(n+m+1)*HVal+u*dHVal;%Defined in Table 14.\n \n a33Loop=CProdMN*dHVal^2; \n a44Loop=CProdMN*Lmn^2;\n a34Loop=-CProdMN*Lmn*dHVal;\n\n for m=1:n\n HVal=HBar(n+1,m+1);\n dHVal=dHBardu(n+1,m+1);\n \n CProdMN=CStdDev(n+1,m+1)^2*rm(m+1)^2+SStdDev(n+1,m+1)^2*im(m+1)^2;\n Lmn=(n+m+1)*HVal+u*dHVal;\n \n %These if-statements are to deal with numerical precision\n %problems near the poles. We want to avoid 0*Inf terms due\n %to limitations in the valid range of double precision\n %numbers. Of course, the loss of the terms where overflow\n %occurs means that the covariance matrix will be\n %underestimated.\n if(isfinite(HVal))\n a11Loop=a11Loop+m^2*(CStdDev(n+1,m+1)^2*rm(m-1+1)^2+SStdDev(n+1,m+1)^2*im(m-1+1)^2)*HVal^2;\n a12Loop=a12Loop+m^2*rm(m-1+1)*im(m-1+1)*(SStdDev(n+1,m+1)^2-CStdDev(n+1,m+1)^2)*HVal^2;\n a22Loop=a22Loop+m^2*(SStdDev(n+1,m+1)^2*rm(m-1+1)^2+CStdDev(n+1,m+1)^2*im(m-1+1)^2)*HVal^2;\n else\n didOverflow=true;\n end\n \n if(isfinite(Lmn))\n a44Loop=a44Loop+CProdMN*Lmn^2;\n if(isfinite(HVal))\n a14Loop=a14Loop-m*(CStdDev(n+1,m+1)^2*rm(m-1+1)*rm(m+1)+SStdDev(n+1,m+1)^2*im(m-1+1)*im(m+1))*HVal*Lmn;\n a24Loop=a24Loop-m*(-CStdDev(n+1,m+1)^2*im(m-1+1)*rm(m+1)+SStdDev(n+1,m+1)^2*rm(m-1+1)*im(m+1))*HVal*Lmn;\n end\n if(isfinite(dHVal))\n a34Loop=a34Loop-CProdMN*Lmn*dHVal;\n end\n else\n didOverflow=true;\n end\n \n if(isfinite(dHVal))\n a33Loop=a33Loop+CProdMN*dHVal^2;\n if(isfinite(HVal))\n a13Loop=a13Loop+m*(CStdDev(n+1,m+1)^2*rm(m-1+1)*rm(m+1)+SStdDev(n+1,m+1)^2*im(m-1+1)*im(m+1))*HVal*dHVal;\n a23Loop=a23Loop+m*(-CStdDev(n+1,m+1)^2*im(m-1+1)*rm(m+1)+SStdDev(n+1,m+1)^2*rm(m-1+1)*im(m+1))*HVal*dHVal;\n end\n else\n didOverflow=true;\n end\n end\n \n a11=a11+nCoeff(n+1)^2*a11Loop;\n a22=a22+nCoeff(n+1)^2*a22Loop;\n a33=a33+nCoeff(n+1)^2*a33Loop;\n a44=a44+nCoeff(n+1)^2*a44Loop;\n a12=a12+nCoeff(n+1)^2*a12Loop;\n a13=a13+nCoeff(n+1)^2*a13Loop;\n a14=a14+nCoeff(n+1)^2*a14Loop;\n a23=a23+nCoeff(n+1)^2*a23Loop;\n a24=a24+nCoeff(n+1)^2*a24Loop;\n a34=a34+nCoeff(n+1)^2*a34Loop;\n end\n\n%These are based on squaring the terms in equation 70, removing cross\n%terms. However, an additional 1/r (squared) term has been added,\n%which the original paper omitted when going from Equation 68 to 70.\n \n s11=a11+2*s*a14+s^2*a44;\n s12=a12+s*a24+t*a14+s*t*a44;\n s13=a13+s*a34+u*a14+s*u*a44;\n s22=a22+2*t*a24+t^2*a44;\n s23=a23+t*a34+u*a24+t*u*a44;\n s33=a33+2*u*a34+u^2*a44;\n \n temp=c/(r^2*scalFactor);\n\n Sigma(:,:,curPoint)=temp*(temp*[s11,s12,s13;\n s12,s22,s23;\n s13,s23,s33]);\n end\n\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Spherical_Harmonics/spherHarmonicCov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6347274437303724}} {"text": "f = [110*1.3 30*2.0 125*1.56 75*1.8 95*.95 100*2.25 50*1.35];\nA = [120 210 150.75 115 186 140 85;\n 110 30 125 75 95 100 50;\n 1 1 1 1 1 1 1;\n 1 -1 0 0 0 0 0;\n 0 0 1 0 -2 0 0;\n 0 0 0 -1 0 -1 1];\nb = [55000;40000;400;0;0;0];\nlp = lp_maker(f, A, b, [-1; -1; -1; -1; -1; -1], [10 10 10 10 20 20 20], [100 Inf 50 Inf Inf 250 Inf], [], 1, 0);\nsolvestat = mxlpsolve('solve', lp)\nformat bank\nobj = mxlpsolve('get_objective', lp)\nformat short\nx = mxlpsolve('get_variables', lp)\nmxlpsolve('delete_lp', lp);", "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/lp_solve/distribution/example6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6346609893503775}} {"text": "function out=janaf(prop, spec,T);\n% ---------------------------------------------------------------------\n% function out=janaf(prop, spec, T) | Version 1.01\n% ---------------------------------------------------------------------\n% Calculates JANAF curve fit according to JANAF virial equation\n% Output is calculated in SI-units\n%\n% prop = 'c' for standard state specific heat\n% = 'h' for standard state enthalpy\n% = 's' for standard state entropy\n% spec = 'CO2', 'H2O', 'CO', 'H2', 'O2', 'N2'\n% T = Temperature, vector allowed\n% \n% JANAF.mat required (contains the coefficients)\n% ---------------------------------------------------------------------\n% Last Change: 2003-07-18 | (c)2003, Stefan Billig, Delphi\n\n% check for correct syntax\nif nargin~=3\n help janaf\n % end function\n return\nend\n\n% load coefficient table\nload JANAF;\nz=1;\n% determine molecular weight from table\nMWeight=eval(['MolWeight.' spec]);\n\nfor i=1:length(T)\n % choose temperature range vector\n if (T(i)>1000 & T(i)<=5000)\n eval(['ai=' spec '(1,:);'])\n out(z)=calc(ai, T(i), prop, MWeight);\n z=z+1;\n elseif (T(i)>=300 & T(i)<=1000)\n eval(['ai=' spec '(2,:);'])\n out(z)=calc(ai, T(i), prop, MWeight);\n z=z+1;\n else \n sprintf(['Temperature ' num2str(T(i)) 'K not between 300K and 5000K!'])\n end\nend\n \n\n%----------------------------------------------------------------------\nfunction out=calc(ai, T, prop, MWeight)\n\nR=8.314;\n% calculate standard state value\nswitch prop\n case 'c'\n out=(ai(1)+ai(2)*T+ai(3)*T.^2+ai(4)*T.^3+ai(5)*T.^4)*R/MWeight;\n case 'h'\n out=(ai(1)+ai(2)/2*T+ai(3)/3*T.^2+ai(4)/4*T.^3+ai(5)/5*T.^4+ai(6)/T).*T*R/MWeight;\n case 's'\n out=(ai(1)*ln(T)+ai(2)*T+ai(3)/2*T.^2+ai(4)/3*T.^3+ai(5)/4*T.^4+ai(7))*R/MWeight;\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/4212-janaf-m/janaf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6346609732275551}} {"text": "function jed = ymdf_to_jed_gregorian ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_GREGORIAN converts a Gregorian YMDF date to a JED.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 December 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm E,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 323-324.\n%\n% Parameters:\n%\n% Input, integer Y, integer M, integer D, real F, the YMDF date.\n%\n% Output, real JED, the corresponding JED.\n%\n\n%\n% Check the date.\n%\n [ y, m, d, ierror ] = ymd_check_gregorian ( y, m, d );\n\n if ( ierror ~= 0 )\n jed = -1.0;\n return\n end\n%\n% Account for the missing year 0 by moving negative years up one.\n%\n y2 = y_common_to_astronomical ( y );\n%\n% Convert the calendar date to a computational date.\n%\n% This frap-dapping formula fails for 1 March 1900!\n%\n if ( m == 3 && d == 1 && ~year_is_leap_gregorian ( y2 ) )\n m = m - 1;\n d = 29;\n end\n\n y_prime = y2 + 4716 - floor ( ( 14 - m ) / 12 );\n m_prime = mod ( m + 9, 12 );\n d_prime = d - 1;\n%\n% Convert the computational date to a JED.\n%\n j1 = floor ( ( 1461 * y_prime ) / 4 );\n\n j2 = floor ( ( 153 * m_prime + 2 ) / 5 );\n\n g = floor ( 3 * floor ( ( y_prime + 184 ) / 100 ) / 4 ) - 38;\n\n jed = j1 + j2 + d_prime - 1401 - g - 0.5;\n jed = jed + f;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calendar_nyt/ymdf_to_jed_gregorian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6346197445552868}} {"text": "function [v, signs] = lnDiffErfs(x1, x2),\n\n% LNDIFFERFS Helper function for computing the log of difference\n% of two erfs.\n% FORMAT\n% DESC computes the log of the difference of two erfs in a numerically stable manner.\n% ARG x1 : argument of the positive erf\n% ARG x2 : argument of the negative erf\n% RETURN v : log(abs(erf(x1) - erf(x2)))\n% RETURN s : sign(erf(x1) - erf(x2))\n%\n% FORMAT\n% DESC computes the log of the difference of two erfs in a numerically stable manner.\n% ARG x1 : argument of the positive erf\n% ARG x2 : argument of the negative erf\n% RETURN v : log(erf(x1) - erf(x2)) (Can be complex)\n%\n% COPYRIGHT : Antti Honkela, 2007, 2008\n%\n% MODIFICATIONS : David Luengo, 2009\n%\n% SEEALSO : gradLnDiffErfs\n\n% NDLUTIL\n\nx1 = real(x1);\nx2 = real(x2);\n\nv = zeros(max(size(x1), size(x2)));\n\nif numel(x1) == 1,\n x1 = x1 * ones(size(x2));\nend\n\nif numel(x2) == 1,\n x2 = x2 * ones(size(x1));\nend\n\nsigns = sign(x1 - x2);\nI = signs == -1;\nswap = x1(I);\nx1(I) = x2(I);\nx2(I) = swap;\n\n% Case 1: arguments of different signs, no problems with loss of accuracy\nI1 = (x1.*x2)<0;\n% Case 2: x1 = x2\nI2 = x1 == x2;\n% Case 3: Both arguments are non-negative\nI3 = (x1 > 0) & ~I1 & ~I2;\n% Case 4: Both arguments are non-positive\nI4 = ~I1 & ~I2 & ~I3;\n\nwarnState = warning('query', 'MATLAB:log:logOfZero');\nwarning('off', 'MATLAB:log:logOfZero');\nv(I1) = log( erf(x1(I1)) - erf(x2(I1)) );\nv(I2) = -inf;\nv(I3) = log(erfcx( x2(I3)) ...\n\t - erfcx(x1(I3)) .* exp(x2(I3).^2 - x1(I3).^2)) ...\n\t- x2(I3).^2;\nv(I4) = log(erfcx( -x1(I4)) ...\n\t - erfcx(-x2(I4)) .* exp(x1(I4).^2 - x2(I4).^2)) ...\n\t- x1(I4).^2;\nwarning(warnState.state, 'MATLAB:log:logOfZero');\n\nif nargout < 2,\n v(I) = v(I) + pi*1i;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/lnDiffErfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6346197374357722}} {"text": "function r = uniform_dataset ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% UNIFORM_DATASET generates a uniform dataset and writes it to a file.\n%\n% Discussion:\n%\n% UNIFORM_DATASET generates a uniform random data and writes it to a file.\n%\n% Usage:\n%\n% r = uniform_dataset ( m, n, seed )\n%\n% where\n%\n% * M, the spatial dimension,\n% * N, the number of points to generate,\n% * SEED, the seed, a positive integer.\n% * R is the M by N array created.\n%\n% creates an M by N uniform random dataset and writes it to the\n% file \"uniform_M_N.txt\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UNIFORM_DATASET\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Generate a uniform pseudorandom dataset.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program requests input values from the user:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * M, the spatial dimension,\\n' );\n fprintf ( 1, ' * N, the number of points to generate,\\n' );\n fprintf ( 1, ' * SEED, a seed for the random number generator.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program generates the data and writes it to the file\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' uniform_M_N.txt\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' where \"M\" and \"N\" are the numeric values.\\n' );\n%\n% Get the spatial dimension.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n m = input ( ' Enter the spatial dimension M: ' );\n else\n m = str2num ( m );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension M = %d\\n', m );\n%\n% Get the number of points.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n n = input ( ' Enter the number of points N: ' );\n else\n n = str2num ( n );\n end\n\n fprintf ( 1, ' Number of points N = %d\\n', n );\n%\n% Get the seed.\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n seed = input ( ' Enter the seed: ' );\n else\n seed = str2num ( seed );\n end\n\n fprintf ( 1, ' The seed = %d\\n', seed );\n%\n% Compute the data.\n%\n [ r, seed ] = r8mat_uniform_01 ( m, n, seed );\n%\n% Write it to a file.\n%\n output_filename = ...\n strcat ( 'uniform_', num2str ( m ), '_', num2str ( n ), '.txt' );\n\n r8mat_write ( output_filename, m, n, r );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data was written to the file \"%s\".\\n', ...\n output_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UNIFORM_DATASET:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n return;\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction [ r, seed ] = r8mat_uniform_01 ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% R8MAT_UNIFORM_01 returns a unit pseudorandom R8MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Linus Schrage,\n% A Guide to Simulation,\n% Second Edition,\n% Springer, 1987,\n% ISBN: 0387964673,\n% LC: QA76.9.C65.B73.\n%\n% Bennett Fox,\n% Algorithm 647:\n% Implementation and Relative Efficiency of Quasirandom\n% Sequence Generators,\n% ACM Transactions on Mathematical Software,\n% Volume 12, Number 4, December 1986, pages 362-376.\n%\n% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998,\n% ISBN: 0471134031,\n% LC: T57.62.H37.\n%\n% Peter Lewis, Allen Goodman, James Miller,\n% A Pseudo-Random Number Generator for the System/360,\n% IBM Systems Journal,\n% Volume 8, Number 2, 1969, pages 136-143.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in the array.\n%\n% Input, integer SEED, the integer \"seed\" used to generate\n% the output random number.\n%\n% Output, real R(M,N), an array of random values between 0 and 1.\n%\n% Output, integer SEED, the updated seed. This would\n% normally be used as the input seed on the next call.\n%\n i4_huge = 2147483647;\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8MAT_UNIFORM_01 - Fatal error!' );\n end\n\n for j = 1 : n\n for i = 1 : m\n\n seed = floor ( seed );\n\n seed = mod ( seed, i4_huge );\n\n if ( seed < 0 ) \n seed = seed + i4_huge;\n end \n\n k = floor ( seed / 127773 );\n\n seed = 16807 * ( seed - k * 127773 ) - k * 2836;\n\n if ( seed < 0 )\n seed = seed + i4_huge;\n end\n\n r(i,j) = seed * 4.656612875E-10;\n\n end\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/uniform_dataset/uniform_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.6346013377501943}} {"text": "clear, clc;\n\n% This is an example for running the function tree_LeastR\n%\n% Problem:\n%\n% min 1/2 || A x - y||^2 + z * sum_j w_j ||x_{G_j}||\n%\n% G_j's are nodes with tree structure\n%\n% The tree structured group information is contained in\n% opts.ind, which is a 3 x nodes matrix, where nodes denotes the number of\n% nodes of the tree.\n%\n% opts.ind(1,:) contains the starting index\n% opts.ind(2,:) contains the ending index\n% opts.ind(3,:) contains the corresponding weight (w_j)\n%\n% Note: \n% 1) If each element of x is a leaf node of the tree and the weight for\n% this leaf node are the same, we provide an alternative \"efficient\" input\n% for this kind of node, by creating a \"super node\" with \n% opts.ind(1,1)=-1; opts.ind(2,1)=-1; and opts.ind(3,1)=the common weight.\n%\n% 2) If the features are well ordered in that, the features of the left\n% tree is always less than those of the right tree, opts.ind(1,:) and\n% opts.ind(2,:) contain the \"real\" starting and ending indices. That is to\n% say, x( opts.ind(1,j):opts.ind(2,j) ) denotes x_{G_j}. In this case,\n% the entries in opts.ind(1:2,:) are within 1 and n.\n%\n%\n% If the features are not well ordered, please use the input opts.G for\n% specifying the index so that \n% x( opts.G ( opts.ind(1,j):opts.ind(2,j) ) ) denotes x_{G_j}.\n% In this case, the entries of opts.G are within 1 and n, and the entries of\n% opts.ind(1:2,:) are within 1 and length(opts.G).\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Moreau-Yosida Regularization for \n% Grouped Tree Structure Learning, NIPS 2010\n%\n%%\n\ncd ..\ncd ..\n\nroot=cd;\naddpath(genpath([root '/SLEP']));\n % add the functions in the folder SLEP to the path\n \n% change to the original folder\ncd Examples/tree;\n\nm=50; n=100; % The data matrix is of size m x n\n\n%randNum=10; % a random number\n\n% ---------------------- generate random data ----------------------\n%randn('state',(randNum-1)*3+1);\nA=randn(m,n); % the data matrix\n\n%randn('state',(randNum-1)*3+2);\nxOrin=full(sprandn(n, 1,1));\nxOrin(1:50,:)=0;\n\n%randn('state',(randNum-1)*3+3);\nnoise=randn(m,1);\ny=A*xOrin +...\n noise*0.01; % the response\n\n%% In this example, the tree is set as:\n%\n% root, 1:100, with weight 0\n% its children nodes, 1:50, and 51:100\n%\n% For 1:50, its children are 1:20, 21:40, and 41:50\n%\n% For 51:100, its children are 51:70, and 71:100\n%\n% These nodes in addition have each individual features (they contain) as\n% children nodes.\n%\n%%\n\n%% One efficient way\n% We make use of the fact that the indices of the left nodes of the tree\n% are smaller than the right nodes.\n\n%----------------------- Set optional items -----------------------\nopts=[];\n\n% Starting point\nopts.init=2; % starting from a zero point\n\n% Termination \nopts.tFlag=5; % run .maxIter iterations\nopts.maxIter=100; % maximum number of iterations\n\n% regularization\nopts.rFlag=1; % use ratio\n\n% Normalization\nopts.nFlag=0; % without normalization\n\n% Group Property\nopts.ind=[[-1, -1, 1]',... % leave nodes (each node contains one feature)\n [1, 20, sqrt(20)]', [21, 40, sqrt(20)]',... % the layer above the leaf\n [41, 50, sqrt(10)]', [51, 70, sqrt(20)]', [71,100, sqrt(30)]',...\n [1, 50, sqrt(50)]', [51, 100, sqrt(50)]']; % the higher layer\n\n%----------------------- Run the code tree_LeastR -----------------------\nz=0.1;\ntic;\n[x1, funVal1, ValueL1]= tree_LeastR(A, y, z, opts);\ntoc;\n\n\n%% An alternative way\n% We make use of the fact that the indices of the left nodes of the tree\n% are smaller than the right nodes.\n%%\n\n%----------------------- Set optional items -----------------------\nopts=[];\n\n% Starting point\nopts.init=2; % starting from a zero point\n\n% Termination \nopts.tFlag=5; % run .maxIter iterations\nopts.maxIter=100; % maximum number of iterations\n\n% regularization\nopts.rFlag=1; % use ratio\n\n% Normalization\nopts.nFlag=0; % without normalization\n\n% Group Property\nopts.ind=[[-1, -1, 1]',... % leave nodes (each node contains one feature)\n [1, 20, sqrt(20)]', [21, 40, sqrt(20)]',... % the layer above the leaf\n [41, 50, sqrt(10)]', [51, 70, sqrt(20)]', [71,100, sqrt(30)]',...\n [101, 150, sqrt(50)]', [151, 200, sqrt(50)]']; % the higher layer\nopts.G=[1:100, 1:100];\n\n%----------------------- Run the code tree_LeastR -----------------------\nz=0.1;\ntic;\n[x2, funVal2, ValueL2]= tree_LeastR(A, y, z, opts);\ntoc;\n\n", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/Examples/tree/example_tree_LeastR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6345913177998246}} {"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 price = FFTCOS_UpAndOut(n, Nex,H,Rb, L, c, cp, type, S0, t, r, q, ...\n strike, varargin)\n\n% Function FFTCOS_UpAndOut calculates the price of a discretely\n% monitored Up-and-Out Call or Put option by use of the Fourier-Cosine\n% Series Expansion introduced by Oosterlee & Fang\n%------------------------------------------------------------------------\n\n% Nex := number of examination points\n% H := Barrier\n% Rb := Rebate\n \ndt = t / Nex; % time interval\nNgrid = 2 ^ n; % Grid points\nNstrike = size(strike,1); % number of strikes\n\nx = double(log(S0 ./ strike)); % center\nh = double(log(H ./ strike));\n\na = double(c(1) + x - L * sqrt(c(2) + sqrt(c(3)))); % lower trunc\nb = double(c(1) + x + L * sqrt(c(2) + sqrt(c(3)))); % upper trunc\n\nGrid_i = repmat((0:Ngrid-1)',1,Nstrike); % Grid index\n\n% Set up function handles\nif cp == 1\n vk = @(x) calcv(Grid_i, x, h, a, b, cp, strike);\n if h >= 0\n V = vk(0);\n end\nelse\n vk = @(x) calcv(Grid_i, a, x, a, b, cp, strike);\n if h >= 0\n V = vk(0);\n else\n V = vk(h);\n end\nend\n\ncv = @(y) cvalue(a, h, a, b, Ngrid, y, type, dt, r, q, varargin{:});\n\naux = pi * Grid_i * diag(1./(b-a));\nG = ((sin(aux * diag(b-a))-sin(aux*diag(h-a)))./aux);\nG = exp(-r * dt) * 2 * Rb * [((b-h)./(b-a))';G(2:end,:)]* diag(1./(b-a));\n\nV = V + G;\nfor m = Nex-1:-1:1 % backward induction\n V = cv(V) + G;\nend\n\ncfval = exp(feval(@CF, type,aux, dt,r,q,varargin{:}));\n\npF = cfval .* exp( 1i * aux * diag(x - a) );\npF(1,:) = 0.5*pF(1,:);\nprice = exp(-r * dt) * sum(real(pF) .* V) ; % Option value at t_0\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/37617-cos-method-multiple-strikes-bermudan-greeks/Cos_Method_Bermudan_Mult_Strikes/FFTCOS_UpAndOut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6345864118495562}} {"text": "% New SVD based initialization strategy for Non-negative Matrix Factorization\n% Hanli Qiao\n\n\nfunction [W, H] = Qiao_SVD_Init(Z, rank)\n [u, s, v, p] = ChoosingR(Z);\n W = abs(u(:,1:rank));\n H = abs(s(1:rank,:)*v'); \nend\n\nfunction [u, s, v, p] = ChoosingR(Z)\n [u,s,v] = svd(Z);\n sum1= sum(s);\n sum2=sum(sum1);\n extract=0;\n p = 0;\n dsum=0;\n while(extract/sum2<0.90)\n p = p + 1;\n dsum=dsum+s(p,p);\n extract=dsum;\n end\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/auxiliary/initialization/Qiao_SVD_Init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6345864097824668}} {"text": "function [ key, seed, matrix, ierror ] = rcont2 ( nrow, ncol, nrowt, ncolt, ...\n key, seed )\n\n%*****************************************************************************80\n%\n%% RCONT2 constructs a random two-way contingency table with given sums.\n%\n% Discussion:\n%\n% It is possible to specify row and column sum vectors which\n% correspond to no table at all. As far as I can see, this routine does\n% not detect such a case.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 March 2009\n%\n% Author:\n%\n% Original FORTRAN77 version by WM Patefield.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% WM Patefield,\n% Algorithm AS 159:\n% An Efficient Method of Generating RXC Tables with\n% Given Row and Column Totals,\n% Applied Statistics,\n% Volume 30, Number 1, 1981, pages 91-97.\n%\n% Parameters:\n%\n% Input, integer NROW, NCOL, the number of rows and columns\n% in the table. NROW and NCOL must each be at least 2.\n%\n% Input, integer NROWT(NROW), NCOLT(NCOL), the row and column\n% sums. Each entry must be positive.\n%\n% Input, logical KEY, a flag that indicates whether data has\n% been initialized for this problem. Set KEY = .FALSE. before the first\n% call.\n%\n% Input, integer SEED, a seed for the random number\n% generator.\n%\n% Output, logical KEY, a flag that indicates whether data has\n% been initialized for this problem. Set KEY = .FALSE. before the first\n% call.\n%\n% Output, integer SEED, a seed for the random number\n% generator.\n%\n% Output, integer MATRIX(NROW,NCOL), the matrix.\n%\n% Output, integer IERROR, an error flag, which is returned\n% as 0 if no error occurred.\n%\n\n persistent fact;\n persistent ntotal;\n\n ierror = 0;\n%\n% On user's signal, set up the factorial table.\n%\n if ( ~key )\n\n key = 1;\n\n if ( nrow <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RCONT - Fatal error!\\n' );\n fprintf ( 1, ' Input number of rows is less than 2.\\n' );\n ierror = 1;\n return\n end\n\n if ( ncol <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RCONT - Fatal error!\\n' );\n fprintf ( 1, ' The number of columns is less than 2.\\n' );\n ierror = 2;\n return\n end\n\n for i = 1 : nrow\n if ( nrowt(i) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RCONT - Fatal error!\\n' );\n fprintf ( 1, ' An entry in the row sum vector is not positive.\\n' );\n ierror = 3;\n return\n end\n end\n\n for j = 1 : ncol\n if ( ncolt(j) <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RCONT - Fatal error!\\n' );\n fprintf ( 1, ' An entry in the column sum vector is not positive.\\n' );\n ierror = 4;\n return\n end\n end\n\n if ( sum ( ncolt(1:ncol) ) ~= sum ( nrowt(1:nrow) ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RCONT - Fatal error!\\n' );\n fprintf ( 1, ' The row and column sum vectors do not have the same sum.\\n' );\n ierror = 6;\n return\n end\n\n ntotal = sum ( ncolt(1:ncol) );\n\n fact = zeros(ntotal,1);\n%\n% Calculate log-factorials.\n%\n x = 0.0;\n fact(1) = 0.0;\n for i = 1 : ntotal\n x = x + log ( i );\n fact(i+1) = x;\n end\n\n end\n%\n% Construct a random matrix.\n%\n jwork(1:ncol-1) = ncolt(1:ncol-1);\n\n jc = ntotal;\n\n for l = 1 : nrow - 1\n\n nrowtl = nrowt(l);\n ia = nrowtl;\n ic = jc;\n jc = jc - nrowtl;\n\n for m = 1 : ncol - 1\n\n id = jwork(m);\n ie = ic;\n ic = ic - id;\n ib = ie - ia;\n ii = ib - id;\n%\n% Test for zero entries in matrix.\n%\n if ( ie == 0 )\n ia = 0;\n matrix(l,m:ncol) = 0;\n break\n end\n%\n% Generate a pseudo-random number.\n%\n [ r, seed ] = r8_uniform_01 ( seed );\n%\n% Compute the conditional expected value of MATRIX(L,M).\n%\n done1 = 0;\n\n while ( 1 );\n\n nlm = floor ( ia * id / ie + 0.5 );\n iap = ia + 1;\n idp = id + 1;\n igp = idp - nlm;\n ihp = iap - nlm;\n nlmp = nlm + 1;\n iip = ii + nlmp;\n x = exp ( fact(iap) + fact(ib+1) + fact(ic+1) + fact(idp) - ...\n fact(ie+1) - fact(nlmp) - fact(igp) - fact(ihp) - fact(iip) );\n\n if ( r <= x )\n break;\n end\n\n sumprb = x;\n y = x;\n nll = nlm;\n lsp = 0;\n lsm = 0;\n%\n% Increment entry in row L, column M.\n%\n while ( ~lsp )\n\n j = ( id - nlm ) * ( ia - nlm );\n\n if ( j == 0 )\n\n lsp = 1;\n\n else\n\n nlm = nlm + 1;\n x = x * j / ( nlm * ( ii + nlm ) );\n sumprb = sumprb + x;\n\n if ( r <= sumprb )\n done1 = 1;\n break\n end\n\n end\n\n done2 = 0;\n\n while ( ~lsm )\n%\n% Decrement the entry in row L, column M.\n%\n j = nll * ( ii + nll );\n\n if ( j == 0 )\n lsm = 1;\n break\n end\n\n nll = nll - 1;\n y = y * j / ( ( id - nll ) * ( ia - nll ) );\n sumprb = sumprb + y;\n\n if ( r <= sumprb )\n nlm = nll;\n done2 = 1;\n break\n end\n\n if ( ~lsp )\n break\n end\n\n end\n\n if ( done2 )\n break\n end\n\n end\n\n if ( done1 )\n break\n end\n\n if ( done2 )\n break\n end\n\n [ r, seed ] = r8_uniform_01 ( seed );\n r = sumprb * r;\n\n end\n\n matrix(l,m) = nlm;\n ia = ia - nlm;\n jwork(m) = jwork(m) - nlm;\n\n end\n\n matrix(l,ncol) = ia;\n\n end\n%\n% Compute the last row.\n%\n matrix(nrow,1:ncol-1) = jwork(1:ncol-1);\n matrix(nrow,ncol) = ib - matrix(nrow,ncol-1);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa159/rcont2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6345821207972939}} {"text": "function [chi, labels] = imEuler3dEstimate(img, varargin)\n% Estimate Euler number in a 3D image.\n%\n% CHIest = imEuler3dEstimate(IMG)\n% CHIest = imEuler3dEstimate(IMG, CONN)\n% Estimate Euler number in a 3D image, without taking into account the\n% contribution of the voxels located on image border. The result of this\n% function is usually divided by the volume the sampling window to obtain\n% an estimate of Euler number density.\n%\n% Example\n% imEuler3dEstimate\n%\n% See also\n% imEuler3dDensity, imEuler3d\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRAE - Cepia Software Platform.\n\n\n%% Process input arguments \n\n% check image dimension\nif ndims(img) ~= 3\n error('first argument should be a 3D image');\nend\n\n% in case of a label image, return a vector with a set of results\nif ~islogical(img)\n labels = unique(img);\n labels(labels==0) = [];\n chi = zeros(length(labels), 1);\n for i = 1:length(labels)\n chi(i) = imEuler3dEstimate(img==labels(i), varargin{:});\n end\n return;\nend\n\n% extract connectivity\nconn = 6;\nif ~isempty(varargin)\n conn = varargin{1};\nend\n\n% determines connectivity to use on faces\nconn2d = 4;\nif conn == 26\n conn2d = 8;\nend\n\n% in case of binary image, compute only one label...\nlabels = 1;\n\n\n%% Main processing\n\n% Euler-Poincare Characteristic of the binary structure in image\nchi = imEuler3d(img, varargin{:});\n\n% compute EPC on each of the 12 border edge of image, and keep the average\nchix = mean([ ...\n imEuler1d(img(:, 1, 1)) ...\n imEuler1d(img(:, end, 1)) ...\n imEuler1d(img(:, 1, end)) ...\n imEuler1d(img(:, end, end)) ...\n ]);\nchiy = mean([ ...\n imEuler1d(img( 1, :, 1)) ...\n imEuler1d(img(end, :, 1)) ...\n imEuler1d(img( 1, :, end)) ...\n imEuler1d(img(end, :, end)) ...\n ]);\nchiz = mean([ ...\n imEuler1d(img( 1, 1, :)) ...\n imEuler1d(img(end, 1, :)) ...\n imEuler1d(img( 1, end, :)) ...\n imEuler1d(img(end, end, :)) ...\n ]);\n\n% compute EPC on each of the 6 border faces, and keep the average\nchixy = mean([ ...\n imEuler2d(squeeze(img(:, :, 1)), conn2d) ...\n imEuler2d(squeeze(img(:, :, end)), conn2d) ...\n ]);\nchixz = mean([ ...\n imEuler2d(squeeze(img(:, 1, :)), conn2d) ...\n imEuler2d(squeeze(img(:, end, :)), conn2d) ...\n ]);\nchiyz = mean([ ...\n imEuler2d(squeeze(img( 1, :, :)), conn2d) ...\n imEuler2d(squeeze(img(end, :, :)), conn2d) ...\n ]);\n\n% compute EPC on each of the 8 corners of image, and keep the average\nchixyz = mean([ ...\n img( 1, 1, 1), ...\n img(end, 1, 1), ...\n img( 1, end, 1), ...\n img(end, end, 1), ...\n img( 1, 1, end), ...\n img(end, 1, end), ...\n img( 1, end, end), ...\n img(end, end, end), ...\n ]);\n\n\n% estimate EPC in image using mean edge correction\nchi = chi - (chix + chiy + chiz) + (chixy + chixz + chiyz) - chixyz;\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/imEuler3dEstimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6345642247899281}} {"text": "function [mx,my,mz] = blochsim2(Mi, bx, by, bz, T1, T2, dt)\n\n%\tEvolve magnetization field using time-discretized Bloch equation\n%\tInput\n%\t\tMi [3,dim]\tinitial X,Y,Z magnetization\n%\t\t\t\t\tNote: normalized to magnitude <= Mo=1\n%\t\tbx,by,bz [ntime,dim]\teffective X,Y,Z applied magnetic field\n%\t\t\t\t\t(Tesla), for rotating frame (no Bo)\n%\t\tT1\t[dim]\t\tspin-lattice relaxation time (msec)\n%\t\tT2\t[dim]\t\tspin-spin relaxation time (msec)\n%\t\tdt\tscalar\t\ttime interval (msec)\n%\tOutput\n%\t\tmx,my,mz [ntime,dim] X,Y,Z magnetization as a function of time\n%\n% uses:\n% https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula\n\n% constants\ngambar = 42.57e3; % gamma/2pi in kHz/T\ngam = 267513; %gambar*2*pi;\n% Put Beff into units rotations, T1 and T2 into losses\nbx = bx.*(dt*gam); % rotation angle/step\nby = by.*(dt*gam); % rotation angle/step\nbz = bz.*(dt*gam); % rotation angle/step\n% Put relaxations into losses/recovery per step\nT1 = (dt ./ T1(:)); \nT2 = (1 - dt ./ T2(:));\n\n% size checks\nif ~isreal(bx) || ~isreal(by) || ~isreal(bz) \n bx = real(bx);\n by = real(by);\n bz = real(bz);\n disp('Warning: B field must be real valued - using only the real part');\nend\nif (size(bx) ~= size(by)) || (size(bx) ~= size(bz))\n disp('Error: B vectors not the same length')\n return;\nend\nif (size(Mi,2) ~= size(bx,2))\n disp('Error: Initial magnetization not right size')\n return;\nend\nif (size(Mi,2) ~= length(T1))\n disp('Error: T1 vector not right size')\n return;\nend\nif (size(Mi,2) ~= length(T2))\n disp('Error: T2 vector not right size')\n return;\nend\n\nnstep = size(bx,1);\n%\n% Initialize outputs\nmx = zeros(size(bx,1)+1,size(bx,2)); % record one more location\nmy = zeros(size(mx));\nmz = zeros(size(mx));\nmx(1,:) = Mi(1,:);\nmy(1,:) = Mi(2,:);\nmz(1,:) = Mi(3,:);\n\n% stable bloch equation simulator: rotations are explicitly\n% calculated and carried out on the magnetization vector \nfor lp = 2:nstep+1 % Hao: modified from 2:nstep to 2:nstep+1. This will record the mag. after last pulse point. \n B = [bx(lp-1,:); by(lp-1,:); bz(lp-1,:)]'; \n %\tCompute sines & cosines of field angles:\n %\tTheta = angle w.r.t positive z axis\n %\tPhi = angle w.r.t positive x axis\n %\tPsi = angle w.r.t transformed positive x axis\n %\n Bmag = sqrt(sum(B.^2,2));\t\t% Magnitude of applied field\n Btrans = sqrt(B(:,1).^2 + B(:,2).^2);\t% Magnitude of transverse applied field\n ct = ones(size(B,1),1);\n good = Bmag ~= 0;\n if any(good)\n\tct(good) = B(good,3) ./ Bmag(good);\t% cos(theta)\n end\n st = sqrt(1 - ct.^2);\t\t\t\t% sin(theta) > 0\n\n cphi = ones(size(B,1),1);\n good = Btrans ~= 0;\n if any(good)\n\tcphi(good) = B(good,1) ./ Btrans(good);\t% cos(phi)\n end\n sphi = sqrt(1 - cphi.^2) .* sign(B(:,2));\t% sin(phi)\n\n cpsi = cos(Bmag);\t\t\t% cos(psi)\n spsi = sin(Bmag);\t\t\t% sin(psi)\n\n %\n %\tEvolve\n %\n if any(Bmag ~= 0)\n Mx0 = mx(lp-1,:)';\n My0 = my(lp-1,:)';\n Mz0 = mz(lp-1,:)';\n \n Mx1 = cphi.*(ct.*(cpsi.*(ct.*(sphi.*My0+cphi.*Mx0)-st.*Mz0) ...\n + spsi.*(cphi.*My0-sphi.*Mx0))+st.*(ct.*Mz0+st.*(sphi.*My0+cphi.*Mx0))) ...\n - sphi.*(-spsi.*(ct.*(sphi.*My0+cphi.*Mx0)-st.*Mz0) ...\n + cpsi.*(cphi.*My0-sphi.*Mx0));\n My1 = sphi.*(ct.*(cpsi.*(ct.*(sphi.*My0+cphi.*Mx0)-st.*Mz0) ...\n + spsi.*(cphi.*My0-sphi.*Mx0))+st.*(ct.*Mz0+st.*(sphi.*My0+cphi.*Mx0))) ...\n + cphi.*(-spsi.*(ct.*(sphi.*My0+cphi.*Mx0)-st.*Mz0) ...\n + cpsi.*(cphi.*My0-sphi.*Mx0));\n Mz1 = ct.*(ct.*Mz0+st.*(sphi.*My0+cphi.*Mx0)) ...\n - st.*(cpsi.*(ct.*(sphi.*My0+cphi.*Mx0)-st.*Mz0) ...\n + spsi.*(cphi.*My0-sphi.*Mx0));\n else\n Mx1 = mx(lp-1,:)';\n My1 = my(lp-1,:)';\n Mz1 = mz(lp-1,:)';\n end\n % relaxation effects: \"1\" in Mz since Mo=1 by assumption\n mx(lp,:) = (Mx1 .* T2)';\n my(lp,:) = (My1 .* T2)';\n mz(lp,:) = (Mz1 + (1- Mz1).* T1)'; % true, since mz = Mo - (Mo-mz)*exp(-dt/T1) ~ Mo - (Mo-mz)(1-dt/T1) = mz + (Mo-mz)*dt/T1\n\nend % end loop through time\n\n% Hao: made the change so my,my,mz will NOT record the initial mag. But record the mag. after last pulse point \n mx(1,:) = [];\n my(1,:) = [];\n mz(1,:) = []; % true, since mz = Mo - (Mo-mz)*exp(-dt/T1) ~ Mo - (Mo-mz)(1-dt/T1) = mz + (Mo-mz)*dt/T1\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri-rf/sun-bloch/blochsim2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6345359673673483}} {"text": "function [out] = baseflow_5(p1,p2,S,Smax,dt)\n%baseflow_5 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Non-linear scaled outflow from a reservoir\n% Constraints: f <= S/dt\n% @(Inputs): p1 - base outflow rate [mm/d]\n% p2 - exponential scaling parameter [-]\n% S - current storage [mm]\n% Smax - maximum contributing storage [mm]\n% dt - time step size [d]\n\nout = min(S/dt,p1*((max(S,0)/Smax)^p2));\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/baseflow_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6345182074796674}} {"text": "classdef DOC3 < PROBLEM\n% \n% Benchmark MOP with constraints in both decision and objective spaces\n\n%------------------------------- Reference --------------------------------\n% Z. Liu and Y. Wang, Handling constrained multiobjective optimization\n% problems with constraints in both the decision and objective spaces. IEEE\n% Transactions on Evolutionary Computation, 2019, 23(5): 870-884.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n obj.D = 10;\n obj.lower = [0 0 0 0 0 0 0 0 0 0.01];\n obj.upper = [1 1 300 100 200 100 1 100 200 0.03];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values and constraint violations\n function Population = Evaluation(obj,varargin)\n X = varargin{1};\n X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));\n g_temp = -9.* X(:, 6) - 15.* X(:, 9) + 6.* X(:, 2) + 16.* X(:, 3) + 10.* (X(:, 7) + X(:, 8));\n g = (g_temp+400.0551) +1;\n PopObj(:,1) = X(:,1);\n PopObj(:,2) = g.*(1 - (PopObj(:,1))./g);\n % Constraints in objective space\n c(:,1) = max( -(PopObj(:,1).^2 + PopObj(:,2).^2-1), 0);\n c(:,2) = max(-( abs( (-PopObj(:,1) + PopObj(:,2) -0.5)/sqrt(2)) - 0.1/sqrt(2)), 0);\n c(:,3) = max(-( abs( (-PopObj(:,1) + PopObj(:,2) -0)/sqrt(2)) - 0.1/sqrt(2)), 0);\n c(:,4) = max(-( abs( (-PopObj(:,1) + PopObj(:,2) +0.5)/sqrt(2)) - 0.1/sqrt(2)), 0);\n\n % Constraints in decision space\n c(:,5) = X(:, 10).* X(:, 4) + 0.02.* X(:, 7) - 0.025.* X(:, 6);\n c(:,6) = X(:, 10).* X(:, 5) + 0.02.* X(:, 8) - 0.015.* X(:, 9);\n c(:,7) = abs(X(:, 2) + X(:, 3) - X(:, 4) - X(:, 5)) - 0.0001;\n c(:,8) = abs(0.03.* X(:, 2) + 0.01.* X(:, 3) - X(:, 10).* (X(:, 4) + X(:, 5))) - 0.0001;\n c(:,9) = abs(X(:, 4) + X(:, 7) - X(:, 6)) - 0.0001;\n c(:,10) = abs(X(:, 5) + X(:, 8) - X(:, 9)) - 0.0001;\n Population = SOLUTION(X,PopObj,c,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = UniformPoint(N,2);\n R = R./repmat(sqrt(sum(R.^2,2)),1,2);\n R(0.340310^(-p)\n k = k+1;\n t = t*x/k;\n T = T*x/k;\n E = E + T;\nend\nk\nexp(x)\ndisplay(E,0)\n\n%%\n% Note that for large negative values of x there quite some \n% cancellation. This can be seen by\n\nx = 30;\nt = 1; T = long(1); E = T; k = 0;\nwhile abs(t)>10^(-p)\n k = k+1;\n t = t*x/k;\n T = T*x/k;\n E = E + T;\nend\nk\n1/exp(x)\ndisplay(1/E,0)\n\n%% Ill-conditioned polynomials\n% Consider the following polynomial:\n\nP = inline(' 4999*x.^6 - 200*x.^5 + 102*x.^4 - 2*x.^3 - 2500*x.^2 + 100*x - 1 ')\n\n%%\n% This is an example Bugeaud-Mignotte polynomial. The general form is\n%\n% ( X^n - aX + 1 )^k - 2X^(nk-k)(aX-1)^k\n%\n% where a>=10, n>=3 and k>=2.\n%\n% Those polynomials are constructed to have a pair of very close real roots near c=1/a+1/a^(n+1). \n% A graph near c looks as follows:\n\ne = 3e-8; \nc = 1/50+1/50^4;\nx = c*(1+linspace(-e,e));\nclose\nplot(x,P(x),x,0*x)\n\n%%\n% From the graph it is not clear whether the polynomial has no, a double or two real roots\n% in the interval c*[1-e,1+e]. An evaluation using the long package yields\n% the following:\n\ny = long2dble(P(long(x)));\nclose\nplot(x,y,x,0*x)\n\n%% Sample programs\n% For sample programs using long numbers, see for example the\n% source codes of long\\longpi.m or long\\@long\\exp.m .\n\n%% Enjoy INTLAB\n% INTLAB was designed and written by S.M. Rump, head of the Institute for Reliable Computing,\n% Hamburg University of Technology. Suggestions are always welcome to rump (at) tuhh.de\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/demos/dlong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.634331435381797}} {"text": "function xdot=dpendulum(t,x)\n%% Double Pendulum ODE\n%\n% ivp=[gamma0; dtgamma0; alpha0; dtalpha0; beta0; lambda; omega; psi; eta];\n\nbeta0=x(5); lambda=x(6); omega=x(7); psi=x(8); eta=x(9);\nxdot=zeros(9,1); % a column vector\n\nC = cos(beta0)*cos(x(3)-x(1))-sin(beta0)*sin(x(3)-x(1));\nS = sin(beta0)*cos(x(3)-x(1))+cos(beta0)*sin(x(3)-x(1));\n\nxdot(1) = x(2);\nxdot(2) = ((omega^2)*sin(x(1))-psi*(S*(x(4)^2+C*x(2)^2*eta)+...\n C*(lambda^2)*sin(x(3))))/(-1+(C^2)*eta*psi);\nxdot(3) = x(4);\nxdot(4) = (S*eta*(x(2)^2+C*x(4)^2*psi)-C*eta*(omega^2)*sin(x(1))+...\n (lambda^2)*sin(x(3)))/(-1+(C^2)*eta*psi);", "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/NumericalMethods/dpendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6342018554378082}} {"text": "function G = gsp_stochastic_block_graph(N, k, params)\n%GSP_STOCHASTIC_BLOCK_GRAPH Create a stochastic block graph\n% Usage: G = gsp_stochastic_block_graph( N );\n% G = gsp_stochastic_block_graph(N , k);\n%\n% Input parameters:\n% N : Number of nodes (default 1024)\n% k : Number of clusters (default 5)\n% params: Structure of optional parameters\n% Output parameters:\n% G : Graph structure.\n%\n% *param* is an optional structure with the following fields\n%\n% * *params.p* : Intra-cluster edge probability (default 0.7)\n% * *params.q* : Inter-cluster edge probability (default 0.3/k)\n% * *params.z* : Assignment vector of nodes (default uniform random)\n% * *params.M* : Link probability matrix between clusters (default uses p and q)\n% * *params.directed* : Flag the graph as directed or not (default false)\n%\n% Use the stochastic block model to create a graph.\n\n% Author: Pierre Vandergheynst, Nathanael Perraudin\n% Date : 2 novemeber 2015 (revision: 6 october 2016 -- Lionel Martin)\n\n\n\n%% Stochastic Block Model generator\nif nargin<1\n N = 1024; % number of nodes\nend\nif nargin<2\n k = 5; % number of clusters\nend\nif nargin < 3\n params = struct;\nend\n\nif ~isfield(params, 'p')\n params.p = 0.7;\nend\n\nif ~isfield(params, 'q')\n params.q = (1-params.p) / k;\nend\n\nif ~isfield(params, 'force_full')\n params.force_full = 0;\nend\n\nif ~isfield(params, 'auto_gen_M')\n params.auto_gen_M = 0;\nend\n\nif (~isfield(params, 'z') || length(params.z) ~= N || max(params.z) > k || min(params.z) < 1)\n params.z = randi(k, 1, N);\nend\n\nif (~isfield(params, 'M') || size(params.M) ~= [k, k])\n if params.force_full\n params.M = params.q * ones(k);\n params.M(1:k+1:end) = params.p;\n end\n params.auto_gen_M = 1;\nend\n\nif ~isfield(params, 'directed')\n params.directed = false;\nend\n\n%% partition with clusters of homogenous sizes\n%\n% THIS PART IS NOT NECESSARY BECAUSE SLOW AND REPLACED\n% BY THE SIMPLE \"UNIFORM\" CLUSTER ASSIGNMENT ABOVE\n%\n% L = ceil(N/k);\n% for i=1:k-1\n% z((i-1)*L + 1:i*L) = i;\n% end\n% z((k-1)*L + 1:end) = k;\n \n%% Generate adjacency\nz = params.z;\n\n% for i=1:N\n% for j=i+1:N\n% W(i, j) = ( rand <= M(z(i), z(j)) );\n% if params.directed\n% W(j, i) = ( rand <= M(z(j), z(i)) );\n% else\n% W(j, i) = W(i, j);\n% end\n% end\n% end\nif params.auto_gen_M && ~params.force_full\n [val_z, idx_z] = sort(z);\n counts = diff(find(diff([0, val_z, N])));\n\n if length(counts) ~= k\n error('There is at least one empty class. Check your z.');\n end\n\n W = sprandsym(counts(k), params.p);\n nb_cols_rect = 0;\n\n for i=k:-1:2\n nb_cols_rect = nb_cols_rect + counts(i);\n rect = sprand(counts(i-1), nb_cols_rect, params.q);\n top_left = sprandsym(counts(i-1), params.p);\n W = vertcat(horzcat(top_left, rect), horzcat(rect', W));\n end\n\n W(1:N+1:end) = 0;\n G.W(idx_z, idx_z) = abs(W) > 0;\n\nelse\n M = params.M;\n\n if params.directed\n W = rand(N) <= M(z, z);\n else\n A = rand(N);\n A(logical(triu(ones(N)))) = 1;\n W = A <= M(z, z);\n W = W + W';\n end\n\n G.W = sparse(W);\nend\n \nG = gsp_graph_default_parameters(G);\nG.info.node_com = z;\n\nG.coords = ones(N, 2);\ncom_coords = sqrt(N) * [-cos(2*pi*(1:k)/k)', sin(2*pi*(1:k)/k)'];\n\n% create uniformly random points in the unit disc\nfor ii = 1:N\n % use rejection sampling to sample from a unit disc (probability = pi/4)\n while norm(G.coords(ii, :)) >= 1/2\n % sample from the square and reject anything outside the circle\n G.coords(ii, :) = [rand-.5, rand-.5];\n end\nend\n\n% add the offset for each node depending on which community it belongs to\nfor ii = 1:k\n idx_ii = find(z==ii);\n rad_com = sqrt(numel(idx_ii));\n G.coords(idx_ii, :) = bsxfun(@plus, rad_com * G.coords(idx_ii, :), com_coords(ii, :));\nend\n\nend\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/graphs/gsp_stochastic_block_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6341966314390571}} {"text": "function [R,eff] = randmio_und_signed(W, ITER)\n% RANDMIO_UND_SIGNED\tRandom graph with preserved signed degree distribution\n%\n% R = randmio_und_signed(W,ITER);\n% [R,eff] = randmio_und_signed(W,ITER);\n%\n% This function randomizes an undirected network with positively and\n% negatively signed connections, while preserving the positively and\n% negatively signed degree distribution. The function does not preserve\n% the strength distribution in weighted networks.\n%\n% Input: W, undirected (binary/weighted) connection matrix\n% ITER, rewiring parameter\n% (each edge is rewired approximately ITER times)\n%\n% Output: R, randomized network\n% eff, number of actual rewirings carried out\n%\n% Reference: Maslov and Sneppen (2002) Science 296:910\n%\n%\n% 2011-2015\n% Dani Bassett, UCSB\n% Olaf Sporns, Indiana U\n% Mika Rubinov, U Cambridge\n\n% Modification History:\n% Mar 2011: Original (Dani Bassett, based on randmio_und.m)\n% Mar 2012: Limit number of rewiring attempts,\n% count number of successful rewirings (Olaf Sporns)\n% Dec 2015: Rewritten the core of the rewiring algorithm to allow\n% unbiased exploration of all network configurations. The new\n% algorithm allows positive-positive/negative-negative\n% rewirings, in addition to the previous positive-positive/0-0\n% and negative-negative/0-0 rewirings (Mika Rubinov). \n\nif nargin('randperm')==1\n warning('This function requires a recent (>2011) version of MATLAB.')\nend\n\nR = double(W); % sign function requires double input\nn = size(R,1);\nITER = ITER*n*(n-1)/2;\n\n% maximal number of rewiring attempts per 'iter'\nmaxAttempts = round(n/2);\n% actual number of successful rewirings\neff = 0;\n\nfor iter=1:ITER\n att=0;\n while (att<=maxAttempts) %while not rewired\n %select four distinct vertices\n nodes = randperm(n,4);\n a = nodes(1);\n b = nodes(2);\n c = nodes(3);\n d = nodes(4);\n \n r0_ab = R(a,b);\n r0_cd = R(c,d);\n r0_ad = R(a,d);\n r0_cb = R(c,b);\n \n %rewiring condition\n if (sign(r0_ab)==sign(r0_cd)) && ...\n (sign(r0_ad)==sign(r0_cb)) && ...\n (sign(r0_ab)~=sign(r0_ad))\n \n R(a,d)=r0_ab; R(a,b)=r0_ad;\n R(d,a)=r0_ab; R(b,a)=r0_ad;\n R(c,b)=r0_cd; R(c,d)=r0_cb;\n R(b,c)=r0_cd; R(d,c)=r0_cb;\n \n eff = eff+1;\n break;\n end %rewiring condition\n att=att+1;\n end %while not rewired\nend %iterations", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/randmio_und_signed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.634196616171591}} {"text": "function mt = SupIntensity_HP(t, History, para, options) \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Compute the super bound of intensity function of Hawkes processes\n%\n% Parameters of Hawkes processes\n% para.mu: base exogenous intensity\n% para.A: coefficients of impact function\n% para.kernel: 'exp', 'gauss'\n% para.w: bandwith of kernel\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\nif isempty(History)\n mt = sum(para.mu);\nelse\n Time = History(1, :);\n index = Time<=t;\n Time = Time(index);\n Event = History(2, index);\n \n MT = sum(para.mu)*ones(1, options.M);\n for m=1:options.M\n t_current = t+(m-1)*options.tstep/options.M;\n \n basis = Kernel(t_current-Time(:), para);\n A = para.A(Event, :, :);\n \n for c = 1:size(para.A, 3);\n MT(m) = MT(m) + sum(sum(basis.*A(:,:,c)));\n end \n end \n mt = max(MT);\nend\n\nmt = mt.*(mt>0);\nend\n\n\n\n\n", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/Simulation/SupIntensity_HP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6341077202519486}} {"text": "% A = riemann_mean(B,epsilon,tol)\n%\n% Calcul du barycentre des matrice de covariances.\n% A : baricentre des K matrices NxN\n%\n% B : Matrice NxNxK\n% epsilon : Pas de la descente de gradient\n% tol : arret de la descente si le crit�re < tol\n\n\nfunction [A critere niter] = opttransp_mean(B,args)\nImat = size(B,3);\nN_itermax = 200;\nif (nargin<2)||(isempty(args))\n tol = 10^-3;\n %A = mean(B,3);\n A = eye(size(B,1));\nelse\n tol = args{1};\n A = args{2};\nend\n\nniter = 0;\nfc = 0;\nK = A^(0.5);\n\nwhile (niter\n% Created: 19th June, 2012\n\n% -- Check arguments\n\nif (nargin < 2)\n help vmrand;\n error('VMRAND:Usage', '*** vmrand: Incorrect usage');\nend\n\n\n% -- Check sizes\n\nvbScalarArgs = [isscalar(fMu) isscalar(fKappa)];\n\nif (nnz(vbScalarArgs) == 1)\n if vbScalarArgs(1)\n % - fMu is scalar\n fMu = repmat(fMu, size(fKappa));\n else\n % - fKappa is scalar\n fKappa = repmat(fKappa, size(fMu));\n end\n \n % - Set return sizes\n vnTensorSize = size(fMu);\n \nelseif (nnz(vbScalarArgs == 0))\n % - Two non-scalar arguments\n if (~isequal(size(fMu), size(fKappa)))\n error('VMRAND:UnequalSizes', ...\n '*** vmrand: ''fMu'' and ''fKappa must be the same size.');\n else\n vnTensorSize = size(fMu);\n end\n \nelseif (~isempty(varargin))\n % - Get argument sizes from varargin (be forgiving)\n varargin = cellfun(@(c)(reshape(c, 1, [])), varargin, 'UniformOutput', false);\n vnTensorSize = [varargin{:}];\n \n % - Take Matlab semantics to make square matrices\n if (isscalar(vnTensorSize))\n vnTensorSize = vnTensorSize([1 1]);\n end\n \n fKappa = repmat(fKappa, vnTensorSize);\n \nelse\n % - Return a scalar variate\n vnTensorSize = [1 1];\nend\n\n\n% -- Check values\n\nif (any(fKappa < 0))\n error('VMRAND:InvalidArguments', ...\n '*** vmrand: ''fKappa'' must be >= 0');\nend\n\nif (any(vnTensorSize < 1))\n error('VMRAND:InvalidArguments', ...\n '*** vmrand: Tensor size dimensions must be positive');\nend\n\n\n% -- Preallocate data\n\ntfVMVariates = nan(vnTensorSize);\ntfZ = nan(vnTensorSize);\ntfF = nan(vnTensorSize);\ntfC = nan(vnTensorSize);\n\n\n% -- Short-cut fKappa == 0\n\ntbUniform = fKappa == 0;\ntfVMVariates(tbUniform) = rand(nnz(tbUniform), 1) * 2*pi - pi;\ntbDraw = ~tbUniform;\ntbAccept = tbUniform;\n\n\n% -- Pre-compute what we can\n\nif (all(vbScalarArgs))\n tfTau = sqrt(4 .* fKappa(1).^2 + 1) + 1;\n tfRho = (tfTau - sqrt(2 .* tfTau)) ./ (2 .* fKappa(1));\n tfR = repmat((1 + tfRho.^2) ./ (2 .* tfRho), vnTensorSize);\n\nelse\n tfTau = sqrt(4 .* fKappa.^2 + 1) + 1;\n tfRho = (tfTau - sqrt(2 .* tfTau)) ./ (2 .* fKappa);\n tfR = (1 + tfRho.^2) ./ (2 .* tfRho);\n clear tfTau tfRho; % - To save some space\nend\n\n\n% -- Draw random variates\n\nwhile (nnz(tbDraw > 0))\n % - Draw partial variates and estimate wrapped Cauchy distribution envelope\n nNumToDraw = nnz(tbDraw);\n tfZ(tbDraw) = cos(pi .* rand(nNumToDraw, 1));\n tfF(tbDraw) = (1 + tfR(tbDraw) .* tfZ(tbDraw)) ./ (tfR(tbDraw) + tfZ(tbDraw));\n tfC(tbDraw) = fKappa(tbDraw) .* (tfR(tbDraw) - tfF(tbDraw));\n \n % - Filter variates\n vfRand2 = rand(nNumToDraw, 1);\n tbAccept(tbDraw) = (tfC(tbDraw) .* (2 - tfC(tbDraw)) - vfRand2) > 0;\n vbRecheck = ~tbAccept(tbDraw);\n if (any(vbRecheck))\n tbAccept(tbDraw & ~tbAccept) = (log(tfC(tbDraw & ~tbAccept) ./ vfRand2(vbRecheck)) + 1 - tfC(tbDraw & ~tbAccept)) >= 0;\n end\n \n % - Construct final variates\n nNumToAccept = nnz(tbDraw & tbAccept);\n tfVMVariates(tbDraw & tbAccept) = sign(rand(nNumToAccept, 1) - 0.5) .* acos(tfF(tbDraw & tbAccept));\n \n % - Mark as being accepted (don't need to try again)\n tbDraw(tbAccept) = false;\nend\n\n\n% -- Shift variates to mean\n\ntfVMVariates = tfVMVariates + fMu;\ntfVMVariates(tfVMVariates > pi) = -2*pi + tfVMVariates(tfVMVariates > pi);\ntfVMVariates(tfVMVariates < -pi) = 2*pi + tfVMVariates(tfVMVariates < -pi);\n\n% --- END of vmrand.m ---\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/37241-von-mises-random-variates/vmrand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6340773737934821}} {"text": "function sparse_count_test025 ( dim_min, dim_max, level_max_min, ...\n level_max_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_COUNT_TEST025 tests CFN_E_SIZE_TOTAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_MIN, the minimum spatial dimension to consider.\n%\n% Input, integer DIM_MAX, the maximum spatial dimension to consider.\n%\n% Input, integer LEVEL_MAX_MIN, the minimum value of LEVEL_MAX to consider.\n%\n% Input, integer LEVEL_MAX_MAX, the maximum value of LEVEL_MAX to consider.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST025\\n' );\n fprintf ( 1, ' CFN_E_SIZE_TOTAL returns the number of\\n' );\n fprintf ( 1, ' points in a CFN_E sparse grid made from \\n' );\n fprintf ( 1, ' any closed fully nested family of 1D quadrature\\n' );\n fprintf ( 1, ' rules with exponential growth, including:\\n' );\n fprintf ( 1, ' * CC_E, the Clenshaw Curtis Exponential Growth family;\\n' );\n fprintf ( 1, ' * NCC_E, the Newton Cotes Closed Exponential Growth family.\\n' );\n fprintf ( 1, ' No reduction is made because of repeated points.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DIM: ' );\n\n for dim_num = dim_min : dim_max\n fprintf ( 1, ' %10d', dim_num );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_MAX\\n' );\n fprintf ( 1, '\\n' );\n\n for level_max = level_max_min : level_max_max\n fprintf ( 1, ' %4d', level_max );\n for dim_num = dim_min : dim_max\n point_num = cfn_e_size_total ( dim_num, level_max );\n fprintf ( 1, ' %10d', point_num );\n end\n fprintf ( 1, '\\n' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_count/sparse_count_test025.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6340307503802062}} {"text": "% vgg_vec De-/vectorization of a matrix.\n%\n% For a matrix X, vgg_vec(X) = X(:).\n% For a N^2-vector x, vgg_vec(x) = reshape(x,N,N).\n%\n% Classical matrix re-arrangement operator, see book Magnus-Neudecker.\n% Trivial function, included mainly for consistency with notation in literature.\n%\n% Useful for rearranging matrix equations. Matrix from the middle of a product can be put to the right as\n%\n% vgg_vec(A*B*C) = kron(C',A)*vgg_vec(B)\n%\n% See also vgg_vec_swap, vgg_commut_matrix, vgg_duplic_matrix.\n\nfunction v = vgg_vec(A)\n\nif any(size(A)==1)\n v = reshape(A,[1 1]*sqrt(prod(size(A))));\nelse\n v = A(:);\nend\n \nreturn", "meta": {"author": "jmmanley", "repo": "VGG-Multiple-View-Geometry", "sha": "f114712de03082bb97229eaf2a65981908b64127", "save_path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry", "path": "github-repos/MATLAB/jmmanley-VGG-Multiple-View-Geometry/VGG-Multiple-View-Geometry-f114712de03082bb97229eaf2a65981908b64127/vgg_numerics/vgg_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6340307409190694}} {"text": "function program_05 ( )\n\n%*****************************************************************************80\n%\n%% PROGRAM_05 displays the points that sample a triangle.\n%\n% Discussion:\n%\n% This program is similar to program_04, but displays the\n% sample points.\n%\n% The program\n% * reads a triangle T (defined by three points),\n% * reads a random number seed;\n% * reads \"1\" for bad scheme, \"2\" for good scheme.\n% * reads N, the number of random values to generate;\n% * it then computes N random points in the triangle;\n% * it determines N1, N2, and N3, the number of points\n% that ended up in subtriangles mbc, amc, and abm,\n% where \"m\" is the centroid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 February 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROGRAM_05 - The Eyeball Test on Sampling\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Define a triangle T:\\n' );\n\n t_v1 = input ( ' Enter [ T.v1.x, T.v1.y]: ' );\n t_v2 = input ( ' Enter [ T.v2.x, T.v2.y]: ' );\n t_v3 = input ( ' Enter [ T.v3.x, T.v3.y]: ' );\n%\n% Get the random seed.\n%\n seed = input ( 'Enter a random number seed: ' );\n rand ( 'state', seed );\n%\n% Get the scheme to use.\n%\n scheme = input ( 'Enter 1 for \"bad scheme\", 2 for \"good scheme\": ' );\n%\n% Get the number of values to generate.\n%\n n = input ( 'Enter the number of samples to generate: ' );\n\n n1 = 0;\n n2 = 0;\n n3 = 0;\n\n p = zeros ( 2, n );\n\n for i = 1 : n\n\n if ( scheme == 1 )\n r = rand;\n s = rand;\n t = rand;\n xi1 = r / ( r + s + t );\n xi2 = s / ( r + s + t );\n xi3 = t / ( r + s + t );\n elseif ( scheme == 2 )\n r = rand;\n s = rand;\n\n xi1 = 1.0 - sqrt ( s );\n xi2 = ( 1.0 - r ) * sqrt ( s );\n xi3 = r * sqrt ( s );\n end\n\n if ( xi1 < xi2 & xi1 < xi3 )\n n1 = n1 + 1;\n elseif ( xi2 < xi1 & xi2 < xi3 )\n n2 = n2 + 1;\n elseif ( xi3 < xi1 & xi3 < xi2 )\n n3 = n3 + 1;\n end\n\n p(1:2,i) = xi1 * t_v1(1:2) ...\n + xi2 * t_v2(1:2) ...\n + xi3 * t_v3(1:2);\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N1 = %8d %% = %8.4f\\n', n1, 100 * n1 / n );\n fprintf ( 1, ' N2 = %8d %% = %8.4f\\n', n2, 100 * n2 / n );\n fprintf ( 1, ' N3 = %8d %% = %8.4f\\n', n3, 100 * n3 / n );\n fprintf ( 1, ' N = %8d %% = %8.4f\\n', n, 100 );\n\n scatter ( p(1,:), p(2,:), 'filled' );\n m = ( t_v1 + t_v2 + t_v3 ) / 3;\n\n line ( [ t_v1(1), t_v2(1) ], [ t_v1(2), t_v2(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n line ( [ t_v2(1), t_v3(1) ], [ t_v2(2), t_v3(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n line ( [ t_v3(1), t_v1(1) ], [ t_v3(2), t_v1(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n\n line ( [ t_v1(1), m(1) ], [ t_v1(2), m(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n line ( [ t_v2(1), m(1) ], [ t_v2(2), m(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n line ( [ t_v3(1), m(1) ], [ t_v3(2), m(2) ], 'Color', 'r', 'LineWidth', 2.0 );\n\n p_min(1) = min ( p(1,:) );\n p_min(1) = min ( p_min(1), t_v1(1) );\n p_min(1) = min ( p_min(1), t_v2(1) );\n p_min(1) = min ( p_min(1), t_v3(1) );\n\n p_max(1) = max ( p(1,:) );\n p_max(1) = max ( p_max(1), t_v1(1) );\n p_max(1) = max ( p_max(1), t_v2(1) );\n p_max(1) = max ( p_max(1), t_v3(1) );\n\n p_min(2) = min ( p(2,:) );\n p_min(2) = min ( p_min(2), t_v1(2) );\n p_min(2) = min ( p_min(2), t_v2(2) );\n p_min(2) = min ( p_min(2), t_v3(2) );\n\n p_max(2) = max ( p(2,:) );\n p_max(2) = max ( p_max(2), t_v1(2) );\n p_max(2) = max ( p_max(2), t_v2(2) );\n p_max(2) = max ( p_max(2), t_v3(2) );\n\n p_range(1) = p_max(1) - p_min(1);\n p_range(2) = p_max(2) - p_min(2);\n\n margin = 0.025 * max ( p_range(1), p_range(2) );\n\n x_min = p_min(1) - margin;\n x_max = p_max(1) + margin;\n y_min = p_min(2) - margin;\n y_max = p_max(2) + margin;\n%\n% The TITLE function will interpret underscores in the title.\n% We need to unescape such escape sequences!\n%\n title_string = 'Sample points in triangle';\n title ( title_string )\n\n axis ( [ x_min, x_max, y_min, y_max ] );\n axis equal\n%\n% Save data to file.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saving data to file \"triangle_samples.txt\".\\n' );\n\n save 'triangle_samples.txt' p -ASCII\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROGRAM_05\\n' );\n fprintf ( 1, ' Normal end of execution.\\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/cg_lab_triangles/program_05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6338539402862242}} {"text": "function x = gen_form(L_p,x_s,A,b,K,M)\n%GEN_FORM Transform a standard-form problem back to the general-form setting.\n%\n% x = gen_form(L_p,x_s,A,b,K,M) (method 1)\n% x = gen_form(L_p,x_s,x_0) (method 2)\n%\n% Transforms the standard-form solution x_s back to the required\n% solution to the general-form problem:\n% x = L_p*x_s + d ,\n% where L_p and d depend on the method as follows:\n% method = 1: L_p = pseudoinverse of L, d = K*(b - A*L_p*x_s)\n% method = 2: L_p = A-weighted pseudoinverse of L, d = x_0.\n%\n% Usually, the standard-form problem is generated by means of\n% function std_form.\n%\n% Note that x_s may have more that one column.\n\n% References: L. Elden, \"Algorithms for regularization of ill-\n% conditioned least-squares problems\", BIT 17 (1977), 134-145.\n% L. Elden, \"A weighted pseudoinverse, generalized singular values,\n% and constrained lest squares problems\", BIT 22 (1982), 487-502.\n% M. Hanke, \"Regularization with differential operators. An itera-\n% tive approach\", J. Numer. Funct. Anal. Optim. 13 (1992), 523-540.\n\n% Per Christian Hansen, IMM, 06/12/93.\n\n% Nargin determines which method.\nif (nargin==6)\n [p,q] = size(x_s); Km = size(K,1);\n if (Km==0)\n x = L_p*x_s;\n else\n x = L_p*x_s + K*(M*(b*ones(1,q) - A*(L_p*x_s)));\n end\nelse\n x_0 = A; [p,q] = size(x_s);\n x = L_p*x_s + x_0*ones(1,q);\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/regu/regu/gen_form.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6338539377744874}} {"text": "function clusterLabels = gacMerging(graphW, initClusters, groupNumber, strDescr, z)\n%% Cluster merging for Graph Agglomerative Clustering \n% Implements an agglomerative clustering algorithm based on maiximum graph\n% strcutural affinity of two groups\n% Inputs:\n%\t- graphW: asymmetric weighted adjacency matrix\n% - initClusters: a cell array of clustered vertices\n% - groupNumber: the final number of clusters\n% - strDescr: structural descriptor, 'zeta' or 'path'\n% - z: (I - z*P), default: 0.01\n% Outputs:\n% - clusterLabels: 1 x m list whose i-th entry is the group assignment of\n% the i-th data vector w_i. Groups are indexed\n% sequentially, starting from 1. \n% by Wei Zhang (wzhang009 at gmail.com), June, 8, 2011\n\n%% \nnumSample = size(graphW,1);\nIminuszW = eye(numSample) - z*graphW;\nclear graphW\nmyInf = 1e10;\n\n%% initialization\nVERBOSE = true;\nswitch lower(strDescr)\n case 'zeta'\n complexity_fun = @gacZetaEntropy;\n conditionalComplexity_fun = @gacZetaCondEntropy;\n case 'path'\n complexity_fun = @gacPathEntropy;\n conditionalComplexity_fun = @gacPathCondEntropy;\n otherwise\n error('GAC: Descriptor type is not supported!');\nend\n\nnumClusters = length(initClusters);\nif numClusters <= groupNumber\n error('GAC: too few initial clusters. Do not need merging!');\nend\n\n%% compute the structural complexity of each initial cluster\nclusterComp = zeros(numClusters,1);\nfor i = 1 : numClusters\n clusterComp(i) = complexity_fun(IminuszW(initClusters{i}, initClusters{i}));\nend\n\n%% compute initial (negative) affinity table (upper trianglar matrix), very slow\nif VERBOSE\n disp(' Computing initial table.' );\nend\naffinityTab = Inf(numClusters);\nfor j = 1 : numClusters\n for i = 1 : j-1\n affinityTab(i, j) = - conditionalComplexity_fun(IminuszW, initClusters{i}, initClusters{j}); \n end\nend\naffinityTab = bsxfun(@plus, clusterComp, clusterComp') + affinityTab;\n\nif VERBOSE\n disp(' Starting merging process');\nend\n\ncurGroupNum = numClusters;\nwhile true \n if mod( curGroupNum, 20 ) == 0 && VERBOSE\n disp([' Group count: ' num2str(curGroupNum)]);\n end\n % Find two clusters with the best affinity\n [minAff, minIndex1] = min(affinityTab(1:curGroupNum, 1:curGroupNum), [], 1);\n [~, minIndex2] = min(minAff);\n minIndex1 = minIndex1(minIndex2);\n if minIndex2 < minIndex1, [minIndex1, minIndex2] = swap(minIndex1, minIndex2); end\n\n % merge the two clusters\n new_cluster = unique([initClusters{minIndex1}; initClusters{minIndex2}]);\n % move the second cluster to be merged to the end of the cluster array\n % note that we only need to copy the end cluster's information to\n % the second cluster's position\n if (minIndex2 ~= curGroupNum)\n initClusters{minIndex2} = initClusters{end};\n clusterComp(minIndex2) = clusterComp(curGroupNum);\n % affinityTab is an upper triangular matrix\n affinityTab(1:minIndex2-1, minIndex2) = affinityTab(1:minIndex2-1, curGroupNum);\n affinityTab(minIndex2, minIndex2+1:curGroupNum-1) = affinityTab(minIndex2+1:curGroupNum-1, curGroupNum);\n end\n \n % update the first cluster and remove the second cluster\n initClusters{minIndex1} = new_cluster;\n initClusters(end) = [];\n clusterComp(minIndex1) = complexity_fun(IminuszW(new_cluster, new_cluster));\n clusterComp(curGroupNum) = myInf;\n affinityTab(:,curGroupNum) = myInf;\n affinityTab(curGroupNum,:) = myInf;\n curGroupNum = curGroupNum - 1;\n if curGroupNum <= groupNumber\n break;\n end\n\n % update the affinity table for the merged cluster\n for groupIndex1 = 1:minIndex1-1\n affinityTab(groupIndex1, minIndex1) = - conditionalComplexity_fun(IminuszW, initClusters{groupIndex1}, new_cluster);\n end\n for groupIndex1 = minIndex1+1:curGroupNum\n affinityTab(minIndex1, groupIndex1) = - conditionalComplexity_fun(IminuszW, initClusters{groupIndex1}, new_cluster);\n end\n affinityTab(1:minIndex1-1, minIndex1) = clusterComp(1:minIndex1-1) + clusterComp(minIndex1) + affinityTab(1:minIndex1-1, minIndex1);\n affinityTab(minIndex1, minIndex1+1:curGroupNum) = clusterComp(minIndex1+1:curGroupNum)' + clusterComp(minIndex1) + affinityTab(minIndex1, minIndex1+1:curGroupNum);\nend\n\n%% generate sample labels\nclusterLabels = ones(numSample,1);\nfor i = 1:length(initClusters)\n clusterLabels(initClusters{i}) = i;\nend\nif VERBOSE\n disp([' Final group count: ' num2str(curGroupNum)]);\nend\n\nend\n\nfunction [y, x] = swap (x, y)\nend", "meta": {"author": "jwyang", "repo": "JULE.torch", "sha": "69bdfd82f9dfd431619a8ee25ac832da76a827e2", "save_path": "github-repos/MATLAB/jwyang-JULE.torch", "path": "github-repos/MATLAB/jwyang-JULE.torch/JULE.torch-69bdfd82f9dfd431619a8ee25ac832da76a827e2/matlab/approaches/common/gactoolbox-master/gacfiles/gacMerging.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6338539201354131}} {"text": "%%******************************************************************\n%% geometric_mean: an example with rotated cone variables\n%%\n%% max {prod(d+B*x) : d+B*x > 0, x <= 10} \n%% \n%% where B = 4xn matrix, \n%% d = 4x1 vector\n%%\n%% [blk,At,C,b,xx] = geometric_mean(B,d,solve); \n%%\n%% E.g. p = 6; m = 4; B = [rand(2,p); -rand(2,p)]; d = rand(m,1);\n%%\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 [blk,At,C,b,xx] = geometric_mean(B,d,solve); \n\n if (nargin == 2); solve = 0; end\n\n n = size(B,2); \n zz = zeros(1,n); \n r2 = sqrt(2); \n blk{1,1} = 'r'; blk{1,2} = [3,3,3];\n blk{2,1} = 'l'; blk{2,2} = [2]; \n At{1,1} = -[B(1,:),0,0,0; B(2,:),0,0,0; zz,r2,0,0; ...\n B(3,:),0,0,0; B(4,:),0,0,0; zz,0,r2,0; ...\n\t zz, 1,0,0; zz, 0,1,0; zz, 0,0,r2]; \n At{2,1} = -[B(1,:),0,0,0; B(3,:),0,0,0]; \n C{1,1} = [d(1:2); 0; d(3:4); 0; 0;0;0]; \n C{2,1} = [d(1); d(3)]; \n b = [zeros(n,1); 0;0;1]; \n blk{3,1} = 'l'; blk{3,2} = n; \n At{3,1} = [eye(n), zeros(n,3)]; C{3,1} = 10*ones(n,1);\n if (solve)\n [bblk,AAt,CC,bb,T] = convertRcone(blk,At,C,b);\n [obj,X,y,Z] = sqlp(bblk,AAt,CC,bb);\n xx = y(1:n); \n end\n%%******************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Examples/geometric_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6338326403821196}} {"text": "function [thetamat, dthetamat] ...\n = ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, ...\n Ftipmat, Mlist, Glist, Slist, dt, ...\n intRes)\n% *** CHAPTER 8: DYNAMICS OF OPEN CHAINS ***\n% Takes thetalist: n-vector of initial joint variables,\n% dthetalist: n-vector of initial joint rates,\n% taumat: An N x n matrix of joint forces/torques, where each row is \n% the joint effort at any time step,\n% g: Gravity vector g,\n% Ftipmat: An N x 6 matrix of spatial forces applied by the \n% end-effector (If there are no tip forces, the user should \n% input a zero and a zero matrix will be used),\n% Mlist: List of link frames {i} relative to {i-1} at the home\n% position,\n% Glist: Spatial inertia matrices Gi of the links,\n% Slist: Screw axes Si of the joints in a space frame, in the format\n% of a matrix with the screw axes as the columns,\n% dt: The timestep between consecutive joint forces/torques,\n% intRes: Integration resolution is the number of times integration\n% (Euler) takes places between each time step. Must be an \n% integer value greater than or equal to 1.\n% Returns thetamat: The N x n matrix of robot joint angles resulting from \n% the specified joint forces/torques,\n% dthetamat: The N x n matrix of robot joint velocities.\n% This function simulates the motion of a serial chain given an open-loop \n% history of joint forces/torques. It calls a numerical integration \n% procedure that uses ForwardDynamics.\n% Example Inputs (3 Link Robot):\n% \n% clc; clear;\n% thetalist = [0.1; 0.1; 0.1];\n% dthetalist = [0.1; 0.2; 0.3];\n% taumat = [[3.63, -6.58, -5.57]; [3.74, -5.55, -5.5]; ...\n% [4.31, -0.68, -5.19]; [5.18, 5.63, -4.31]; ...\n% [5.85, 8.17, -2.59]; [5.78, 2.79, -1.7]; ...\n% [4.99, -5.3, -1.19]; [4.08, -9.41, 0.07]; ...\n% [3.56, -10.1, 0.97]; [3.49, -9.41, 1.23]];\n% %Initialise robot description (Example with 3 links)\n% g = [0; 0; -9.8];\n% Ftipmat = ones(size(taumat, 1), 6);\n% M01 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.089159]; [0, 0, 0, 1]];\n% M12 = [[0, 0, 1, 0.28]; [0, 1, 0, 0.13585]; [-1, 0 ,0, 0]; [0, 0, 0, 1]];\n% M23 = [[1, 0, 0, 0]; [0, 1, 0, -0.1197]; [0, 0, 1, 0.395]; [0, 0, 0, 1]];\n% M34 = [[1, 0, 0, 0]; [0, 1, 0, 0]; [0, 0, 1, 0.14225]; [0, 0, 0, 1]];\n% G1 = diag([0.010267, 0.010267, 0.00666, 3.7, 3.7, 3.7]);\n% G2 = diag([0.22689, 0.22689, 0.0151074, 8.393, 8.393, 8.393]);\n% G3 = diag([0.0494433, 0.0494433, 0.004095, 2.275, 2.275, 2.275]);\n% Glist = cat(3, G1, G2, G3);\n% Mlist = cat(3, M01, M12, M23, M34); \n% Slist = [[1; 0; 1; 0; 1; 0], ...\n% [0; 1; 0; -0.089; 0; 0], ...\n% [0; 1; 0; -0.089; 0; 0.425]];\n% dt = 0.1;\n% intRes = 8;\n% [thetamat, dthetamat] ...\n% = ForwardDynamicsTrajectory(thetalist, dthetalist, taumat, g, ...\n% Ftipmat, Mlist, Glist, Slist, dt, intRes);\n% %Output using matplotlib to plot the joint forces/torques\n% Tf = size(taumat, 1);\n% time=0: (Tf / size(thetamat, 1)): (Tf - (Tf / size(thetamat, 1)));\n% plot(time,thetamat(:, 1),'b')\n% hold on\n% plot(time,thetamat(:, 2), 'g')\n% plot(time,thetamat(:, 3), 'r')\n% plot(time,dthetamat(:, 1), 'c')\n% plot(time,dthetamat(:, 2), 'm')\n% plot(time,dthetamat(:, 3), 'y')\n% title('Plot of Joint Angles and Joint Velocities')\n% xlabel('Time')\n% ylabel('Joint Angles/Velocities')\n% legend('Theta1', 'Theta2', 'Theta3', 'DTheta1', 'DTheta2', 'DTheta3')\n%\n\ntaumat = taumat';\nFtipmat = Ftipmat';\nthetamat = taumat;\nthetamat(:, 1) = thetalist;\ndthetamat = taumat;\ndthetamat(:, 1) = dthetalist;\nfor i = 1: size(taumat, 2) - 1\n for j = 1: intRes\n ddthetalist ...\n = ForwardDynamics(thetalist, dthetalist, taumat(:,i), g, ...\n Ftipmat(:, i), Mlist, Glist, Slist); \n [thetalist, dthetalist] = EulerStep(thetalist, dthetalist, ...\n ddthetalist, dt / intRes);\n end\n thetamat(:, i + 1) = thetalist;\n dthetamat(:, i + 1) = dthetalist;\nend\nthetamat = thetamat';\ndthetamat = dthetamat';\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/ForwardDynamicsTrajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6337734524501472}} {"text": "function [mm]=misssum(X,def)\n%MISSSUM sum of a matrix X with NaN's\n%\n%[mm]=misssum(X,def)\n%\n%This function calculates the sum of a matrix X.\n%X may hold missing elements denoted by NaN's which\n%are ignored.\n%\n%The result is standardized, that is, corrected for the lower\n%number of contributing terms.\n%\n%Check that for no column of X, all values are missing\n\n% Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson\n% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk\n%\n% This program is free software; you can redistribute it and/or modify it under \n% the terms of the GNU General Public License as published by the Free Software \n% Foundation; either version 2 of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS \n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n% You should have received a copy of the GNU General Public License along with \n% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin \n% Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n%Insert zeros for missing, correct afterwards\nmissidx = isnan(X);\ni = find(missidx);\nif ~isempty(i),\n X(i) = zeros(size(i));\nend;\n\n%Find the number of real(non-missing objects)\nif min(size(X))==1,\n n_real=length(X)-sum(missidx);\n weight=length(X);\nelse\n n_real=size(X,1)-sum(missidx);\n weight=size(X,1);\nend\n\ni=find(n_real==0);\nif isempty(i) %All values are real and can be corrected\n mm=weight*sum(X)./n_real;\nelse %There are columns with all missing, insert missing\n n_real(i)=1;\n mm=weight*sum(X)./n_real;\n mm(i)=i + NaN;\nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/nway331/misssum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6337734424238722}} {"text": "function FMatrix=kannumfcc(num,s,Fs)\n%Author: Olutope Foluso Omogbenigun\n%Email: olutopeomogbenigun at hotmail.com\n%University: London Metropolitan University\n%Date: 11/09/07\n%Syntax: M=mfccf(num,s, Fs);\n%Computes and returns the mfcc coefficients for a speech signal s\n%where num is the required number of MFCC coefficients. It utilises the \n%function 'melbankm' from the toolbox Voicebox by Mike Brooks copyright(c)\n%1997 (GNU General Public License), freely available on the internet, \n%to implement the triangular mel filter bank\n\nn=512; %Number of FFT points\nTf=0.025; %Frame duration in seconds\nN=Fs*Tf; %Number of samples per frame\nfn=24; %Number of mel filters\nl=length(s); %total number of samples in speech\nTs=0.01; %Frame step in seconds\nFrameStep=Fs*Ts; %Frame step in samples\na=1;\nb=[1, -0.97]; %a and b are high pass filter coefficients\n\nnoFrames=floor(l/FrameStep); %Maximum no of frames in speech sample\nFMatrix=zeros(noFrames-2, num); %Matrix to hold cepstral coefficients\nlifter=1:num; %Lifter vector index\nlifter=1+floor((num)/2)*(sin(lifter*pi/num));%raised sine lifter version\n\nif mean(abs(s)) > 0.01\n s=s/max(s); %Normalises to compensate for mic vol differences\nend\n\n%Segment the signal into overlapping frames and compute MFCC coefficients\nfor i=1:noFrames-2\n frame=s((i-1)*FrameStep+1:(i-1)*FrameStep+N); %Holds individual frames\n Ce1=sum(frame.^2); %Frame energy\n Ce2=max(Ce1,2e-22); %floors to 2 X 10 raised to power -22\n Ce=log(Ce2);\n framef=filter(b,a,frame); %High pass pre-emphasis filter\n F=framef.*hamming(N); %multiplies each frame with hamming window\n FFTo=fft(F,N); %computes the fft\n melf=melbankm(fn,n,Fs); %creates 24 filter, mel filter bank\n halfn=1+floor(n/2); \n spectr1=log10(melf*abs(FFTo(1:halfn)).^2);%result is mel-scale filtered\n spectr=max(spectr1(:),1e-22);\n c=dct(spectr); %obtains DCT, changes to cepstral domain\n c(1)=Ce; %replaces first coefficient\n coeffs=c(1:num); %retains first num coefficients\n ncoeffs=coeffs.*lifter'; %Multiplies coefficients by lifter value\n FMatrix(i, :)=ncoeffs'; %assigns mfcc coeffs to succesive rows i\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/23119-mfcc/kannumfcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6337734421741911}} {"text": "function [knn_dist, nn_dist] = smooth_knn_dist(distances, k, varargin)\n%SMOOTH_KNN_DIST Compute a continuous version of the distance to the kth\n% nearest neighbor. That is, this is similar to knn-distance but allows\n% continuous k values rather than requiring an integral k. In esscence we\n% are simply computing the distance such that the cardinality of fuzzy set\n% we generate is k.\n% \n% [knn_dist, nn_dist] = SMOOTH_KNN_DIST(distances, k, local_connectivity,\n% n_iter, bandwidth)\n% \n% Parameters\n% ----------\n% distances: array of size (n_samples, n_neighbors)\n% Distances to nearest neighbors for each samples. Each row should be a\n% sorted list of distances to a given sample's nearest neighbors.\n% \n% k: double\n% The number of nearest neighbors to approximate for.\n% \n% n_iter: double (optional, default 64)\n% We need to binary search for the correct distance value. This is the\n% max number of iterations to use in such a search.\n% \n% local_connectivity: double (optional, default 1)\n% The local connectivity required -- i.e. the number of nearest\n% neighbors that should be assumed to be connected at a local level.\n% The higher this value the more connected the manifold becomes\n% locally. In practice this should be not more than the local intrinsic\n% dimension of the manifold.\n% \n% bandwidth: double (optional, default 1)\n% The target bandwidth of the kernel, larger values will produce\n% larger return values.\n% \n% Returns\n% -------\n% knn_dist: array of size (n_samples, 1)\n% The distance to kth nearest neighbor, as suitably approximated.\n% \n% nn_dist: array of size (n_samples, 1)\n% The distance to the 1st nearest neighbor for each point.\n%\n% AUTHORSHIP\n% Math Lead & Primary Developer: Connor Meehan \n% Secondary Developer: Stephen Meehan \n% Bioinformatics Lead: Wayne Moore \n% Provided by the Herzenberg Lab at Stanford University \n% License: BSD 3 clause\n%\n p=parseArguments();\n parse(p,varargin{:});\n args=p.Results;\n local_connectivity = args.local_connectivity;\n n_iter = args.n_iter;\n bandwidth = args.bandwidth;\n same_set = args.same_set;\n \n SMOOTH_K_TOLERANCE = 1e-5;\n MIN_K_DIST_SCALE = 1e-3;\n \n height = size(distances,1);\n \n target = log2(k)*bandwidth;\n\n lo = zeros(height,1);\n hi = Inf(height,1);\n mid = ones(height,1);\n\n zero_dists = sum(distances == 0, 2);\n \n if any(zero_dists==size(distances,2))\n warning('There are at least n_neighbors identical data points in the raw data. Results may be inaccurate.');\n end\n \n index = floor(local_connectivity);\n interpolation = local_connectivity - index;\n aug_dists = [lo distances repmat(max(distances, [], 2), [1 index+1])];\n \n idx = sub2ind(size(aug_dists), (1:height)', zero_dists + index + 1);\n rho = aug_dists(idx) + interpolation*(aug_dists(idx) - aug_dists(idx+height));\n \n if same_set\n d = distances(:,2:end) - rho;\n else\n d = distances(:,1:end) - rho;\n end\n\n for n = 1:n_iter\n \n summands = exp(-max(0, d./repmat(mid, [1 size(d, 2)])));\n\n psum = sum(summands, 2);\n \n if all(abs(psum - target) < SMOOTH_K_TOLERANCE)\n break\n end\n \n b = ~(psum > target).*hi;\n b(isnan(b)) = 0;\n \n hi = (psum > target).*mid + b;\n lo = (psum > target).*lo + ~(psum > target).*mid;\n \n c = (psum > target).*((lo + hi)/2);\n c(isnan(c)) = 0;\n \n mid = c + ~(psum > target).*min(2*lo, (lo + hi)/2);\n\n end\n\n result = mid;\n \n result = max(result, MIN_K_DIST_SCALE * ((rho > 0).*mean(distances,2) + (rho == 0).*mean(mean(distances))));\n\n knn_dist = result;\n nn_dist = rho;\nend\n \n function p=parseArguments(varargin)\n p = inputParser;\n addParameter(p,'local_connectivity', 1);\n addParameter(p,'n_iter', 64);\n addParameter(p,'bandwidth', 1);\n addParameter(p,'same_set','true');\n end\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/umap/umap/smooth_knn_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6337081660331952}} {"text": "function M = lbs_matrix(V,W)\n % LBS_MATRIX construct a matrix that when multiplied against a column of\n % affine transformation entries computes new coordinates of the vertices\n %\n % M = lbs_matrix(V,W)\n %\n % Input:\n % V #V by dim list of vertex rest positions\n % W #W by #handles list of correspondence weights\n % Output:\n % M #V * dim by #handles * dim * (dim+1) matrix such that\n % new_V(:) = LBS(V,W,A) = reshape(M * A,size(V)), where A is a column\n % vectors formed by the entries in each handle's dim by dim+1 \n % transformation matrix. Specifcally, A =\n % reshape(permute(Astack,[3 1 2]),n*dim*(dim+1),1)\n % or A = [Lxx;Lyx;Lxy;Lyy;tx;ty], and likewise for other dim\n % if Astack(:,:,i) is the dim by (dim+1) transformation at handle i\n %\n % Example:\n % MLBS = lbs_matrix(V,W);\n % n = size(V,1);\n % dim = size(V,2);\n % m = size(W,2);\n % % stack of identity transformations\n % Astack = repmat([eye(dim,dim) zeros(dim,1)],[1 1 m]);\n % % collect transformations into column\n % A = reshape(permute(Astack,[3 1 2]),m*dim*(dim+1),1);\n % % apply transformations\n % new_V = MLBS*A;\n % new_V = reshape(new_V,[n dim]);\n % \n % % Alternative:\n % % Q is #W by 4 list of quats, T is #W by 3 list of translations\n % % A is #W*4 by 3 stack of transposed affine transformations\n % A = reshape(cat(2,permute(quat2mat(Q),[2 1 3]),permute(T,[2 3 1])),3,[])';\n % % M is #V by #W*4 skinning matrix\n % % M = (𝟙ᵀ⊗ [V 𝟙]) ⊙ (W ⊗ 𝟙ᵀ)\n % %M = kron(ones(1,size(W,2)),[V ones(size(V,1),1)]).* ...\n % % kron(W,ones(1,size(V,2)+1));\n % M = reshape([V ones(size(V,1),1)].*permute(W,[1 3 2]),size(V,1),[]);\n % U = M*A;\n % \n\n % number of mesh (domain) vertices\n n = size(V,1);\n assert(n == size(W,1));\n % dimension of mesh\n dim = size(V,2);\n % number of handles\n m = size(W,2);\n\n % M = zeros(V*dim,m*dim*(dim+1));\n\n % repeat vertex positions so that VV(:,:,i) gives #V by #handles matrix where\n % each column is ith coordinates of vertices\n VV = permute(repmat(V,[1 1 m]),[1 3 2]);\n % multiply each column in VV by respective weights for that handle\n VVW = VV.*repmat(W,[1 1 dim]);\n % matrix of zeros\n Z = zeros(n,m);\n switch dim\n case 2\n M = [ ...\n VVW(:,:,1) Z VVW(:,:,2) Z W Z; ...\n Z VVW(:,:,1) Z VVW(:,:,2) Z W];\n case 3\n M = [ ...\n VVW(:,:,1) Z Z VVW(:,:,2) Z Z VVW(:,:,3) Z Z W Z Z; ...\n Z VVW(:,:,1) Z Z VVW(:,:,2) Z Z VVW(:,:,3) Z Z W Z; ...\n Z Z VVW(:,:,1) Z Z VVW(:,:,2) Z Z VVW(:,:,3) Z Z W];\n otherwise\n error('Only dim=2 or dim=3 supported');\n end\n\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/lbs_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6336988234475417}} {"text": "function [ radius ] = atomic_radius( Z )\n%ATOMIC_RADIUS Get atomic radius of element.\n% r = ATOMIC_RADIUS(Z) returns the atomic radius of element number Z in\n% Angstroms, as given in J. Chem. Phys. 47, 1300 (1967) doi: \n% 10.1063/1.1712084. Z can also be a string the the element symbol. For \n% unrecognized symbols/element numbers, a a value of 1.0 is returned.\n%\n% See also CHEMSYM2NUMBER, NUMBER2CHEMSYM\n\n if ischar(Z)\n Z = chemsym2number(Z);\n end\n \n default_r = 1.0;\n \n r = [ ...\n 0.53 ... H\n 0.31 ... He\n 1.67 ... Li\n 1.12 ... Be\n 0.87 ... B\n 0.67 ... C\n 0.56 ... N\n 0.48 ... O\n 0.42 ... F\n 0.38 ... Ne\n 1.90 ... Na\n 1.45 ... Mg\n 1.18 ... Al\n 1.11 ... Si\n 0.98 ... P\n 0.88 ... S\n 0.79 ... Cl\n 0.71 ... Ar\n 2.43 ... K\n 1.94 ... Ca\n 1.84 ... Sc\n 1.76 ... Ti\n 1.71 ... V\n 1.66 ... Cr\n 1.61 ... Mn\n 1.56 ... Fe\n 1.52 ... Co\n 1.49 ... Ni\n 1.45 ... Cu\n 1.42 ... Zn\n 1.36 ... Ga\n 1.25 ... Ge\n 1.14 ... As\n 1.03 ... Se\n 0.94 ... Br\n 0.88 ... Kr\n 2.65 ... Rb\n 2.19 ... Sr\n 2.12 ... Y\n 2.06 ... Zr\n 1.98 ... Nb\n 1.90 ... Mo\n 1.83 ... Tc\n 1.78 ... Ru\n 1.73 ... Rh\n 1.69 ... Pd\n 1.65 ... Ag\n 1.61 ... Cd\n 1.56 ... In\n 1.45 ... Sn\n 1.33 ... Sb\n 1.23 ... Te\n 1.15 ... I\n 1.08 ... Xe\n 2.98 ... Cs\n 2.53 ... Ba\n default_r ... La (missing value)\n default_r ... Ce (missing value)\n 2.47 ... Pr\n 2.06 ... Nd\n 2.05 ... Pm\n 2.38 ... Sm\n 2.31 ... Eu\n 2.33 ... Gd\n 2.25 ... Tb\n 2.28 ... Dy\n 2.26 ... Ho\n 2.26 ... Er\n 2.22 ... Tm\n 2.22 ... Yb\n 2.17 ... Lu\n%{\n ... Hf\n ... Ta\n ... W \n ... Re\n ... Os\n ... Ir\n ... Pt\n ... Au\n ... Hg\n ... Tl\n ... Pb\n ... Bi\n ... Po\n ... At\n ... Rn\n ... Fr\n ... Ra\n ... Ac\n ... Th\n ... Pa\n ... U\n ... Np\n ... Pu\n ... Am\n ... Cm\n ... Bk\n ... Cf\n ... Es\n ... Fm\n ... Md\n ... No\n ... Lr\n ... Rf\n ... Db\n ... Sg\n ... Bh\n ... Hs\n ... Mt\n%}\n ]; \n if Z <= numel(r)\n radius = r(Z);\n else\n radius = default_r; % default radius\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/36836-vasplab/vasplab/atomic_radius.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603725, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6336846810242869}} {"text": "function [v_INTERP,ind_Start,ind_End] = FitzHugh_Nagumo_1d(dt_IBM,T_final)\n%function FitzHugh_Nagumo_1d(dt_IBM,T_final)\n\n%\n% This script solves the FitzHugh-Nagumo Equations in 1d, which are \n% a reduced order model of the more complicated Hodgkin-Huxley Equations. \n%\n% Author: Nick Battista\n% Created: 09/11/2015\n% University: UNC-CH\n%\n% Equations:\n% dv/dt = D*Laplacian(v) + v*(v-a)*(v-1) - w - I(t)\n% dw/dt = eps*(v-gamma*w)\n%\n% Inputs:\n% dt_IBM: time-step from immersed boundary code\n% T_final: final time for immersed boundary simulation\n%\n% Variables & Parameters:\n% v(x,t): membrane potential\n% w(x,t): blocking mechanism\n% D: diffusion rate of potential\n% a: threshold potential\n% gamma: resetting rate\n% eps: strength of blocking\n% I(t): initial condition for applied activation\n%\n\n\n%USER-INPUT FROM MODEL:\nnumPtsAlongTube = 78; % # of Lag. Muscle Pts Along Tube \nind_Start = 155; % first index for muscle between tube in spring count\nind_End = 232; % last index for muscle between tube in spring count\ndt_IBM = dt_IBM*2500; % scale time-info\nT_final_Ca = T_final; % Stays on time-scale of IBM\nT_final = T_final * 2500;% scale time-info\n\n\n% Save Movie? \nPLAY_MOVIE = 0; % (1 for YES, 0 for NO)\n\n% Parameters in model %\nD = 10.0; % Diffusion coefficient\na = 0.3; % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting)\ngamma = 1.0; % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired)\neps = 0.001; % Blocking strength (Note: eps = 0.001 is desired)\nI_mag = 0.05; % Activation strength\n\n% Discretization/Simulation Parameters %\nfactor = 4; % 4x the resolution of the FHN model than IBM for tube\nN = factor*numPtsAlongTube-1; % # of discretized points for FHN model (finer resolution than IBM mesh)\nL = 500; % Length of domain, [0,L]\ndx = L/N; % Spatial Step\nx = 0:dx:L; % Computational Domain\n\n% Temporal Parameters %\nNp = 10; % Set the number of pulses\npulse = T_final/Np; % determines the length of time between pulses.\nnumFHN = 10; % # that relates # of time-steps of FHN to IBM\ndt = dt_IBM / numFHN; % Time-step for FitzHugh-Nagumo (fraction of IBM time-step)\nNT = T_final / dt; % Total # of time-steps to be taken for FHN\nNT_IBM = T_final / dt_IBM; % Total # of time-steps for IBM\ni1 = 0.25;%0.475; % fraction of total length where current starts\ni2 = 0.3;%0.525; % fraction of total length where current ends\ndp = pulse/50; % Set the duration of the current pulse\npulse_time = 0; % pulse time is used to store the time that the next pulse of current will happen\nIIapp=zeros(1,N+1); % this vector holds the values of the applied current along the length of the neuron\ndptime = T_final/100; % This sets the length of time frames that are saved to make a movie.\n\n% Initialization %\nv = zeros(1,N+1);\nw = v;\nt=0;\nptime = 0; \nstore = 1; % counter for storing data to match time-steps from IBM\ntVec = 0:dt:T_final;\nNsteps = length(tVec);\nvStore = zeros(NT_IBM,N+1); vStore(store,:) = v;\nwStore = zeros(NT_IBM,N+1); wStore(store,:) = w;\nIIappStore=vStore;\nstore = store+1; % update storage counter\n\n\n% Compute Calcium-Dynamics a-priori for activation wave!\n% (returns Ca: free calcium ions, Caf: bound to filaments Ca-ions)\nfprintf(' --> Solving Calcium Dynamics Model\\n');\n[Ca,Caf] = Calcium_Dynamics(Nsteps,T_final_Ca);\nfprintf(' --> Finished calculating Calcium Dynamics\\n');\n\n\n\n%\n% **** % **** BEGIN SIMULATION! **** % **** %\n%\nfor i=2:Nsteps;\n \n % Update the time\n t = t+dt; \n \n % Give Laplacian\n DD_v_p = give_Me_Laplacian(v,dx); \n \n % Gives activation wave (either from prescribed or Calcium-Dynamics model)\n %[IIapp,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,IIapp);\n IIapp = Iapp_from_Calcium_Dynamics(i,i1,i2,N,Caf);\n \n % Update potential and blocking mechanism, using Forward Euler\n vN = v + dt * ( D*DD_v_p - v.*(v-a).*(v-1) - w + IIapp );\n wN = w + dt * ( eps*( v - gamma*w ) );\n \n % Update time-steps\n v = vN;\n w = wN;\n \n % Store time-step values\n if mod(i-1,numFHN) == 0\n vStore(store,:) = v;\n wStore(store,:) = w;\n IIappStore(store,:) = IIapp;\n store = store + 1;\n end\n \n % PLAY MOVIE?\n if PLAY_MOVIE == 1\n %This is used to determine if the current time step will be a frame in the movie\n if t > ptime,\n figure(1)\n plot(x, v);\n axis([0 L -0.5 1.5]);\n xlabel('Distance (x)');\n ylabel('Electropotenital (v)');\n ptime = ptime+dptime;\n fprintf('Time(s): %d\\n',t);\n pause(0.01);\n end\n end\n \nend %END TIME-STEPPING LOOP\n\n% Compute electro-potential at associated Lagrangian Pts.\nv_INTERP = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,vStore);\n%IIapp_INTERP = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,IIappStore);\n\n\n% TEST SOLUTION\n% pause();\n% x=1:1:78;\n% for i=1:10:length(v_INTERP(:,1))\n% plot(x,v_INTERP(i,:),'-'); \n% %plot(x,IIapp_INTERP(i,:),'-');\n% axis([0 79 -0.5 1.5]);\n% pause(0.01);\n% end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes the electro-potential, v(x,t), at the correct points\n% along the IBM's Lagrangian Structure\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [v_INTERP] = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,vStore)\n\n% v: row: electro-potential \n% factor: resolution of FHN:IBM \n% vStore: membrane potential along tube\n\nv_INTERP = zeros(length(vStore(:,1)),numPtsAlongTube);\n\nct = 1;\nfor j=1:length(vStore(1,:))\n if ( mod(j-1,factor) == 0 )\n v_INTERP(:,ct) = vStore(:,j);\n ct = ct+1;\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: the CALCIUM inspired injection function, Iapp = activation wave \n% for system, and returns the activation signal between i1 and i2 in\n% geometry along tube\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction IIapp = Iapp_from_Calcium_Dynamics(ith_step,i1,i2,N,Caf)\n\n % Resets activation to zero\n IIapp = zeros(1,N+1);\n \n % Activates the proper region based on Calcium-Dynamics\n for j=(floor(i1*N):floor(i2*N))\n coeff = 0.5; % Coefficient to scale activation wave accordingly\n IIapp(j) = coeff*Caf(ith_step); % Activation of bound Calcium to filaments\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: the injection function, Iapp = activation wave for system, and\n% returns both the activation as well as updated pulse_time\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [app,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,app)\n\n\n %Check to see if there should be a pulse\n if t > (pulse_time),\n \n % Sets pulsing region to current amplitude of I_mag x\\in[i1*N,i2*N]\n for j=(floor(i1*N):floor(i2*N)),\n app(j) = I_mag; \n end\n \n % Checks if the pulse is over & then resets pulse_time to the next pulse time.\n if t > (pulse_time+dp),\n pulse_time = pulse_time+pulse;\n end\n \n else\n \n % Resets to no activation\n app = zeros(1,N+1);\n \n end\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: gives Laplacian of the membrane potential, note: assumes\n% periodicity and uses the 2nd order central differencing operator.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction DD_v = give_Me_Laplacian(v,dx)\n\nNpts = length(v);\nDD_v = zeros(1,Npts);\n\nfor i=1:Npts\n if i==1\n %DD_v(i) = ( v(i+1) - 2*v(i) + v(end) ) / dx^2;\n DD_v(i) = ( v(i+1) - 2*v(i) + 0 ) / dx^2;\n elseif i == Npts\n %DD_v(i) = ( v(1) - 2*v(i) + v(i-1) ) / dx^2;\n DD_v(i) = ( 0 - 2*v(i) + v(i-1) ) / dx^2;\n else\n DD_v(i) = ( v(i+1) - 2*v(i) + v(i-1) ) /dx^2;\n end\n\nend\n\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Example_HeartTube/Electromechanical_Pumping_w_Ca_Dynamics/FitzHugh_Nagumo_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6336846570000764}} {"text": "%This Matlab script can be used to reproduce Figure 2.8 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Number of BS antennas\nM = 100;\n\n%Angular standard deviation in the local scattering model (in degrees)\nASDs = [10 30];\n\n%Set the nominal angle of the desired UE\nvarphiDesired = pi/6;\n\n%Set range of nominal angles of the interfering UE\nvarphiInterfererDegrees = -180:1:180;\nvarphiInterfererRadians = varphiInterfererDegrees*(pi/180);\n\n%Define the antenna spacing (in number of wavelengths)\nantennaSpacing = 1/2; %Half wavelength distance\n\n%Preallocate matrix for storing the simulation results\nvariance = zeros(length(varphiInterfererRadians),length(ASDs));\n\n\n%% Go through the range of ASDs\nfor n = 1:length(ASDs)\n\n %Output simulation progress\n disp([num2str(n) ' ASDs out of ' num2str(length(ASDs))]); \n \n %Compute spatial correlation matrix of the desired UE\n R1 = functionRlocalscattering(M,varphiDesired,ASDs(n),antennaSpacing);\n \n %Go through all angles of the interfering UE\n for r = 1:length(varphiInterfererRadians)\n \n %Compute spatial correlation matrix of the interfering UE\n R2 = functionRlocalscattering(M,varphiInterfererRadians(r),ASDs(n),antennaSpacing);\n \n %Compute variance of favorable propagation according to (2.19)\n variance(r,n) = real(trace(R1*R2)/(trace(R1)*trace(R2)));\n\n end\n \nend\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\n\nplot(varphiInterfererDegrees,variance(:,1),'r--','LineWidth',1);\nplot(varphiInterfererDegrees,variance(:,2),'b-.','LineWidth',1);\nplot(varphiInterfererDegrees,1/M*ones(length(varphiInterfererDegrees),1),'k-','LineWidth',1);\n\nxlabel('Angle of interfering UE [degree]');\nylabel('Variance in (2.19)');\nxlim([-180 180]);\n\nlegend('Gaussian, ASD 10^o','Gaussian, ASD 30^o','Uncorrelated','Location','NorthWest');\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section2_figure8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6336801007984075}} {"text": "function [sol, infos] = gsp_ml_rls_tv(G, xl, y, k, tau,lambda, A, At, param)\n%GSP_ML_RLS_TV Manifold Learning regularized least square with TV regularization\n% Usage: sol = gsp_ml_rls_tv(G, xl, y, k, tau,lambda);\n% sol = gsp_ml_rls_tv(G, xl, y, k, tau, lambda, A, At);\n% sol = gsp_ml_rls_tv(G, xl, y, k, tau, lambda, A, At, param);\n% [sol, infos] = gsp_ml_rls_tv(...)\n% \n% Input parameters:\n% G : Graph\n% xl : labeled points\n% y : labels\n% k : kernel\n% tau : regularization parameters\n% lambda : regularization parameters\n% A : Operator\n% At : Adoint operator\n% param : Optional parameters\n% Output parameters:\n% sol : solution of the problem (kernel coefficients)\n% infos : convergence info\n% \n% *param* is a structure of optional argument given to the solver\n% gradient_descent. Please see the function gradient descent for more\n% information. \n%\n% In *param*, you also have to set an upperbound for the operator A as\n% param.nu!\n%\n% This function solves the following problem:\n%\n% .. argmin_alpha || A (K alpha) - y ||_2^2 \n% + tau *alpha^T K alpha \n% + lambda || L K alpha ||_TVG\n%\n% If tau is set to zero, then the following problem is solved\n%\n% .. argmin_alpha alpha^T K alpha\n% + lambda || L K alpha ||_TVG\n% s. t. A (K alpha) = y\n%\n\n% Author: Nathanael Perraudin\n% Date : 8 decembre 2014\n\n\nif nargin<7\n A = @(x) x;\nend\n\n\nif nargin<8\n At = A;\nend\n\nif nargin<9\n param = struct;\nend\n\n\nif ~isfield(param, 'tol'), param.tol = 1e-6; end\nif ~isfield(param, 'nu'), param.nu = 1; end\nif ~isfield(param, 'verbose'), param.verbose = 1; end\n \n \n\nN = size(xl,2);\n\n% Evaluate the kernel on the data points\nK = gsp_rkhs_evaluate(k,xl);\nnu = norm(K);\n\nalpha_in = zeros(N,size(y,2));\n\nif ~isfield(G,'D');\n G = gsp_adj2vec(G);\nend\nif ~isfield(G,'lmax');\n G = gsp_estimate_lmax(G);\nend\n \nparamtv.verbose = param.verbose - 1;\nftv.eval = @(x) sum(lambda*gsp_norm_tv(G,K*x));\nftv.prox = @(x,T) gsp_prox_tv(x,lambda*T,G,paramtv);\n\n\nif tau >0\n \n fp.eval = @(x) tau * sum(gsp_norm_tik(K,x));\n fp.grad = @(x) 2*tau*K*x;\n\n ffid.eval = @(x) norm(A(K*x)-y,'fro')^2;\n ffid.grad = @(x) 2*K'*At(A(K*x)-y);\n \n ftot.grad = @(x) ffid.grad(x) + fp.grad(x);\n ftot.eval = @(x) ffid.eval(x) + fp.eval(x);\n\n\n param.gamma = 0.5/(tau*nu+nu^2*param.nu^2+lambda*nu*G.lmax);\n\n [sol,infos] = forward_backward(alpha_in, ftv, ftot, param);\nelse\n \n fp.eval = @(x) x'*K*x;\n fp.grad = @(x) 2*K*x;\n \n \n paramproj.A = @(x) A(K*x);\n paramproj.At = @(x) K'*At(x);\n paramproj.nu = nu^2*param.nu^2;\n paramproj.tight = 0;\n paramproj.verbose = param.verbose-1;\n paramproj.y = y;\n paramproj.maxit = 50;\n ffid.eval = @(x) eps;\n ffid.prox = @(x,T) proj_b2(x,T,paramproj);\n\n param.gamma = 0.5/(nu+lambda*nu*G.lmax);\n\n [sol,infos] = generalized_forward_backward(alpha_in, {ffid,ftv}, fp, param);\n\nend\n\n\n\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/graph_ml/gsp_ml_rls_tv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6336020131642093}} {"text": "function [] = ControlPanel()\n\n% initialize control variables\nLx = 200*10^-3; % billet size\nLy = 200*10^-3;\ndx = 01*10^-3;\ndy = 01*10^-3;\ndt = 0.001;\n\n% Temperature definitions\ninitial_Temperature = 510+273;\nleft_Temperature = 65+273;\nupper_Temperature = 65+273;\nright_Temperature = 65+273;\nbottom_Temperature = 65+273;\nBC_temperature = left_Temperature;\nnew_Temperature = BC_temperature;\nreference_Temperature = 200+273;\n\n% Secondary variables\nboolean = 0; \ntimeRequired = 0;\ntime = 26;\n\n% Material properties\nalpha = 6.584*10^-5; % Steel\nrho = 2700;\nCp = 900;\n\ncourant_Number = alpha*dt/(dx^2);\n\n% Define computational domain (Geometry)\n\n% storage parameters\nx_intervals = Lx/dx + 1;\ny_intervals = Ly/dy + 1;\n\n% Matrices\nT_old = zeros(x_intervals,y_intervals); % 2-D storage for previous time step\nT_new = zeros(x_intervals,y_intervals); % 2-D storage for current time step\n%T = zeros((time/dt),x_intervals,y_intervals); % Mega Temperature matrix to stroe in 2-D for each time step, hence 3-D\n\n% Initialize domain\nT_old = InitializeSolution(T_old,initial_Temperature,left_Temperature,upper_Temperature,right_Temperature,bottom_Temperature,x_intervals,y_intervals);\nT_boundary = zeros(1,time/dt);\n\n% formulation : EXPLICIT scheme\nfor time_index = 1:1:(time/dt)\n\n T_new = ExplicitScheme(T_old,alpha,dx,dy,dt,x_intervals,y_intervals); \n % Introduce the water bath dynaic BC factor\n new_Temperature = CalculatedBathAdjustedBoundaryTemperature(T_new,T_old,x_intervals,y_intervals,dt,rho,Cp,new_Temperature);\n boolean = ExitConditionEvaluation(T_new,reference_Temperature,x_intervals,y_intervals);\n \n if(boolean == 1 && timeRequired == 0)\n timeRequired = time_index;\n end\n \n T_boundary(time_index) = new_Temperature;\n \n T_old = ReInitializeSolution(T_new,new_Temperature,x_intervals,y_intervals);\n \nend\n\nT_plot = T_new';\nT_plotting = CalculatePlottingMatrix(T_plot,x_intervals,y_intervals); % Plotting matrix\n\n%Contour plot on the 2-D spatial domain\nT_constant = initial_Temperature:.001:max([initial_Temperature,left_Temperature,upper_Temperature,right_Temperature,bottom_Temperature]);\n[C,h] = contour(T_plotting,T_constant);\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/ControlPanel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857834, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6335926111696493}} {"text": "% THE DEMO PRESENTS AN ERROR PROPAGATION USING A MONTE-CARLO METHOD\n% The error in the positioning of the joints is propagated to an error\n% in the position of the end effector\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\n\nclose all\n\nM=1500; %number of particles\n\n%load arm parameters\nrobot=load_robot('ABB', 'IRB140');\n\n%standard deviation AT EACH JOINT\nsigmaq=0.017;%rad\n\n%find errors around this pose\nq=[pi/2 -pi/2 0 0 0 0]';\n\npuntos=[];\nfor i=1:M,\n qi = q + [normrnd(0, sigmaq, robot.DOF, 1)];\n T=directkinematic(robot, qi);\n puntos=[puntos; T(1,4) T(2,4) T(3,4)];\nend\n\n\nadjust_view(robot)\ndrawrobot3d(robot,q), hold on\nplot3(puntos(:,1),puntos(:,2), puntos(:,3),'r.')", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/more_demos/draw_errors_monte_carlo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6335799100114816}} {"text": "function [A,h] = build_A_h_3d(dphi,cert,phiGrad,transformatioinModel)\n% BUILD_A_H_LINEAR3D Builds the equation system A*p = h\n%\n% INPUT ARGUMENTS\n% dphi - Phase-difference\n% cert - Certainty\n% phiGrad - Phase gradient\n% transformationModel - Transformation model (translation or affine)\n%\n% OPTIONAL INPUT ARGUMENTS\n% N/A\n%\n% OUTPUT ARGUMENTS\n% A \t\t\t\t\t- A matrix\n% h \t\t\t\t\t- h vector\n%\n% See \"Phase-Based Multidimensional Volume Registration\" by Hemmendorf et al\n% or \"PHASE BASED VOLUME REGISTRATION USING CUDA\" by Eklund et al for a\n% detailed description of how the equation system is set up. Note that here\n% we use a differenct S(x)p then the one used in the papers. This is done\n% in order to be consistent with functions build_G_h_linear2d and\n% build_G_h_linear3d.\n\n% Copyright (c) 2012 Daniel Forsberg\n% danne.forsberg@outlook.com\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nsz = size(dphi(:,:,:,1));\n\ndphiX = vec(dphi(:,:,:,1));\ndphiY = vec(dphi(:,:,:,2));\ndphiZ = vec(dphi(:,:,:,3));\ncertX = vec(cert(:,:,:,1));\ncertY = vec(cert(:,:,:,2));\ncertZ = vec(cert(:,:,:,3));\nphiGradX = vec(phiGrad(:,:,:,1));\nphiGradY = vec(phiGrad(:,:,:,2));\nphiGradZ = vec(phiGrad(:,:,:,3));\n\nswitch transformatioinModel\n case 'translation'\n A = [ sum(certX.*phiGradX.^2), 0, 0; ...\n 0, sum(certY.*phiGradY.^2), 0; ...\n 0, 0, sum(certZ.*phiGradZ.^2)];\n h = [ sum(certX.*dphiX.*phiGradX); ...\n sum(certY.*dphiY.*phiGradY); ...\n sum(certZ.*dphiZ.*phiGradZ)];\n case {'rigid','affine'}\n [x,y,z] = meshgrid(1:sz(2),1:sz(1),1:sz(3));\n x = x - sz(2)/2 - 0.5;\n y = y - sz(1)/2 - 0.5;\n z = z - sz(3)/2 - 0.5;\n x = x(:);\n y = y(:);\n z = z(:);\n \n A = [ sum(certX.*phiGradX.^2.*x.^2), sum(certX.*phiGradX.^2.*x.*y), sum(certX.*phiGradX.^2.*x.*z) 0, 0, 0, 0, 0, 0, sum(certX.*phiGradX.^2.*x), 0, 0; ...\n 0, sum(certX.*phiGradX.^2.*y.^2), sum(certX.*phiGradX.^2.*y.*z) 0, 0, 0, 0, 0, 0, sum(certX.*phiGradX.^2.*y), 0, 0; ...\n 0, 0, sum(certX.*phiGradX.^2.*z.^2) 0, 0, 0, 0, 0, 0, sum(certX.*phiGradX.^2.*z), 0, 0; ...\n 0, 0, 0, sum(certY.*phiGradY.^2.*x.^2), sum(certY.*phiGradY.^2.*x.*y), sum(certY.*phiGradY.^2.*x.*z), 0, 0, 0, 0, sum(certY.*phiGradY.^2.*x), 0; ...\n 0, 0, 0, 0, sum(certY.*phiGradY.^2.*y.^2), sum(certY.*phiGradY.^2.*y.*z), 0, 0, 0, 0, sum(certY.*phiGradY.^2.*y), 0; ...\n 0, 0, 0, 0, 0, sum(certY.*phiGradY.^2.*z.^2), 0, 0, 0, 0, sum(certY.*phiGradY.^2.*z), 0; ...\n 0, 0, 0, 0, 0, 0, sum(certZ.*phiGradZ.^2.*x.^2), sum(certZ.*phiGradZ.^2.*x.*y), sum(certZ.*phiGradZ.^2.*x.*z), 0, 0, sum(certZ.*phiGradZ.^2.*x); ...\n 0, 0, 0, 0, 0, 0, 0, sum(certZ.*phiGradZ.^2.*y.^2), sum(certZ.*phiGradZ.^2.*y.*z), 0, 0, sum(certZ.*phiGradZ.^2.*y); ...\n 0, 0, 0, 0, 0, 0, 0, 0, sum(certZ.*phiGradZ.^2.*z.^2), 0, 0, sum(certZ.*phiGradZ.^2.*z); ...\n 0, 0, 0, 0, 0, 0, 0, 0, 0, sum(certX.*phiGradX.^2), 0, 0; ...\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, sum(certY.*phiGradY.^2), 0; ...\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, sum(certZ.*phiGradZ.^2)];\n \n h = [ sum(certX.*dphiX.*phiGradX.*x); ...\n sum(certX.*dphiX.*phiGradX.*y); ...\n sum(certX.*dphiX.*phiGradX.*z); ...\n sum(certY.*dphiY.*phiGradY.*x); ...\n sum(certY.*dphiY.*phiGradY.*y); ...\n sum(certY.*dphiY.*phiGradY.*z); ...\n sum(certZ.*dphiZ.*phiGradZ.*x); ...\n sum(certZ.*dphiZ.*phiGradZ.*y); ...\n sum(certZ.*dphiZ.*phiGradZ.*z); ...\n sum(certX.*dphiX.*phiGradX); ...\n sum(certY.*dphiY.*phiGradY); ...\n sum(certZ.*dphiZ.*phiGradZ)];\n \n A = A + transpose(A) - diag(diag(A));\nend\n", "meta": {"author": "fordanic", "repo": "image-registration", "sha": "36c23d5da1f035b07c66a04fe5bac20de1bd1c74", "save_path": "github-repos/MATLAB/fordanic-image-registration", "path": "github-repos/MATLAB/fordanic-image-registration/image-registration-36c23d5da1f035b07c66a04fe5bac20de1bd1c74/registration/phase/phase-difference-linear/build_A_h_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6335798817548476}} {"text": "function [num, den, gamma] = designIIR(phi, D, m0, h, M)\n\n% designIIR: design filters F_i(z) (as in Section III.B.)\n%\n% Usage: [num, den, gamma] = designIIR(phi, D, m0, h, M)\n%\n% INPUTS: \n% phi: input rational transfer functions\n% D: vector of fractional delays\n% m0: system delay tolerance\n% h: fast sampling interval\n% M: superresolution factor (integer)\n%\n% OUTPUTS: \n% gamma: the H infinity norm of the induced error system K\n% num: numerator vectors\n% den: denominator vectors\n%\n% filter F_i(z) will be an IIR filter with num{i} is the coefficients of\n% the numerator and den{i} is the coefficients of the denominator.\n%\n% See also: getF, demo\n\n% Get the ingeter and residual of the delays\nm = floor(D(:)/h);\nd = D(:) - m * h;\n\n% Get the digital system as in Prop. 1 and 2\nAd = getAd(phi, h, d);\nBd = getBd(phi, h, d);\nCd = getCd(phi, h, d);\nDd = zeros(size(Cd,1), size(Bd,2));\n\n% The Integer Delay Operator\nsysd = IntDelayOp([m0; m]);\n\n% Get the digital system as in Prop. 3 by taking into account the integer\n% delay operators\nsys = sminreal( sysd * ss(Ad, Bd, Cd, Dd, -1) ); % sminreal to reduce the system's dimension on the fly \n% sys = sysd * ss(Ad, Bd, Cd, Dd, -1);\n\n% Get the system P (see Fig. 6)\n[Ap, Bp, Cp, Dp, p, q] = getP(sys, M);\n\n% Convert P into analog, since hinfsyn works in analog domain\n[Ac, Bc, Cc, Dc] = Digital2Analog(Ap, Bp, Cp, Dp);\n\n% Design in continuous time\nP = pck(Ac, Bc, Cc, Dc);\n\nubd = 1;\nlbd = 0;\ninc = .0001;\n\n[F, g, gamma] = hinfsyn(P,p,q,lbd,ubd,inc);\n\n% Get the synthesis system F\n[Af, Bf, Cf, Df] = unpck(F);\n\n% Convert F back to digital domain\n[Af, Bf, Cf, Df] = Analog2Digital(Af, Bf, Cf, Df);\n\n% Convert to filter coefficients\n[num, den] = getF(Af, Bf, Cf, Df, M);\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/22472-hybrid-filter-banks-with-fractional-delays-minimax-design-and-applications-to-multichannel-sampling/HybridFBwFractionalDelays/designIIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6335173837874635}} {"text": "%KNNR Trainable Nearest Neighbor Regression\n%\n% Y = KNNR(X,K)\n% Y = X*KNNR([],K)\n% Y = X*KNNR(K)\n%\n% INPUT\n% X Regression dataset, used for training\n% K number of neighbors (default K=3)\n%\n% OUTPUT\n% Y k-nearest neighbor regression\n%\n% DESCRIPTION\n% Define a k-Nearest neighbor regression on dataset X.\n%\n% SEE ALSO (PRTools Guide)\n% LINEARR, TESTR, PLOTR\n\n% Copyright: D.M.J. Tax, D.M.J.Tax@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\nfunction y = knnr(varargin)\n\n mapname = 'KNN regression';\n argin = shiftargin(varargin,'scalar');\n argin = setdefaults(argin,[],3);\n \n if mapping_task(argin,'definition')\n \n y = define_mapping(argin,'untrained',mapname);\n \n\telseif mapping_task(argin,'training')\t\t\t% Train a mapping.\n\n\t\t[x,k] = deal(argin{:});\n [n,d] = size(x);\n W.x = +x;\n W.y = gettargets(x);\n W.k = k;\n y = prmapping(mfilename,'trained',W,1,d,1);\n y = setname(y,'k-nearest neighbor regression');\n \n else % Evaluation\n \n [x,v] = deal(argin{1:2});\n w = getdata(v);\n [n,d] = size(x);\n D = distm(+x,w.x);\n [sD,I] = sort(D,2);\n if n==1\n out = mean(w.y(I(:,1:w.k)));\n else\n out = mean(w.y(I(:,1:w.k)),2);\n end\n y = setdat(x,out);\n\n end\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/knnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6334790767068517}} {"text": "function value = r4_besk1 ( x )\n\n%*****************************************************************************80\n%\n%% R4_BESK1 evaluates the Bessel function K of order 1 of an R4 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the Bessel function K of order 1 of X.\n%\n persistent bk1cs\n persistent ntk1\n persistent xmax\n persistent xmin\n persistent xsml\n\n if ( isempty ( ntk1 ) )\n\n bk1cs = [ ...\n 0.0253002273389477705, ...\n -0.353155960776544876, ...\n -0.122611180822657148, ...\n -0.0069757238596398643, ...\n -0.0001730288957513052, ...\n -0.0000024334061415659, ...\n -0.0000000221338763073, ...\n -0.0000000001411488392, ...\n -0.0000000000006666901, ...\n -0.0000000000000024274, ...\n -0.0000000000000000070 ]';\n\n ntk1 = r4_inits ( bk1cs, 11, 0.1 * r4_mach ( 3 ) );\n xmin = exp ( max ( log ( r4_mach ( 1 ) ), ...\n - log ( r4_mach ( 2 ) ) ) + 0.01 );\n xsml = sqrt ( 4.0 * r4_mach ( 3 ) );\n xmax = - log ( r4_mach ( 1 ) );\n xmax = xmax - 0.5 * xmax * log ( xmax ) ...\n / ( xmax + 0.5 ) - 0.01;\n\n end\n\n if ( x <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BESK1 = Fatal error!\\n' );\n fprintf ( 1, ' X <= 0.\\n' );\n error ( 'R4_BESK1 = Fatal error!' )\n elseif ( x <= xsml )\n y = 0.0;\n value = log ( 0.5 * x ) * r4_besi1 ( x ) + ( 0.75 ...\n + r4_csevl ( 0.5 * y - 1.0, bk1cs, ntk1 ) ) / x;\n elseif ( x <= 2.0 )\n y = x * x;\n value = log ( 0.5 * x ) * r4_besi1 ( x ) + ( 0.75 ...\n + r4_csevl ( 0.5 * y - 1.0, bk1cs, ntk1 ) ) / x;\n elseif ( x <= xmax )\n value = exp ( - x ) * r4_besk1e ( x );\n else\n value = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_besk1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6334790707265077}} {"text": "function y = MVL(Ai, Bi, Aj, Bj, t)\n\n% MVL: compute the integral Mij(t) of equation (51)\n%\n% Usage: y = MVL(Ai, Bi, Aj, Bj, t)\n% \n% INPUTS:\n% Ai, Aj, Bi, Bj: matrices of the operators Phi_i(s) and Phi_j(s)\n% t: upper limit of the integral\n%\n% OUTPUT: \n% y = MVL(t) = int_0^t expm(tau*Ai)*Bi*Bj'*expm(tau*Aj')dtau\n%\n% SEE ALSO: reference [19]\n\nF = expm([-Ai Bi*Bj'; \n zeros( size(Aj',1), size(Ai,2) ) Aj'] * t );\n\ny = expm(Ai*t) * F( 1:size(Ai,1), (1+size(Ai,2)):end );", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22472-hybrid-filter-banks-with-fractional-delays-minimax-design-and-applications-to-multichannel-sampling/HybridFBwFractionalDelays/MVL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.633333877902504}} {"text": "\nfunction [Y1 h11]=derotated_dtcwt(I1,n,biot,Qshift)\n% X -> 2D real matrix/Image\n%\n% nlevels -> No. of levels of wavelet decomposition\n%\n% biort -> 'antonini' => Antonini 9,7 tap filters.\n% 'legall' => LeGall 5,3 tap filters.\n% 'near_sym_a' => Near-Symmetric 5,7 tap filters.\n% 'near_sym_b' => Near-Symmetric 13,19 tap filters.\n%\n% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters, \n% (only 6,6 non-zero taps).\n% 'qshift_a' => Q-shift 10,10 tap filters,\n% (with 10,10 non-zero taps, unlike qshift_06).\n% 'qshift_b' => Q-Shift 14,14 tap filters.\n% 'qshift_c' => Q-Shift 16,16 tap filters.\n% 'qshift_d' => Q-Shift 18,18 tap filters.\n% \n%\n% Y1 -> The real lowpass image from the final level\n% h11 -> A cell array containing the 6 complex highpass subimages\n% for each level.\n%clear all;\n%clc;\n[Y1,h1] = dtwavexfm2(I1,n,biot,Qshift);\n%[Y2,h2] = dtwavexfm2(I2,n,biot,Qshift);\n\nh11{n}=h1{n};\nfor k=n:-1:2\n for m=1:6\n xp=imresize(h1{k}(:,:,m),2);%\n argxp=angle(xp);\n argx=angle(h1{k-1}(:,:,m));\n argx=argx-2.*argxp;\n absx=abs(h1{k-1}(:,:,m));\n xa=absx.*cos(argx);\n xb=absx.*sin(argx);\n h11{k-1}(:,:,m)=complex(xa,xb);\n end\nend\n%figure;\n%cimage5(h11{1}(:,:,4));\n%figure;\n%cimage5(h1{1}(:,:,4));\n%figure;\n%cimage5(h11{2}(:,:,4));\n%figure;\n%cimage5(h1{2}(:,:,4));", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dtcwt_toolbox/dDTCWT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6333129094220405}} {"text": "%DEMO_REGRESSION_SPARSE2 Regression demo comparing different sparse\n% approximations with optimization of inducing\n% variables\n%\n% Description\n% A regression problem with one input variable and one output\n% variable with Gaussian noise. The output is assumed to be\n% realization of additive functions and Gaussian noise.\n% \n% For standard full GP demonstration, see for example\n% DEMO_REGRESSION1, and for detailed discussion, Rasmussen and\n% Williams (2006). For more sparse demonstrations including use\n% of compact support covariance functions see DEMO_REGRESSION2,\n% DEMO_MODELASSESMENT2, and DEMO_SPARSEAPPROX.\n% \n% In this demo, sparse approximations for the full GP model are\n% compared. We use\n% - FIC, fully independent conditional\n% - DTC, deterministic training conditional\n% - VAR, variational approach\n% For illustration purposes the hyperparameters from the full GP\n% are used for the sparse models and only the inducing variables\n% are optimised.\n% \n% For technical details, see Quinonero-Candela and Rasmussen\n% (2005) for the FIC and DTC models and Titsias (2009) for the\n% VAR model.\n% \n% We use a simple one dimensional data set to present the three\n% methods.\n% \n% See also DEMO_REGRESSION1, DEMO_REGRESSION2, DEMO_REGRESSION_SPARSE1\n%\n%\n% References:\n% \n% Quinonero-Candela, J. and Rasmussen, C. E. (2005). A Unifying\n% View of Sparse Approximate Gaussian Process Regression. Journal\n% of Machine Learning Research.\n% \n% Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian\n% Processes for Machine Learning. The MIT Press.\n% \n% Titsias, M. K. (2009). Variational Model Selection for Sparse\n% Gaussian Process Regression. Technical Report, University of\n% Manchester.\n\n% Copyright (c) 2010 Heikki Peura, Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\n% Set randomstream for reproducing same results\nprevstream=setrandstream();\n\n% Start by creating 1D data\nxx=linspace(1,10,901);\n\n% Choose a subset of data so that the data are less dense in the right end.\n% xt are the inputs and yt are the outputs, xstar are the values we want to\n% predict.\nx1=logspace(0,1,100);\nx1=round(x1*100)-99;\nx=xx(x1)';\ny=2*sin(4*x)+0.2*randn(size(x));\nxt=[1:0.01:14]';\n[n,nin] = size(x);\n\nfprintf('Full GP\\n')\n% Initialize full GP with a squared exponential component and set\n% priors for their parameters.\npl = prior_t('s2', 1);\npm = prior_logunif();\npn = prior_logunif();\n\ngpcfse = gpcf_sexp('lengthScale',0.5,'magnSigma2',1, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\nlik = lik_gaussian('sigma2', 0.1, 'sigma2_prior', pn);\n\ngp = gp_set('lik', lik, 'cf', gpcfse, 'jitterSigma2', 1e-6);\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-4,'TolX',1e-4);\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'opt',opt);\n\n[Eft_full, Varft_full] = gp_pred(gp, x, y, xt);\nVarft_full = Varft_full + gp.lik.sigma2;\n\nfigure\n% Blue crosses are the initial inducing input locations, red ones are\n% the optimised ones. Black circles represent the distance to the next\n% optimized location, with a dashed trendline.');\n\nsubplot(2,2,1);hold on;\nplot(xt,Eft_full,'k', 'LineWidth', 2)\nplot(xt,Eft_full-2.*sqrt(Varft_full),'--','Color',[0 0.5 0])\nplot(xt,Eft_full+2.*sqrt(Varft_full),'--','Color',[0 0.5 0])\nplot(x,y,'.', 'MarkerSize',7)\nylim([-3 3])\ntitle('FULL GP')\n\nfprintf('FIC GP\\n')\n% Run FIC approximation for the same data: choose the inducing\n% inputs Xu, then proceed with the inference with the optimized\n% parameters from the full GP: here, we optimize only the locations\n% of the inducing inputs for the FIC model.\nXu=round(10+90*rand(18,1))/10; % Random placement\n\n% Change type to FIC, add inducing inputs, and optimize only inducing inputs\ngp_fic = gp_set(gp, 'type','FIC','X_u',Xu,'infer_params','inducing');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-4,'TolX',1e-4);\n% Optimize with the scaled conjugate gradient method\ngp_fic=gp_optim(gp_fic,x,y,'opt',opt);\n\n[Eft_fic, Varft_fic] = gp_pred(gp_fic, x, y, xt);\nVarft_fic = Varft_fic + gp_fic.lik.sigma2;\n\n\nsubplot(2,2,2);hold on;\nh1=plot(xt,Eft_fic,'k', 'LineWidth', 2);\nh2=plot(xt,Eft_fic-2.*sqrt(Varft_fic),'--','Color',[0 0.5 0]);\nplot(xt,Eft_fic+2.*sqrt(Varft_fic),'--','Color',[0 0.5 0])\nh3=plot(x,y,'.', 'MarkerSize',7);\nh4=plot(Xu, -2.8, 'bx', 'MarkerSize', 5, 'LineWidth', 2);\nh5=plot(gp_fic.X_u, -3, 'rx', 'MarkerSize', 5, 'LineWidth', 2);\nlegend([h1 h2 h3 h4(1) h5(1)],'Ef','95% CI','Data','Initial X_u','Optimized X_u')\n% plot diff of sorted X_u and regress line for that\n%XuSorted=sort(gp_fic.X_u);\n%dXuSorted=diff(XuSorted);\n%bb=regress(dXuSorted,[ones(size(dXuSorted)) XuSorted(1:end-1)]);\n%plotbb=bb(1)+(min(XuSorted):0.1:max(XuSorted))*bb(2);\n%plot(XuSorted(1:end-1),dXuSorted,'ko');\n%plot(min(XuSorted):0.1:max(XuSorted),plotbb,'k--')\nylim([-3 3])\ntitle('FIC')\n\n\nfprintf('VAR GP\\n')\n% Run the VAR model similarly to the FIC model with the same\n% starting inducing inputs. The difference in the optimized results\n% is notable. The VAR model places the inducing inputs quite evenly\n% (slightly increasing as the data becomes more sparse), with\n% predictions closely matching the full GP model. The other two\n% sparse approximations yield less reliable results.\ngp_var = gp_set(gp,'type','VAR','X_u',Xu,'infer_params','inducing');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-4,'TolX',1e-4);\n% Optimize with the scaled conjugate gradient method\ngp_var=gp_optim(gp_var,x,y,'opt',opt);\n\n[Eft_var, Varft_var] = gp_pred(gp_var, x, y, xt);\nVarft_var = Varft_var + gp_var.lik.sigma2;\n\n\n\nsubplot(2,2,4);hold on\nplot(xt,Eft_var,'k', 'LineWidth', 2)\nplot(xt,Eft_var-2.*sqrt(Varft_var),'--','Color',[0 0.5 0])\nplot(xt,Eft_var+2.*sqrt(Varft_var),'--','Color',[0 0.5 0])\nplot(x,y,'.', 'MarkerSize',7)\nplot(gp_var.X_u, -3, 'rx', 'MarkerSize', 5, 'LineWidth', 2)\nplot(Xu, -2.8, 'bx', 'MarkerSize', 5, 'LineWidth', 2)\n% plot diff of sorted X_u and regress line for that\n%XuSorted=sort(gp_var.X_u);\n%dXuSorted=diff(XuSorted);\n%bb=regress(dXuSorted,[ones(size(dXuSorted)) XuSorted(1:end-1)]);\n%plotbb=bb(1)+(min(XuSorted):0.1:max(XuSorted))*bb(2);\n%plot(XuSorted(1:end-1),dXuSorted,'ko');\n%plot(min(XuSorted):0.1:max(XuSorted),plotbb,'k--')\nylim([-3 3])\ntitle('VAR')\n\n\nfprintf('DTC GP\\n')\n% Run the DTC model similarly to the FIC model with the same starting\n% inducing inputs. The difference in the optimized results is notable.\ngp_dtc = gp_set(gp,'type','DTC','X_u',Xu,'infer_params','inducing');\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-4,'TolX',1e-4);\n% Optimize with the scaled conjugate gradient method\ngp_dtc=gp_optim(gp_dtc,x,y,'opt',opt);\n\n[Eft_dtc, Varft_dtc] = gp_pred(gp_dtc, x, y, xt);\nVarft_dtc = Varft_dtc + gp_dtc.lik.sigma2;\n\nsubplot(2,2,3);hold on\nplot(xt,Eft_dtc,'k', 'LineWidth', 2)\nplot(xt,Eft_dtc-2.*sqrt(Varft_dtc),'--','Color',[0 0.5 0])\nplot(xt,Eft_dtc+2.*sqrt(Varft_dtc),'--','Color',[0 0.5 0])\nplot(x,y,'.', 'MarkerSize',7)\nplot(gp_dtc.X_u, -3, 'rx', 'MarkerSize', 5, 'LineWidth', 2)\nplot(Xu, -2.8, 'bx', 'MarkerSize', 5, 'LineWidth', 2)\n% plot diff of sorted X_u and regress line for that\n%XuSorted=sort(gp_dtc.X_u);\n%dXuSorted=diff(XuSorted);\n%bb=regress(dXuSorted,[ones(size(dXuSorted)) XuSorted(1:end-1)]);\n%plotbb=bb(1)+(min(XuSorted):0.1:max(XuSorted))*bb(2);\n%plot(XuSorted(1:end-1),dXuSorted,'ko');\n%plot(min(XuSorted):0.1:max(XuSorted),plotbb,'k--')\nylim([-3 3])\ntitle('DTC')\n\n% Set back initial random stream\nsetrandstream([],prevstream);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/demo_regression_sparse2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6332796072085111}} {"text": "function [ value_min, value_mean, value_max, value_var ] = ...\n tet_mesh_quality1 ( node_num, node_xyz, tetra_order, tetra_num, tetra_node )\n\n%*****************************************************************************80\n%\n%% TET_MESH_QUALITY1 returns a tet mesh quality factor.\n%\n% Discussion:\n%\n% The tet mesh quality measure is the minimum of the\n% corresponding tetrahedron quality measure, over all tetrahedrons in the\n% tet mesh.\n%\n% This routine is designed for an order-4 tet mesh. Order 10 tet meshes\n% may be input, but the extra nodes are ignored.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, double NODE_XYZ(3,NODE_NUM), the nodes.\n%\n% Input, integer TETRA_ORDER, the order of the tetrahedrons.\n%\n% Input, integer TETRA_NUM, the number of tetrahedrons.\n%\n% Input, integer TETRA_NODE(TETRA_ORDER,TETRA_NUM), the indices of the nodes\n% that make up the tetrahedrons.\n%\n% Output, double VALUE_MIN, VALUE_MEAN, VALUE_MAX, VALUE_VAR,\n% the minimum, mean, maximum and variance of the quality measure.\n%\n dim_num = 3;\n\n for tetra = 1 : tetra_num\n\n tetrahedron(1:dim_num,1:4) = node_xyz(1:dim_num,tetra_node(1:4,tetra));\n\n tetrahedron_quality(tetra) = tetrahedron_quality1_3d ( tetrahedron );\n\n end\n\n value_max = max ( tetrahedron_quality(1:tetra_num) );\n value_min = min ( tetrahedron_quality(1:tetra_num) );\n value_mean = mean ( tetrahedron_quality(1:tetra_num) );\n value_var = var ( tetrahedron_quality(1:tetra_num) );\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/tet_mesh/tet_mesh_quality1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6332796045769371}} {"text": "function [vertices, faces] = curveToMesh(curve, varargin)\n%CURVETOMESH Create a mesh surrounding a 3D curve\n%\n% [V, F] = curveToMesh(CURVE)\n% Computes the vertices and the faces of the mesh surrounding the\n% specified 3D curve.\n%\n% [V, F] = curveToMesh(CURVE, THICKNESS)\n% Specifies the thickness of the mesh (distance between mesh vertices and\n% curve vertices). Default is 0.5.\n%\n% [V, F] = curveToMesh(CURVE, THICKNESS, NCORNERS)\n% Also specifies the number of mesh vertices around each curve vertex.\n% Default is 8.\n%\n%\n% Example\n% % Creates a tubular mesh around a trefoil knot curve\n% t = linspace(0, 2*pi, 200)';\n% x = sin(t) + 2 * sin(2 * t);\n% y = cos(t) - 2 * cos(2 * t);\n% z = -sin(3 * t);\n% curve = [x, y, z];\n% [v2, f2] = curveToMesh(curve, .5, 16);\n% figure; \n% drawMesh(v2, f2);\n% axis equal; view(3);\n% axis([-4 4 -4 4 -2 2]);\n% \n% See also\n% meshes3d, torusMesh, surfToMesh\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2015-01-07, using Matlab 8.4.0.150421 (R2014b)\n% Copyright 2015 INRA - Cepia Software Platform.\n\nradius = .1;\nif nargin > 1\n radius = varargin{1};\nend\n\nnCorners = 8;\nif nargin > 2\n nCorners = varargin{2};\nend\n\nnNodes = size(curve, 1);\nnVerts = nNodes * nCorners;\n\nvertices = zeros(nVerts, 3);\n\n% create reference corners, that will be rotated and translated\nt = linspace(0, 2*pi, nCorners + 1)';\nt(end) = [];\nbaseCorners = radius * [cos(t) sin(t) zeros(size(t))];\n\nfor iNode = 1:nNodes\n % coordinate of current node\n node = curve(iNode, :);\n \n % compute local tangent vector\n iNext = mod(iNode, nNodes) + 1;\n tangentVector = normalizeVector3d(curve(iNext, :) - node);\n\n % convert to spherical coordinates\n [theta, phi, rho] = cart2sph2(tangentVector); %#ok\n \n % apply transformation to place corners around current node\n rotY = createRotationOy(theta);\n rotZ = createRotationOz(phi);\n trans = createTranslation3d(node);\n transformMatrix = trans * rotZ * rotY;\n corners = transformPoint3d(baseCorners, transformMatrix);\n \n % concatenate with other corners\n vertices( (1:nCorners) + (iNode - 1) * nCorners, :) = corners;\nend\n\n% indices of vertices\ninds = (1:nVerts)';\nadd1 = repmat([ones(nCorners-1, 1) ; 1-nCorners], nNodes, 1);\n\n% generate faces\nfaces = [inds ...\n mod(inds + add1 - 1, nVerts) + 1 ...\n mod(inds + nCorners + add1 - 1, nVerts) + 1 ...\n mod(inds + nCorners - 1, nVerts) + 1];\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/meshes3d/curveToMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6332795993137875}} {"text": "% Copyright (C) 2012 Quan Wang , \n% Signal Analysis and Machine Perception Laboratory, \n% Department of Electrical, Computer, and Systems Engineering, \n% Rensselaer Polytechnic Institute, Troy, NY 12180, USA\n% \n% You are free to use this software for academic purposes if you cite our paper: \n% Quan Wang, Kim L. Boyer, \n% The active geometric shape model: A new robust deformable shape model and its applications, \n% Computer Vision and Image Understanding, Volume 116, Issue 12, December 2012, Pages 1178-1194, \n% ISSN 1077-3142, 10.1016/j.cviu.2012.08.004. \n% \n% For commercial use, please contact the authors. \n\nfunction [xc yc a b phi]=fit_arb_ellipse_force(init,increment,threshold,bound,field_x,field_y,iter,show_fitness)\n\nx0=init(1);\ny0=init(2);\na0=init(3);\nb0=init(4);\nphi0=init(5);\nd_xc=increment(1);\nd_yc=increment(2);\nd_a=increment(3);\nd_b=increment(4);\nd_phi=increment(5);\nt_xc=threshold(1);\nt_yc=threshold(2);\nt_a=threshold(3);\nt_b=threshold(4);\nt_phi=threshold(5);\na_low=bound(1);\na_up=bound(2);\nb_low=bound(3);\nb_up=bound(4);\n\n%% Fit an arbitrary ellipse in the force filed. xc, yc, a, b and phi will be returned.\n% The parametric equations of the arbitrary ellipse:\n% x=xc+a*cos(theta)*cos(phi)-b*sin(theta)*sin(phi)\n% y=yc+a*cos(theta)*sin(phi)+b*sin(theta)*cos(phi)\n% x0, y0: initial position of center\n% a0, b0: initial semi-major and semi-minor axes\n% phi0: initial orientation\n% d_xc, d_yc: increment of xc and yc in each loop\n% d_a, d_b: increment of a and b in each loop\n% d_phi: increment of phi in each loop\n% t_xc, t_yc: threshold needed to update xc and yc\n% t_a, t_b: threshold needed to update a and b\n% t_phi: threshold needed to update phi\n% a_low, a_up: lower bound and upper bound of a\n% b_low, b_up: lower bound and upper bound of b\n% field_x: the x component of force field\n% field_y: the y component of force field\n% iter: number of iterations\n% show_fitness: a flag of whether to show the fitness function\n\n% note: m rows and n columns, but x is column and y is row here\n[m n]=size(field_x);\n\nxc=x0;\nyc=y0;\na=a0;\nb=b0;\nphi=phi0;\n\nfor it=1:iter\n [x,y,theta]=arb_ellipse_in_image(m,n,xc,yc,a,b,phi);\n N=max(size(x));\n \n %% torque along the ellpise about center\n torque_v=[0 0 0]; % the torque as a vector\n for i=1:max(size(theta))\n torque_v=torque_v+cross([x(i)-xc,y(i)-yc,0],...\n [field_x(y(i),x(i)),field_y(y(i),x(i)),0]);\n end\n torque=torque_v(3);\n torque=torque/N^2;\n if torque>t_phi\n phi=phi+d_phi;\n elseif torque<-t_phi\n phi=phi-d_phi;\n end\n \n %% F_around\n F_round=[0,0];\n for i=1:max(size(theta))\n F_round=F_round+[field_x(y(i),x(i)),field_y(y(i),x(i))];\n end\n F_round=F_round/max(size(theta));\n \n %% F_left, which is on the left quarter of the ellipse, and inward\n index = find( theta>pi*3/4 & thetapi*7/4 );\n F_right=0;\n for i=index\n F_right=F_right+dot([field_x(y(i),x(i)),field_y(y(i),x(i))],[-cos(phi),-sin(phi)]);\n end\n F_right=F_right/max(size(index));\n \n %% F_up, which is on the up quarter of the ellipse, and inward\n index = find( theta>pi/4 & thetapi*5/4 & thetat_xc\n xc=xc+d_xc;\n elseif F_left_right<-t_xc\n xc=xc-d_xc;\n end\n \n F_down_up=dot(F_round,[0,1]);\n if F_down_up>t_yc\n yc=yc+d_yc;\n elseif F_down_up<-t_yc\n yc=yc-d_yc;\n end\n \n %% update xc and yc again according to diagonal force\n F_diag1=dot(F_round,[0.7071,0.7071]);\n if F_diag1>t_xc+t_yc\n xc=xc+d_xc;\n yc=yc+d_yc;\n elseif F_diag1<-t_xc-t_yc\n xc=xc-d_xc;\n yc=yc-d_yc;\n end\n \n F_diag2=dot(F_round,[-0.7071,0.7071]);\n if F_diag2>t_xc+t_yc\n xc=xc-d_xc;\n yc=yc+d_yc;\n elseif F_diag2<-t_xc-t_yc\n xc=xc+d_xc;\n yc=yc-d_yc;\n end\n \n %% update a and b\n \n if F_left+F_right>t_a\n a=a-d_a;\n elseif F_left+F_right<-t_a\n a=a+d_a;\n end\n \n if F_up+F_down>t_b\n b=b-d_b;\n elseif F_up+F_down<-t_b\n b=b+d_b;\n end\n \n if b>a\n temp=a;a=b;b=temp;\n phi=mod(phi+pi/2,pi);\n end\n \n %% restrict a and b using lower and upper bounds\n if a>a_up\n a=a_up;\n end\n if ab_up\n b=b_up;\n end\n if b0\n milags(li) = mutualinformationx(pow1(lagz(li)+1:end,:),pow2(1:end-lagz(li),:),30);\n end\nend\n\nfigure\nplot(1000*lagz/(1/mean(diff(time))),milags)\nxlabel([ electrodes4mi{1} ' leads ' electrodes4mi{2} ' ... Lag (ms) ... ' electrodes4mi{2} ' leads ' electrodes4mi{1} ]), ylabel('mutual information (bits)')\nset(gca,'xlim',[-onecycle onecycle])\n\n%% end.\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/chapter29.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6330718083407875}} {"text": "%% Dynamic Matrix Control Tutorial\n% Dynamic Matrix Control (DMC) was the first Model Predictive Control (MPC)\n% algorithm introduced in early 1980s. Nowadays, DMC is available in almost\n% all commercial industrial distributed control systems and process\n% simulation software packages. This tutorial intends to explain the\n% features of DMC using the dmc function developed by the author.\n\n%% Example: A Water Heater\n% Consider a water heater as shown in the following figure, where the cold\n% water is heated by means of a gas burner. The aim of DMC is by\n% manipulating valve to control the gas flow so that the outlet temperature\n% is at desired level.\n%%\n% \n% <>\n% \n\n%% The Step Response Model\n% The DMC algorithm works with a step response model. The first step to\n% design a DMC controller is to perform a step test on the plant to\n% generate a step response model. The step response of the water heater is\n% obtained through such a test and given as follows:\np.sr = [0;0;0.271;0.498;0.687;0.845;0.977;1.087;1.179;1.256;...\n 1.320;1.374;1.419;1.456;1.487;1.513;1.535;1.553;1.565;1.581;...\n 1.592;1.600;1.608;1.614;1.619;1.632;1.627;1.630;1.633;1.635];\n\n% The response is converged after 30 steps.\n\n%% DMC without Setpoint Prediction\n% Setup the DMC\nN=120; % Total simulation length (samples)\np.p=10; % Prediction horizon\np.m=5; % Moving horizon\np.la=1; % Control weight\n% Reference (setpoint)\nR=[ones(30,1);zeros(30,1);ones(30,1);zeros(30,1)];\np.y=0; % Initial output\np.v=[]; % empty past input to indicate initialization\n% buffer of input to cope with time delay\nu=zeros(3,1);\n% Initialization of variables for results\nY=zeros(N,1);\nU=zeros(N,1);\n% DMC Simulation\nfor k=1:120\n p.a=0;\n p.r=R(k); % DMC only knows current setpoint\n if k>60 % change smoothing factor for second half simulation\n p.a=0.7;\n end\n p=dmc(p);\n Y(k)=p.y;\n U(k)=p.u;\n u=[u(2:3);p.u];\n p.y=0.8351*p.y+0.2713*u(1); % actual plant output \nend\n% DMC results\nsubplot(211)\nplot(1:N,Y,'b-',1:N,R,'r--',[60 60],[-0.5 1.5],':','linewidth',2)\ntitle('solid: output, dashed: reference')\ntext(35,1,'\\alpha=0')\ntext(95,1,'\\alpha=0.7')\naxis([0 120 -0.5 1.5])\nsubplot(212)\n[xx,yy]=stairs(1:N,U);\nplot(xx,yy,'-',[60 60],[-0.5 1.5],':','linewidth',2)\naxis([0 120 -0.5 1.5])\ntitle('input, \\lambda=1')\nxlabel('time, min')\n\n%% DMC with Setpoint Prediction\n% Setup the DMC\nN=120; % Total simulation length (samples)\np.p=10; % Prediction horizon\np.m=5; % Moving horizon\np.la=1; % Control weight\n% Reference (setpoint)\nR=[ones(30,1);zeros(30,1);ones(30,1);zeros(30,1)];\np.y=0; % Initial output\np.v=[]; % empty past input to indicate initialization\n% buffer of input to cope with time delay\nu=zeros(3,1);\n% Initialization of variables for results\nY=zeros(N,1);\nU=zeros(N,1);\n% DMC Simulation\nfor k=1:120\n p.a=0;\n p.r=R(k:min(N,k+p.p)); % DMC knows future setpoint\n if k>60 % change smoothing factor for second half simulation\n p.a=0.7;\n end\n p=dmc(p);\n Y(k)=p.y;\n U(k)=p.u;\n u=[u(2:3);p.u];\n p.y=0.8351*p.y+0.2713*u(1); % actual plant output \nend\n% DMC results\nsubplot(211)\nplot(1:N,Y,'b-',1:N,R,'r--',[60 60],[-0.5 1.5],':','linewidth',2)\ntitle('solid: output, dashed: reference')\ntext(35,1,'\\alpha=0')\ntext(95,1,'\\alpha=0.7')\naxis([0 120 -0.5 1.5])\nsubplot(212)\n[xx,yy]=stairs(1:N,U);\nplot(xx,yy,'-',[60 60],[-0.5 1.5],':','linewidth',2)\naxis([0 120 -0.5 1.5])\ntitle('input, \\lambda=1')\nxlabel('time, min')\n\n%% DMC with Different Control Weight\n% Setup the DMC\nN=120; % Total simulation length (samples)\np.p=10; % Prediction horizon\np.m=5; % Moving horizon\np.la=0.1; % Control weight\n% Reference (setpoint)\nR=[ones(30,1);zeros(30,1);ones(30,1);zeros(30,1)];\np.y=0; % Initial output\np.v=[]; % empty past input to indicate initialization\n% buffer of input to cope with time delay\nu=zeros(3,1);\n% Initialization of variables for results\nY=zeros(N,1);\nU=zeros(N,1);\n% DMC Simulation\nfor k=1:120\n p.a=0;\n p.r=R(k:min(N,k+p.p)); % DMC knows future setpoint\n if k>60 % change smoothing factor for second half simulation\n p.a=0.7;\n end\n p=dmc(p);\n Y(k)=p.y;\n U(k)=p.u;\n u=[u(2:3);p.u];\n p.y=0.8351*p.y+0.2713*u(1); % actual plant output \nend\n% DMC results\nsubplot(211)\nplot(1:N,Y,'b-',1:N,R,'r--',[60 60],[-0.5 1.5],':','linewidth',2)\ntitle('solid: output, dashed: reference')\ntext(35,1,'\\alpha=0')\ntext(95,1,'\\alpha=0.7')\naxis([0 120 -0.5 1.5])\nsubplot(212)\n[xx,yy]=stairs(1:N,U);\nplot(xx,yy,'-',[60 60],[-0.5 1.5],':','linewidth',2)\naxis([0 120 -1 2])\ntitle('input, \\lambda=0.1')\nxlabel('time, min')\n\n%% Reference\n% Camacho, E.F. and Bordons, C., Model Predictive Control, Springer-Verlag,\n% 1999.\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/19479-mpc-tutorial-i-dynamic-matrix-control/dmctutorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.633071806413127}} {"text": "function [R,L_lb,L_cpd] = rankest(T,options)\n%RANKEST Estimate rank.\n% rankest(T) plots an L-curve of number of rank-one terms in a canonical\n% polyadic decomposition. The x-axis corresponds to the number of\n% rank-one terms, and the y-axis corresponds to the relative error of the\n% CPD in that many rank-one terms. Additionally, the corner R of the\n% resulting L-curve is estimated.\n%\n% R = rankest(T) does not plot anything and instead returns the number of\n% rank-one terms R corresponding to the corner of the L-curve.\n%\n% [R,L_lb,L_cpd] = rankest(T) also returns the L-curve ranks L_lb(:,1)\n% and L_cpd(:,1) and the corresponding lower bound on the truncation\n% error L_lb(:,2) and relative error of the CPD approximation L_cpd(:,2),\n% respectively.\n%\n% rankest(T,options) may be used to set the following options:\n%\n% options.MaxR = - Maximum number of rank-one terms to try.\n% numel(T)/max(size_tens)\n% options.MinR = 1 - Minimum number of rank-one terms to try.\n% options.MinRelErr = 1e-2 - Determines an upper threshold for the\n% number of rank-one terms R to try.\n% options.Solver = @cpd - The solver used to compute the CPD for\n% each number of rank-one terms R. Called\n% as options.Solver(T,R, ...\n% options.SolverOptions), where\n% options.SolverOptions is an options\n% structure passed to the solver.\n% options.XMultiplier = 1 - The importance of the number of rank-one\n% terms in determining the L-curve corner,\n% relative to the importance of the\n% relative error of the approximation.\n%\n% See also mlrankest.\n\n% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)\n% Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)\n% Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)\n%\n% References:\n% [1] J.L. Castellanos, S. Gomez, V. Guerra, \"The triangle method for\n% finding the corner of the L-curve,\" Applied Numerical Mathematics,\n% Vol. 43, No. 4, 2002, pp. 359-373.\n\n% Incomplete/sparse tensors not supported yet.\nT = fmt(T,true);\nif isstruct(T), size_tens = T.size;\nelse size_tens = size(T); end\n\n% Check the options structure.\nif nargin < 2, options = struct; end\nif ~isfield(options,'MaxR')\n options.MaxR = prod(size_tens)/max(size_tens);\nend\nif ~isfield(options,'MinR'), options.MinR = 1; end\nif ~isfield(options,'MinRelErr'), options.MinRelErr = 1e-2; end\nif ~isfield(options,'Solver'), options.Solver = @cpd; end\nif ~isfield(options,'SolverOptions'), options.SolverOptions = struct; end\nif ~isfield(options.SolverOptions,'Compression')\n options.SolverOptions.Compression = false;\nend\nif ~isfield(options.SolverOptions,'Display')\n options.SolverOptions.Display = false;\nend\nif ~isfield(options,'XMultiplier'), options.XMultiplier = 1; end\n\n% Compute lower bound on truncation error.\nfrobT = frob(T);\nif ~isstruct(T)\n [~,~,sv] = mlsvd(T);\n Rmax = max(cellfun(@length,sv))-1;\n lb = max(cell2mat(cellfun( ...\n @(s)[sqrt(flipud(cumsum(flipud(s(:).^2)))).'/frobT ...\n zeros(1,Rmax+1-length(s))],sv(:),'UniformOutput',false)));\n lb = lb(2:end);\nelse\n Rmax = 0;\n lb = [];\nend\n\n% Determine the range of rank-one terms to test.\nif ~isempty(lb)\n R = find(lb(options.MinR:end)<=options.MinRelErr,1,'first')+ ...\n options.MinR-1;\n if isempty(R), R = max(options.MinR,Rmax+1); end\n R = R:options.MaxR;\nelse\n R = 1:options.MaxR;\nend\n\n% Compute the relative error for each number of rank-one terms R(r).\nrelerr = zeros(1,length(R));\nfor r = 1:length(R)\n \n % Compute the CPD in R rank-one terms.\n [U,output] = options.Solver(T,R(r),options.SolverOptions);\n if isfield(output,'Refinement') && ...\n isfield(output.Refinement,'fval')\n relerr(r) = sqrt(2*output.Refinement.fval(end))/frobT;\n elseif isfield(output,'Algorithm') && ...\n isfield(output.Algorithm,'fval')\n relerr(r) = sqrt(2*output.Algorithm.fval(end))/frobT;\n elseif isfield(output,'fval')\n relerr(r) = sqrt(2*output.fval(end))/frobT;\n else\n relerr(r) = frob(cpdres(T,U))/frobT;\n end\n \n % Stop is options.MinRelErr has been reached.\n if relerr(r) <= options.MinRelErr\n R = R(1:r);\n relerr = relerr(1:r);\n break;\n end\n \n % Update the plot.\n if r > 1 && r < length(R) && nargout == 0, Lcurve(true); end\n \nend\n\n% Compute L-curve corner using the triangle method [1].\nlogx = options.XMultiplier*R(:);\nlogy = log10(relerr(:));\nif R(1) ~= 1 && ~isempty(lb)\n logx = [options.XMultiplier;logx];\n logy = [log10(lb(1));logy];\nend\nab = cat(3,bsxfun(@minus,logx,logx.'),bsxfun(@minus,logy,logy.'));\nac = cat(3,logx(end)-logx.',logy(end)-logy.');\narea = bsxfun(@times,ab(:,:,1),ac(:,:,2)) - ...\n bsxfun(@times,ab(:,:,2),ac(:,:,1));\ncosa = bsxfun(@times,ab(:,:,1),ac(:,:,1)) + ...\n bsxfun(@times,ab(:,:,2),ac(:,:,2));\ncosa = bsxfun(@rdivide,cosa./sqrt(ab(:,:,1).^2+ab(:,:,2).^2), ...\n sqrt(ac(:,:,1).^2+ac(:,:,2).^2));\ncosa(area >= 0 | tril(true(size(cosa))) | cosa <= cos(7*pi/8)) = -1;\n[a,opt] = max(max(cosa(:,2:end)));\nif isempty(a), opt = 1; end\nif a == -1, opt = size(cosa,2)-1; end\n\n% Display output.\nL_lb = [(1:Rmax).' lb(:)];\nL_cpd = [R(:) relerr(:)];\nif nargout == 0, Lcurve(false); end\nR = R(opt);\n\nfunction Lcurve(update)\n if R(r) <= 1, return; end\n style = {'Marker','+','MarkerSize',2.5};\n if ~update\n semilogy(R(opt),relerr(opt),'rs','LineStyle','none'); hold on;\n end\n semilogy(R(1:length(relerr)),relerr,'r',style{:}); hold on;\n semilogy(1:length(lb),lb,style{:});\n semilogy([1 R(r)],options.MinRelErr*[1 1],'k:');\n text(1,options.MinRelErr,'MinRelErr','VerticalAlignment','Top');\n hold off;\n ylim([min(options.MinRelErr/(10^0.5),min(relerr(1:r))) lb(1)]);\n xlim([1 R(r)]);\n ylabel('frob(cpdres(T,U))/frob(T)'); xlabel('R');\n xt = get(gca,'XTick'); set(gca,'XTick',xt(mod(xt,1) == 0));\n if update\n if ~isempty(lb)\n legend(['CPD error (trying R = ' int2str(R(r+1)) '...)'], ...\n 'Lower bound on error','Location','NE');\n else\n legend(['CPD error (trying R = ' int2str(R(r+1)) '...)'], ...\n 'Location','NE');\n end\n else\n if ~isempty(lb)\n legend(['L-curve corner at R = ' int2str(R(opt))], ...\n 'CPD error','Lower bound on error','Location','NE');\n else\n legend(['L-curve corner at R = ' int2str(R(opt))], ...\n 'CPD error','Location','NE');\n end\n end\n set(datacursormode(gcf),'UpdateFcn',@datacursor);\n drawnow;\nend\n\nfunction txt = datacursor(~,event_obj)\n pos = get(event_obj,'Position');\n txt = {['R: ' int2str(pos(1))], ...\n ['relative error: ' num2str(pos(2))]};\nend\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+tensorlab/rankest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6330634882623296}} {"text": "function Serr=specerr(S,J,err,trialave,numsp)\n% Function to compute lower and upper confidence intervals on the spectrum \n% Usage: Serr=specerr(S,J,err,trialave,numsp)\n% Outputs: Serr (Serr(1,...) - lower confidence level, Serr(2,...) upper confidence level)\n%\n% Inputs:\n% S - spectrum\n% J - tapered fourier transforms \n% err - [errtype p] (errtype=1 - asymptotic estimates; errchk=2 - Jackknife estimates; \n% p - p value for error estimates)\n% trialave - 0: no averaging over trials/channels\n% 1 : perform trial averaging\n% numsp - number of spikes in each channel. specify only when finite\n% size correction required (and of course, only for point\n% process data)\n%\n% Outputs:\n% Serr - error estimates. Only for err(1)>=1. If err=[1 p] or [2 p] Serr(...,1) and Serr(...,2)\n% contain the lower and upper error bars with the specified method. \nif nargin < 4; error('Need at least 4 input arguments'); end;\nif err(1)==0; error('Need err=[1 p] or [2 p] for error bar calculation. Make sure you are not asking for the output of Serr'); end;\n[nf,K,C]=size(J);\nerrchk=err(1);\np=err(2);\npp=1-p/2;\nqq=1-pp;\n\nif trialave\n dim=K*C;\n C=1;\n dof=2*dim;\n if nargin==5; dof = fix(1/(1/dof + 1/(2*sum(numsp)))); end\n J=reshape(J,nf,dim);\nelse\n dim=K;\n dof=2*dim*ones(1,C);\n for ch=1:C;\n if nargin==5; dof(ch) = fix(1/(1/dof + 1/(2*numsp(ch)))); end \n end;\nend;\nSerr=zeros(2,nf,C);\nif errchk==1;\n Qp=chi2inv(pp,dof);\n Qq=chi2inv(qq,dof);\n Serr(1,:,:)=dof(ones(nf,1),:).*S./Qp(ones(nf,1),:);\n Serr(2,:,:)=dof(ones(nf,1),:).*S./Qq(ones(nf,1),:);\nelseif errchk==2;\n tcrit=tinv(pp,dim-1);\n for k=1:dim;\n indices=setdiff(1:dim,k);\n Jjk=J(:,indices,:); % 1-drop projection\n eJjk=squeeze(sum(Jjk.*conj(Jjk),2));\n Sjk(k,:,:)=eJjk/(dim-1); % 1-drop spectrum\n end;\n sigma=sqrt(dim-1)*squeeze(std(log(Sjk),1,1)); if C==1; sigma=sigma'; end; \n conf=repmat(tcrit,nf,C).*sigma;\n conf=squeeze(conf); \n Serr(1,:,:)=S.*exp(-conf); Serr(2,:,:)=S.*exp(conf);\nend;\nSerr=squeeze(Serr);", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/spectral_analysis/helper/specerr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6330634882623296}} {"text": "function ccl_sparse_test ( )\n\n%*****************************************************************************80\n%\n%% CCL_SPARSE_TEST uses CCL to build a sparse grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Local parameters:\n%\n% Local, integer D, the spatial dimension.\n%\n% Local, integer MAXK, the maximum level to check.\n%\n d = 10;\n maxk = 7;\n func = 'prod( exp(-(x/2).^2/2)/2/sqrt(2*pi), 2)';\n trueval = fu_integral ( d );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CCL_SPARSE_TEST:\\n' );\n fprintf ( 1, ' CCL sparse grid:\\n' );\n fprintf ( 1, ' Clenshaw-Curtis Linear sparse grid.\\n' );\n fprintf ( 1, ' Exact integral is %g\\n', trueval );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' D Level Nodes SG error MC error\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 1 : maxk\n%\n% Compute the sparse grid estimate.\n%\n [ x, w ] = nwspgr ( 'ccl', d, k );\n fx = eval ( func );\n SGappr = w' * fx;\n SGerror = sqrt ( ( SGappr - trueval ).^2 ) / trueval;\n%\n% Average 1000 Monte Carlo estimates.\n%\n numnodes = length ( w );\n sim = zeros ( 1000, 1 );\n for r = 1 : 1000\n x = rand ( numnodes, d );\n fx = eval ( func );\n sim(r) = mean ( fx );\n end\n simerror = sqrt ( mean ( ( sim - trueval ).^2 ) ) / trueval;\n\n fprintf( ' %2d %2d %6d %10.5g %10.5g\\n', ...\n d, k, numnodes, SGerror, simerror )\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/ccl_sparse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6330634776151345}} {"text": "function a = gk323_inverse ( n )\n\n%*****************************************************************************80\n%\n%% GK323_INVERSE returns the inverse of the GK323 matrix.\n%\n% Properties:\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i == j )\n if ( i == 1 | i == n )\n a(i,j) = - 0.5 * ( n - 2 ) / ( n - 1 );\n else\n a(i,j) = - 1.0;\n end\n elseif ( i == j+1 | i == j-1 )\n a(i,j) = 0.5;\n elseif ( i == 1 & j == n )\n a(i,j) = 0.5 / ( n - 1 );\n elseif ( i == n & j == 1 )\n a(i,j) = 0.5 / ( n - 1 );\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/gk323_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.633063470356903}} {"text": "function [zPred,PzPred,otherInfo]=sqrtKalmanMeasPred(xPred,SPred,H)\n%%SQRTKALMANMEASPRED Perform the measurement prediction part of the\n% measurement update step of the square-root Kalman filter. The\n% function sqrtKalmanUpdateWithPred can be used to complete the\n% measurement update. Separating the measurement prediction step\n% from the rest of the update step can make the creation of\n% multiple measurement association hypotheses from a single\n% target prediction more efficient. The full measurement update\n% function is sqrtKalmanUpdate.\n%\n%INPUTS: xPred The xDimXnumComp set of numComp predicted target states.\n% SPred The xDimXxDimXnumComp lower-triangular predicted square-root\n% state covariance matrices.\n% H The zDimXxDim measurement matrix. The measurement is modeled\n% as z=H*x+noise and the model is the same for all components\n% given in xPred and SPred.\n%\n%OUTPUTS: zPred The zDimXnumComp measurement predictions from the filter.\n% PzPred The zDimXzDimXnumComp covariance matrix associated with\n% zPred.\n% otherInfo A structure containing members of intermediate results of\n% this function that can be passed to sqrtKalmanUpdate\n% when updating with a measurement.\n%\n%The mathematics behind the specific square root implementation used here\n%are described in Appendix G of [1].\n%\n%EXAMPLE:\n%With this example, we demonstrate that one gets the same result using\n%KalmanUpdate versus calling sqrtKalmanMeasPred and then\n%sqrtKalmanUpdateWithPred. \n% xPred=[1e3;-2e3;100;200];\n% SPred=chol([28, 3.5, 6, 8.5;\n% 3.5, 23, 8.5, 11;\n% 6, 8.5, 18, 13.5;\n% 8.5, 11, 13.5, 13],'lower');\n% z=1e3*[-5.498856156296510;\n% 1.199241491470584];\n% SR=eye(2);\n% H=[0, 4, 9, 8;\n% 6, 3, 0, 6];\n% \n% %The update in one step.\n% [xUpdate,SUpdate,innov,Szz,W]=sqrtKalmanUpdate(xPred,SPred,z,SR,H);\n% %The update in two steps.\n% [zPred,PzPred,otherInfo]=sqrtKalmanMeasPred(xPred,SPred,H);\n% [xUpdate1,SUpdate1,innov1,Szz1,W1]=sqrtKalmanUpdateWithPred(z,SR,zPred,otherInfo);\n% %One will see that the one and two step updates agree.\n% max(abs([xUpdate1-xUpdate;SUpdate1(:)-SUpdate(:);innov1(:)-innov;Szz1(:)-Szz(:);W1(:)-W(:)]))\n%\n%REFERENCES\n%[1] David F. Crouse , \"Basic tracking using nonlinear 3D monostatic and\n% bistatic measurements,\" IEEE Aerospace and Electronic Systems \n% Magazine, vol. 29, no. 8, Part II, pp. 4-53, Aug. 2014.\n%\n%June 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nzDim=size(H,1);\nxDim=size(H,2);\nnumComp=size(xPred,2);\n\nzPred=H*xPred;\n\nPzPred=zeros(zDim,zDim,numComp);\nPxz=zeros(xDim,zDim,numComp);\nfor k=1:numComp\n temp=H*SPred(:,:,k);\n PzPred(:,:,k)=temp*temp';\n\n Pxz(:,:,k)=SPred(:,:,k)*SPred(:,:,k)'*H';\n %Pxz is not needed for the measurement prediction, but we compute it\n %here, so that it need not be recomputed again and again if\n %sqrtKalmanUpdateWithPred is called for multiple measurements.\nend\notherInfo.xPred=xPred;\notherInfo.SPred=SPred;\notherInfo.Pxz=Pxz;\notherInfo.H=H;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Measurement_Update/Update_Parts/Filter_Measurement_Prediction/sqrtKalmanMeasPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6330634597097073}} {"text": "function ns3de_test02 ( )\n\n%*****************************************************************************80\n%\n%% NS3DE_TEST02 samples the residual at the initial time.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/navier_stokes_3d_exact/ns3de_test02.m\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n a = pi / 4.0;\n d = pi / 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NS3DE_TEST02\\n' );\n fprintf ( 1, ' Sample the Navier-Stokes residuals' );\n fprintf ( 1, ' at the initial time T = 0, using a region that is \\n' );\n fprintf ( 1, ' the cube centered at (0,0,0) with \"radius\" 1.0,\\n' );\n fprintf ( 1, ' Parameter A = %g\\n', a );\n fprintf ( 1, ' Parameter D = %g\\n', d );\n\n n = 1000;\n x = 2.0 * rand ( n, 1 ) - 1.0;\n y = 2.0 * rand ( n, 1 ) - 1.0;\n z = 2.0 * rand ( n, 1 ) - 1.0;\n t = 0.0;\n\n [ ur, vr, wr, pr ] = resid_ethier ( a, d, n, x, y, z, t );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Minimum Maximum\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ur: %14.6g %14.6g\\n', min ( abs ( ur ) ), max ( abs ( ur ) ) );\n fprintf ( 1, ' Vr: %14.6g %14.6g\\n', min ( abs ( vr ) ), max ( abs ( vr ) ) );\n fprintf ( 1, ' Wr: %14.6g %14.6g\\n', min ( abs ( wr ) ), max ( abs ( wr ) ) );\n fprintf ( 1, ' Pr: %14.6g %14.6g\\n', min ( abs ( pr ) ), max ( abs ( pr ) ) );\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/navier_stokes_3d_exact/ns3de_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6330466892929549}} {"text": "function [h0, h1] = dfilters(fname, type)\n% DFILTERS\tGenerate directional 2D filters\n%\n%\t[h0, h1] = dfilters(fname, type)\n%\n% Input:\n%\tfname:\tFilter name. Available 'fname' are:\n%\t\t'haar':\t\tthe \"Haar\" filters\n%\t\t'vk':\t\tMcClellan transformed of the filter from\n%\t\t\t\t the VK book\n%\t\t'ko':\t\torthogonal filter in the Kovacevic's paper\n%\t\t'kos':\t\tsmooth 'ko' filter\n%\t\t'lax':\t\t17 x 17 by Lu, Antoniou and Xu\n%\t\t'sk':\t\t9 x 9 by Shah and Kalker\n%\t\t'cd':\t\t7 and 9 McClellan transformed by \n%\t\t\t\t Cohen and Daubechies\n%\t\t'pkva':\t\tladder filters by Phong et al.\n%\t\t'oqf_362':\tregular 3 x 6 filter\n% 'dvmlp' : regular linear phase biorthogonal filter with 3 dvm\n%\t\t'sinc':\t\tideal filter (*NO perfect recontruction*)\n% 'dmaxflat': diamond maxflat filters obtained from a three stage ladder\n%\n%\t type:\t'd' or 'r' for decomposition or reconstruction filters\n%\n% Output:\n%\th0, h1:\tdiamond filter pair (lowpass and highpass)\n\n% To test those filters (for the PR condition for the FIR case), verify that:\n% conv2(h0, modulate2(h1, 'b')) + conv2(modulate2(h0, 'b'), h1) = 2\n% (replace + with - for even size filters)\n%\n% To test for orthogonal filter\n% conv2(h, reverse2(h)) + modulate2(conv2(h, reverse2(h)), 'b') = 2\n\n% The diamond-shaped filter pair\nswitch fname\n case {'haar'}\n\tif lower(type(1)) == 'd'\n\t h0 = [1, 1] / sqrt(2);\n\t h1 = [-1, 1] / sqrt(2);\n\telse\n\t h0 = [1, 1] / sqrt(2);\n\t h1 = [1, -1] / sqrt(2);\n\tend\n\t\n case 'vk'\t% in Vetterli and Kovacevic book\n\tif lower(type(1)) == 'd'\n\t h0 = [1, 2, 1] / 4;\n\t h1 = [-1, -2, 6, -2, -1] / 4;\n\telse\n\t h0 = [-1, 2, 6, 2, -1] / 4;\n\t h1 = [-1, 2, -1] / 4;\n\tend\n\t\n\t% McClellan transfrom to obtain 2D diamond filters\n\tt = [0, 1, 0; 1, 0, 1; 0, 1, 0] / 4;\t% diamond kernel\n\th0 = ftrans2(h0, t);\n\th1 = ftrans2(h1, t);\n\t\n case 'ko'\t% orthogonal filters in Kovacevic's thesis\n\ta0 = 2; a1 = 0.5; a2 = 1;\n\t\n\th0 = [0, -a1, -a0*a1, 0;\n\t -a2, -a0*a2, -a0, 1;\n\t 0, a0*a1*a2, -a1*a2, 0];\n\t\n\t% h1 = qmf2(h0);\n\th1 = [0, -a1*a2, -a0*a1*a2, 0;\n\t 1, a0, -a0*a2, a2;\n\t 0, -a0*a1, a1, 0];\n\t\n\t% Normalize filter sum and norm;\n\tnorm = sqrt(2) / sum(h0(:));\n\t\n\th0 = h0 * norm;\t\n\th1 = h1 * norm;\n\t \n\tif type == 'r'\n\t % Reverse filters for reconstruction\n\t h0 = h0(end:-1:1, end:-1:1);\n\t h1 = h1(end:-1:1, end:-1:1);\n\tend\n \n case 'kos'\t% Smooth orthogonal filters in Kovacevic's thesis\n\ta0 = -sqrt(3); a1 = -sqrt(3); a2 = 2+sqrt(3);\n\t\n\th0 = [0, -a1, -a0*a1, 0;\n\t -a2, -a0*a2, -a0, 1;\n\t 0, a0*a1*a2, -a1*a2, 0];\n\t\n\t% h1 = qmf2(h0);\n\th1 = [0, -a1*a2, -a0*a1*a2, 0;\n\t 1, a0, -a0*a2, a2;\n\t 0, -a0*a1, a1, 0];\n\t\n\t% Normalize filter sum and norm;\n\tnorm = sqrt(2) / sum(h0(:));\n\t\n\th0 = h0 * norm;\t\n\th1 = h1 * norm;\n\t \n\tif type == 'r'\n\t % Reverse filters for reconstruction\n\t h0 = h0(end:-1:1, end:-1:1);\n\t h1 = h1(end:-1:1, end:-1:1);\n\tend\n\t\n case 'lax'\t% by Lu, Antoniou and Xu\n\th = [-1.2972901e-5, 1.2316237e-4, -7.5212207e-5, 6.3686104e-5, ...\n\t 9.4800610e-5, -7.5862919e-5, 2.9586164e-4, -1.8430337e-4; ...\n\t \n\t 1.2355540e-4, -1.2780882e-4, -1.9663685e-5, -4.5956538e-5, ...\n\t -6.5195193e-4, -2.4722942e-4, -2.1538331e-5, -7.0882131e-4; ...\n\t \n\t -7.5319075e-5, -1.9350810e-5, -7.1947086e-4, 1.2295412e-3, ...\n\t 5.7411214e-4, 4.4705422e-4, 1.9623554e-3, 3.3596717e-4; ...\n\t \n\t 6.3400249e-5, -2.4947178e-4, 4.4905711e-4, -4.1053629e-3, ...\n\t -2.8588307e-3, 4.3782726e-3, -3.1690509e-3, -3.4371484e-3; ...\n\t \n\t 9.6404973e-5, -4.6116254e-5, 1.2371871e-3, -1.1675575e-2, ...\n\t 1.6173911e-2, -4.1197559e-3, 4.4911165e-3, 1.1635130e-2; ...\n\t \n\t -7.6955555e-5, -6.5618379e-4, 5.7752252e-4, 1.6211426e-2, ...\n\t 2.1310378e-2, -2.8712621e-3, -4.8422645e-2, -5.9246338e-3; ...\n\t \n\t 2.9802986e-4, -2.1365364e-5, 1.9701350e-3, 4.5047673e-3, ...\n\t -4.8489158e-2, -3.1809526e-3, -2.9406153e-2, 1.8993868e-1; ...\n\t \n\t -1.8556637e-4, -7.1279432e-4, 3.3839195e-4, 1.1662001e-2, ...\n\t -5.9398223e-3, -3.4467920e-3, 1.9006499e-1, 5.7235228e-1];\n\t\n\th0 = sqrt(2) * [h, h(:, end-1:-1:1); ...\n\t\t\th(end-1:-1:1, :), h(end-1:-1:1, end-1:-1:1)];\t\n\t\n\th1 = modulate2(h0, 'b');\n\t\n case 'sk'\t% by Shah and Kalker\n\th = [ 0.621729, 0.161889, -0.0126949, -0.00542504, 0.00124838; ...\n\t 0.161889, -0.0353769, -0.0162751, -0.00499353, 0; ...\n\t -0.0126949, -0.0162751, 0.00749029, 0, 0; ...\n\t -0.00542504, 0.00499353, 0, 0, 0; ...\n\t 0.00124838, 0, 0, 0, 0];\n\t\n\th0 = sqrt(2) * [h(end:-1:2, end:-1:2), h(end:-1:2, :); ...\n\t\t\th(:, end:-1:2), h];\n\t\n\th1 = modulate2(h0, 'b');\n\t\n case 'dvmlp'\n q= sqrt(2); b=.02; b1 = b*b;\n h = [b/q 0 -2*q*b 0 3*q*b 0 -2*q*b 0 b/q;\n 0 -1/(16*q) 0 9/(16*q) 1/q 9/(16*q) 0 -1/(16*q) 0;\n b/q 0 -2*q*b 0 3*q*b 0 -2*q*b 0 b/q]; \n g0 = [-b1/q 0 4*b1*q 0 -14*q*b1 0 28*q*b1 0 -35*q*b1 0 28*q*b1 0 -14*q*b1 0 4*b1*q 0 -b1/q;\n 0 b/(8*q) 0 -13*b/(8*q) b/q 33*b/(8*q) -2*q*b -21*b/(8*q) 3*q*b -21*b/(8*q) -2*q*b 33*b/(8*q) b/q -13*b/(8*q) 0 b/(8*q) 0;\n -q*b1 0 -1/(256*q) + 8*q*b1 0 9/(128*q) - 28*q*b1 -1/(q*16) -63/(256*q) + 56*q*b1 9/(16*q) 87/(64*q)-70*q*b1 9/(16*q) -63/(256*q) + 56*q*b1 -1/(q*16) 9/(128*q) - 28*q*b1 0 -1/(256*q) + 8*q*b1 0 -q*b1;\n 0 b/(8*q) 0 -13*b/(8*q) b/q 33*b/(8*q) -2*q*b -21*b/(8*q) 3*q*b -21*b/(8*q) -2*q*b 33*b/(8*q) b/q -13*b/(8*q) 0 b/(8*q) 0;\n -b1/q 0 4*b1*q 0 -14*q*b1 0 28*q*b1 0 -35*q*b1 0 28*q*b1 0 -14*q*b1 0 4*b1*q 0 -b1/q];\n h1 = modulate2(g0,'b' );\n h0 = h;\n if lower(type(1)) == 'r'\n h1 = modulate2(h ,'b');\n h0 = g0; \n end\n \n \n \n case {'cd', '7-9'}\t% by Cohen and Daubechies\n\t% 1D prototype filters: the '7-9' pair\n\th0 = [0.026748757411, -0.016864118443, -0.078223266529, ...\n\t 0.266864118443, 0.602949018236, 0.266864118443, ...\n\t -0.078223266529, -0.016864118443, 0.026748757411];\n\tg0 = [-0.045635881557, -0.028771763114, 0.295635881557, ...\n\t 0.557543526229, 0.295635881557, -0.028771763114, ...\n\t -0.045635881557];\n\t\n\tif lower(type(1)) == 'd'\n\t h1 = modulate2(g0, 'c');\n\telse\n\t h1 = modulate2(h0, 'c');\n\t h0 = g0;\n\tend\n\n\t% Use McClellan to obtain 2D filters\n\tt = [0, 1, 0; 1, 0, 1; 0, 1, 0] / 4;\t% diamond kernel\n\th0 = sqrt(2) * ftrans2(h0, t);\t\t\n\th1 = sqrt(2) * ftrans2(h1, t);\n\t\n case {'pkva', 'ldtest'}\t% Filters from the ladder structure\t\n\t% Allpass filter for the ladder structure network\n\tbeta = ldfilter(fname);\n\t\n\t% Analysis filters\n\t[h0, h1] = ld2quin(beta);\n\t\n\t% Normalize norm\n\th0 = sqrt(2) * h0;\n\th1 = sqrt(2) * h1;\n\t\n\t% Synthesis filters\n\tif lower(type(1)) == 'r'\n\t f0 = modulate2(h1, 'b');\n\t f1 = modulate2(h0, 'b');\n\t \n\t h0 = f0;\n\t h1 = f1;\n\tend\t\n\t\n case {'pkva-half4'}\t% Filters from the ladder structure\t\n\t% Allpass filter for the ladder structure network\n\tbeta = ldfilterhalf( 4);\n\t\n\t% Analysis filters\n\t[h0, h1] = ld2quin(beta);\n\t\n\t% Normalize norm\n\th0 = sqrt(2) * h0;\n\th1 = sqrt(2) * h1;\n\t\n\t% Synthesis filters\n\tif lower(type(1)) == 'r'\n\t f0 = modulate2(h1, 'b');\n\t f1 = modulate2(h0, 'b');\n\t \n\t h0 = f0;\n\t h1 = f1;\n\tend\t\n\t\n case {'pkva-half6'}\t% Filters from the ladder structure\t\n\t% Allpass filter for the ladder structure network\n\tbeta = ldfilterhalf( 6);\n\t\n\t% Analysis filters\n\t[h0, h1] = ld2quin(beta);\n\t\n\t% Normalize norm\n\th0 = sqrt(2) * h0;\n\th1 = sqrt(2) * h1;\n\t\n\t% Synthesis filters\n\tif lower(type(1)) == 'r'\n\t f0 = modulate2(h1, 'b');\n\t f1 = modulate2(h0, 'b');\n\t \n\t h0 = f0;\n\t h1 = f1;\n\tend\t\n \n case {'pkva-half8'}\t% Filters from the ladder structure\t\n\t% Allpass filter for the ladder structure network\n\tbeta = ldfilterhalf( 8);\n\t\n\t% Analysis filters\n\t[h0, h1] = ld2quin(beta);\n\t\n\t% Normalize norm\n\th0 = sqrt(2) * h0;\n\th1 = sqrt(2) * h1;\n\t\n\t% Synthesis filters\n\tif lower(type(1)) == 'r'\n\t f0 = modulate2(h1, 'b');\n\t f1 = modulate2(h0, 'b');\n\t \n\t h0 = f0;\n\t h1 = f1;\n\tend\t\n \n \n case 'sinc'\t% The \"sinc\" case, NO Perfect Reconstruction\n\t% Ideal low and high pass filters\n\tflength = 30;\n\t\n\th0 = fir1(flength, 0.5);\n\th1 = modulate2(h0, 'c');\n\t\n\t% Use McClellan to obtain 2D filters\n\tt = [0, 1, 0; 1, 0, 1; 0, 1, 0] / 4;\t% diamond kernel\n\th0 = sqrt(2) * ftrans2(h0, t);\t\n\th1 = sqrt(2) * ftrans2(h1, t);\t\n\n case {'oqf_362'}\t% Some \"home-made\" filters!\n h0 = sqrt(2) / 64 * ...\n [\tsqrt(15),\t-3,\t0; ...\n 0,\t\t5,\t-sqrt(15); ...\n -2*sqrt(15),\t30,\t0; ...\n 0,\t\t30,\t2*sqrt(15); ...\n sqrt(15),\t5, \t0; ...\n 0, \t\t-3,\t-sqrt(15)]';\n\n h1 = -reverse2(modulate2(h0, 'b'));\n\t\n\tif type == 'r'\n\t % Reverse filters for reconstruction\n\t h0 = h0(end:-1:1, end:-1:1);\n\t h1 = h1(end:-1:1, end:-1:1);\n\tend\n \n \n \t\n case {'test'}\t% Only for the shape, not for PR\n\th0 = [0, 1, 0; 1, 4, 1; 0, 1, 0];\n\th1 = [0, -1, 0; -1, 4, -1; 0, -1, 0];\n\t\n case {'testDVM'}\t% Only for directional vanishing moment\n\th0 = [1, 1; 1, 1] / sqrt(2);\n\th1 = [-1, 1; 1, -1] / sqrt(2);\t\n\t\n \t\n case 'qmf'\t% by Lu, Antoniou and Xu\n\t% ideal response\n % window\n m=2;\n n=2;\n w=[];\n w1d=kaiser(4*m+1,2.6);\n for n1=-m:m\n for n2 = -n:n\n w(n1+m+1,n2+n+1) = w1d(2*m+n1+n2+1)*w1d(2*m+n1-n2+1) ;\n end\n end\n h=[];\n for n1=-m:m\n for n2 = -n:n\n h(n1+m+1,n2+n+1) = .5*sinc((n1+n2)/2)*.5*sinc((n1-n2)/2);\n end\n end\n c=sum(sum(h));\n h = sqrt(2)*h/c;\n h0=h.*w;\n h1 = modulate2(h0,'b');\n \n %h0 = modulate2(h,'r');\n %h1 = modulate2(h,'b');\n \n \n case 'qmf2'\t% by Lu, Antoniou and Xu\n\t% ideal response\n % window\n \n h=[-.001104 .002494 -0.001744 0.004895 -0.000048 -.000311;\n 0.008918 -0.002844 -0.025197 -0.017135 0.003905 -0.000081;\n -0.007587 -0.065904 00.100431 -0.055878 0.007023 0.001504;\n 0.001725 0.184162 0.632115 0.099414 -0.027006 -0.001110;\n -0.017935 -0.000491 0.191397 -0.001787 -0.010587 0.002060;\n .001353 0.005635 -0.001231 -0.009052 -0.002668 0.000596];\n h0 = h./sum(sum(h));\n h1 = modulate2(h0,'b');\n \n %h0 = modulate2(h,'r');\n %h1 = modulate2(h,'b'); \n \n case 'dmaxflat4'\n M1 = 1/sqrt(2); M2=M1;\n k1=1-sqrt(2);k3=k1;\n k2 = M1; \n h = [.25*k2*k3 .5*k2 1+.5*k2*k3]*M1; h = [h fliplr(h(1:end-1))];\n g = [-.125*k1*k2*k3 0.25*k1*k2 (-0.5*k1-0.5*k3-0.375*k1*k2*k3) 1+ .5*k1*k2]*M2;\n g = [g fliplr(g(1:end-1))];\n B = dmaxflat(4,0);\n h0 = mctrans(h,B);\n g0 = mctrans(g,B);\n h0 = sqrt(2)*(h0./sum(h0(:)));\n g0 = sqrt(2)*(g0./sum(g0(:)));\n \n h1 = modulate2(g0,'b' );\n if lower(type(1)) == 'r'\n h1 = modulate2(h0 ,'b');\n h0 = g0; \n end\n case 'dmaxflat5'\n M1 = 1/sqrt(2); M2=M1;\n k1=1-sqrt(2);k3=k1;\n k2 = M1; \n h = [.25*k2*k3 .5*k2 1+.5*k2*k3]*M1; h = [h fliplr(h(1:end-1))];\n g = [-.125*k1*k2*k3 0.25*k1*k2 (-0.5*k1-0.5*k3-0.375*k1*k2*k3) 1+ .5*k1*k2]*M2;\n g = [g fliplr(g(1:end-1))];\n B = dmaxflat(5,0);\n h0 = mctrans(h,B);\n g0 = mctrans(g,B);\n h0 = sqrt(2)*(h0./sum(h0(:)));\n g0 = sqrt(2)*(g0./sum(g0(:)));\n \n h1 = modulate2(g0,'b' );\n if lower(type(1)) == 'r'\n h1 = modulate2(h0 ,'b');\n h0 = g0; \n end\n \n case 'dmaxflat6'\n M1 = 1/sqrt(2); M2=M1;\n k1=1-sqrt(2);k3=k1;\n k2 = M1; \n h = [.25*k2*k3 .5*k2 1+.5*k2*k3]*M1; h = [h fliplr(h(1:end-1))];\n g = [-.125*k1*k2*k3 0.25*k1*k2 (-0.5*k1-0.5*k3-0.375*k1*k2*k3) 1+ .5*k1*k2]*M2;\n g = [g fliplr(g(1:end-1))];\n B = dmaxflat(6,0);\n h0 = mctrans(h,B);\n g0 = mctrans(g,B);\n h0 = sqrt(2)*(h0./sum(h0(:)));\n g0 = sqrt(2)*(g0./sum(g0(:)));\n \n h1 = modulate2(g0,'b' );\n if lower(type(1)) == 'r'\n h1 = modulate2(h0 ,'b');\n h0 = g0; \n end\n \n case 'dmaxflat7'\n M1 = 1/sqrt(2); M2=M1;\n k1=1-sqrt(2);k3=k1;\n k2 = M1; \n h = [.25*k2*k3 .5*k2 1+.5*k2*k3]*M1; h = [h fliplr(h(1:end-1))];\n g = [-.125*k1*k2*k3 0.25*k1*k2 (-0.5*k1-0.5*k3-0.375*k1*k2*k3) 1+ .5*k1*k2]*M2;\n g = [g fliplr(g(1:end-1))];\n B = dmaxflat(7,0);\n h0 = mctrans(h,B);\n g0 = mctrans(g,B);\n h0 = sqrt(2)*(h0./sum(h0(:)));\n g0 = sqrt(2)*(g0./sum(g0(:)));\n \n h1 = modulate2(g0,'b' );\n if lower(type(1)) == 'r'\n h1 = modulate2(h0 ,'b');\n h0 = g0; \n end\n \n \n otherwise\n\t% Assume the \"degenerated\" case: 1D wavelet filters\n\t[h0, h1] = wfilters(fname, type); \nend", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/nsct_toolbox/dfilters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6330026125535846}} {"text": "function PlotAdaptiveContour2D(u, levels, tol)\n\n% function PlotAdaptiveContour2D(u, levels, tol)\n% Purpose: adaptively refine the mesh to approximately locate isocontours\n\nGlobals2D;\n\n% build interpolation matrix (coarse->fine)\nri(:,1) = 0.5*(-(r+s)*( 0) + (1+r)*( 0) + (1+s)*(-1) );\nsi(:,1) = 0.5*(-(r+s)*(-1) + (1+r)*( 0) + (1+s)*( 0) );\n\nri(:,2) = 0.5*(-(r+s)*(-1) + (1+r)*( 0) + (1+s)*(-1) );\nsi(:,2) = 0.5*(-(r+s)*(-1) + (1+r)*(-1) + (1+s)*( 0) );\n\nri(:,3) = 0.5*(-(r+s)*( 1) + (1+r)*( 0) + (1+s)*( 0) );\nsi(:,3) = 0.5*(-(r+s)*(-1) + (1+r)*( 0) + (1+s)*(-1) );\n\nri(:,4) = 0.5*(-(r+s)*(-1) + (1+r)*(-1) + (1+s)*( 0) );\nsi(:,4) = 0.5*(-(r+s)*( 1) + (1+r)*( 0) + (1+s)*( 0) );\n\n%interp = Vandermonde2D(N, ri(:), si(:))*invV; \ninterp = InterpMatrix2D(ri(:),si(:));\n\nNlevels = length(levels);\n\nxref = x; yref = y; uref = u; Kref = K;\n\nsk = 1;\nF = spalloc(Np,Np,1);\nfor i=0:N % old ordering\n for j=0:N - i\n if(i+j<=1), F(sk,sk) = 1.; end;\n sk = sk+1;\n end\nend\n\nhold on\nfor nlev=1:Nlevels\n lev = levels(nlev);\n\n xref = x; yref = y; uref = u; Kref = K; Jref = J;\n\n err = 1;\n while(err > tol)\n \n umin = min(uref, [], 1);\n umax = max(uref, [], 1);\n \n refineflag = (umin <= lev & umax >= lev);\n \n toref = find( refineflag);\n Nref = length(toref);\n\n uref = reshape(interp*uref(:,toref), Np, 4*Nref);\n xref = reshape(interp*xref(:,toref), Np, 4*Nref);\n yref = reshape(interp*yref(:,toref), Np, 4*Nref);\n \n Kref = 4*Nref;\n \n ufilt = V*(F*(invV*uref));\n err = max(max(abs(ufilt-uref)));\n\n end \n\n ri = [-1;1;-1]; si = [-1;-1;1]; refNp = length(ri);\n interp1 = InterpMatrix2D(ri,si);\n xref = interp1*xref; yref = interp1*yref; uref = interp1*uref; \n \n ltri = delaunay(ri,si);\n Nltri = size(ltri,1);\n tri = zeros(Kref*Nltri, Nfaces);\n ks = (1:Nltri)';\n for k=1:Kref\n tri(ks,:) = ltri + (k-1)*refNp;\n ks = ks + Nltri;\n end\n \n PlotContour2D(tri, xref(:), yref(:), uref(:), levels)\n \nend\nhold off\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/ServiceRoutines/PlotAdaptiveContour2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6329358457247408}} {"text": "function sparse_grid_cc_dataset ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_CC_DATASET is the main program for SPARSE_GRID_CC_DATASET.\n%\n% Discussion:\n%\n% This program computes a sparse grid quadrature rule based on 1D\n% Clenshaw-Curtis rules and writes it to a file.. \n%\n% The user specifies:\n% * the spatial dimension of the quadrature region,\n% * the level that defines the Smolyak grid.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_CC_DATASET\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute the abscissas and weights of a quadrature rule\\n' );\n fprintf ( 1, ' associated with a sparse grid derived from a Smolyak\\n' );\n fprintf ( 1, ' construction based on 1D Clenshaw-Curtis rules.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Inputs to the program include:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DIM_NUM, the spatial dimension.\\n' );\n fprintf ( 1, ' (typically in the range of 2 to 10)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_MAX, the \"level\" of the sparse grid.\\n' );\n fprintf ( 1, ' (typically in the range of 0, 1, 2, 3, ...\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Output from the program includes:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A printed table of the abscissas and weights.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * A set of 3 files that define the quadrature rule.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"cc_d?_level?_r.txt\", a file of the ranges.\\n' );\n fprintf ( 1, ' \"cc_d?_level?_w.txt\", a file of the weights;\\n' );\n fprintf ( 1, ' \"cc_d?_level?_x.txt\", a file of the abscissas;\\n' );\n%\n% Get the spatial dimension.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n dim_num = input ( ' Enter the value of DIM_NUM (1 or greater): ' );\n elseif ( ischar ( dim_num ) )\n dim_num = str2num ( dim_num );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension requested is = %d\\n', dim_num );\n%\n% Get the level.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n level_max = input ( ' Enter the value of LEVEL_MAX (0 or greater): ' );\n elseif ( ischar ( level_max ) )\n level_max = str2num ( level_max );\n end\n\n level_min = max ( 0, level_max + 1 - dim_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_MIN = %d\\n', level_min );\n fprintf ( 1, ' LEVEL_MAX = %d\\n', level_max );\n%\n% How many distinct points will there be?\n%\n point_num = sparse_grid_cfn_size ( dim_num, level_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of distinct abscissas in the\\n' );\n fprintf ( 1, ' quadrature rule is determined from the spatial\\n' );\n fprintf ( 1, ' dimension DIM_NUM and the level LEVEL_MAX.\\n' );\n fprintf ( 1, ' For the given input, this value will be = %d\\n', point_num );\n\n r = zeros ( dim_num, 2 );\n%\n% Compute the weights and points.\n%\n r(1:dim_num,1) = -1.0;\n r(1:dim_num,2) = +1.0;\n\n [ w, x ] = sparse_grid_cc ( dim_num, level_max, point_num );\n\n r8mat_transpose_print_some ( dim_num, point_num, x, 1, 1, ...\n dim_num, 10, ' First 10 grid points:' );\n\n r8vec_print_some ( point_num, w, 1, 10, ' First 10 weights:' );\n\n weight_sum = sum ( w(1:point_num) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weights sum to %24.16f\\n', weight_sum );\n fprintf ( 1, ' Correct value is %24.16f\\n', 2.0^dim_num );\n%\n% Write the rule to files.\n%\n r_filename = sprintf ( 'cc_d%d_level%d_r.txt', dim_num, level_max );\n w_filename = sprintf ( 'cc_d%d_level%d_w.txt', dim_num, level_max );\n x_filename = sprintf ( 'cc_d%d_level%d_x.txt', dim_num, level_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Creating R file = \"%s\".\\n', r_filename );\n\n r8mat_write ( r_filename, dim_num, 2, r );\n\n fprintf ( 1, ' Creating W file = \"%s\".\\n', w_filename );\n\n r8mat_write ( w_filename, 1, point_num, w );\n\n fprintf ( 1, ' Creating X file = \"%s\".\\n', x_filename );\n\n r8mat_write ( x_filename, dim_num, point_num, x );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_CC_DATASET:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction test_level = abscissa_level_closed_nd ( level_max, dim_num, ...\n test_num, test_val )\n\n%*******************************************************************************\n%\n%% ABSCISSA_LEVEL_CLOSED_ND: first level at which given abscissa is generated.\n%\n% Discussion:\n%\n% We assume an underlying product grid. In each dimension, this product\n% grid has order 2^LEVEL_MAX + 1.\n%\n% We will say a sparse grid has total level LEVEL if each point in the\n% grid has a total level of LEVEL or less.\n%\n% The \"level\" of a point is determined as the sum of the levels of the\n% point in each spatial dimension.\n%\n% The level of a point in a single spatial dimension I is determined as\n% the level, between 0 and LEVEL_MAX, at which the point's I'th index\n% would have been generated.\n%\n%\n% This description is terse and perhaps unenlightening. Keep in mind\n% that the product grid is the product of 1D grids,\n% that the 1D grids are built up by levels, having\n% orders (total number of points ) 1, 3, 5, 9, 17, 33 and so on,\n% and that these 1D grids are nested, so that each point in a 1D grid\n% has a first level at which it appears.\n%\n% Our procedure for generating the points of a sparse grid, then, is\n% to choose a value LEVEL_MAX, to generate the full product grid,\n% but then only to keep those points on the full product grid whose\n% LEVEL is less than or equal to LEVEL_MAX. \n%\n%\n% Note that this routine is really just testing out the idea of\n% determining the level. Our true desire is to be able to start\n% with a value LEVEL, and determine, in a straightforward manner,\n% all the points that are generated exactly at that level, or\n% all the points that are generated up to and including that level.\n%\n% This allows us to generate the new points to be added to one sparse\n% grid to get the next, or to generate a particular sparse grid at once.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer LEVEL_MAX, controls the size of the final sparse grid.\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer TEST_NUM, the number of points to be tested.\n%\n% Input, integer TEST_VAL(DIM_NUM,TEST_NUM), the indices of the points \n% to be tested. Normally, each index would be between 0 and 2^LEVEL_MAX.\n%\n% Output, integer TEST_LEVEL(TEST_NUM), the value of LEVEL at which the\n% point would first be generated, assuming that a standard sequence of\n% nested grids is used.\n%\n test_level = zeros ( test_num, 1 );\n \n if ( level_max == 0 )\n test_level(1:test_num) = 0;\n return\n end\n\n order = 2^level_max + 1;\n\n for j = 1 : test_num\n\n test_level(j) = index_to_level_closed ( dim_num, test_val(1:dim_num,j), ...\n order, level_max );\n\n end\n\n return\nend\nfunction value = cc_abscissa ( n, i )\n\n%*******************************************************************************\n%\n%% CC_ABSCISSA returns the I-th abscissa of the Clenshaw Curtis rule.\n%\n% Discussion:\n%\n% The abscissas are numbered from left to right.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the rule.\n%\n% Input, integer I, the index of the desired abscissa. 1 <= I <= N.\n%\n% Output, real VALUE, the value of the I-th abscissa in the \n% rule of order N.\n%\n if ( n < 1 )\n value = - Inf;\n elseif ( i < 1 || n < i )\n value = - Inf;\n elseif ( n == 1 )\n value = 0.0;\n elseif ( 2 * ( n - i ) == n - 1 )\n value = 0.0;\n else\n value = cos ( ( n - i ) * pi / ( n - 1 ) );\n end\n\n return\nend\nfunction w = cc_weights ( n )\n\n%*******************************************************************************\n%\n%% CC_WEIGHTS computes Clenshaw Curtis weights.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Charles Clenshaw, Alan Curtis,\n% A Method for Numerical Integration on an Automatic Computer,\n% Numerische Mathematik,\n% Volume 2, Number 1, December 1960, pages 197-205.\n%\n% Parameters:\n%\n% Input, integer N, the order of the rule.\n%\n% Output, real W(N), the weights of the rule.\n%\n w = zeros ( n, 1 );\n \n if ( n == 1 )\n w(1) = 2.0;\n return\n end\n\n theta = zeros ( n, 1 );\n \n for i = 1 : n\n theta(i) = ( i - 1 ) * pi / ( n - 1 );\n end\n\n for i = 1 : n\n\n w(i) = 1.0;\n\n for j = 1 : floor ( ( n - 1 ) / 2 )\n\n if ( 2 * j == ( n - 1 ) )\n b = 1.0;\n else\n b = 2.0;\n end\n\n w(i) = w(i) - b * cos ( 2.0 * j * theta(i) ) / ( 4 * j * j - 1 );\n\n end\n\n end\n\n w(1) = w(1) / ( n - 1 );\n w(2:n-1) = 2.0 * w(2:n-1) / ( n - 1 );\n w(n) = w(n) / ( n - 1 );\n\n return\nend\nfunction value = choose ( n, k )\n\n%*******************************************************************************\n%\n%% CHOOSE computes the binomial coefficient C(N,K).\n%\n% Discussion:\n%\n% The value is calculated in such a way as to avoid overflow and\n% roundoff. The calculation is done in integer arithmetic.\n%\n% The formula used is:\n%\n% C(N,K) = N! / ( K! * (N-K)! )\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% ML Wolfson, HV Wright,\n% Algorithm 160:\n% Combinatorial of M Things Taken N at a Time,\n% Communications of the ACM,\n% Volume 6, Number 4, April 1963, page 161.\n%\n% Parameters:\n%\n% Input, integer N, K, are the values of N and K.\n%\n% Output, integer VALUE, the number of combinations of N\n% things taken K at a time.\n%\n mn = min ( k, n - k );\n\n if ( mn < 0 )\n\n value = 0;\n\n elseif ( mn == 0 )\n\n value = 1;\n\n else\n\n mx = max ( k, n - k );\n value = mx + 1;\n\n for i = 2 : mn\n value = ( value * ( mx + i ) ) / i;\n end\n\n end\n\n return\nend\nfunction [ a, more, h, t ] = comp_next ( n, k, a, more, h, t )\n\n%*******************************************************************************\n%\n%% COMP_NEXT computes the compositions of the integer N into K parts.\n%\n% Discussion:\n%\n% A composition of the integer N into K parts is an ordered sequence\n% of K nonnegative integers which sum to N. The compositions (1,2,1)\n% and (1,1,2) are considered to be distinct.\n%\n% The routine computes one composition on each call until there are no more.\n% For instance, one composition of 6 into 3 parts is\n% 3+2+1, another would be 6+0+0.\n%\n% On the first call to this routine, set MORE = FALSE. The routine\n% will compute the first element in the sequence of compositions, and\n% return it, as well as setting MORE = TRUE. If more compositions\n% are desired, call again, and again. Each time, the routine will\n% return with a new composition.\n%\n% However, when the LAST composition in the sequence is computed \n% and returned, the routine will reset MORE to FALSE, signaling that\n% the end of the sequence has been reached.\n%\n% This routine originally used a SAVE statement to maintain the\n% variables H and T. I have decided (based on an wasting an\n% entire morning trying to track down a problem) that it is safer\n% to pass these variables as arguments, even though the user should\n% never alter them. This allows this routine to safely shuffle\n% between several ongoing calculations.\n%\n% There are 28 compositions of 6 into three parts. This routine will\n% produce those compositions in the following order:\n%\n% I A\n% - ---------\n% 1 6 0 0\n% 2 5 1 0\n% 3 4 2 0\n% 4 3 3 0\n% 5 2 4 0\n% 6 1 5 0\n% 7 0 6 0\n% 8 5 0 1\n% 9 4 1 1\n% 10 3 2 1\n% 11 2 3 1\n% 12 1 4 1\n% 13 0 5 1\n% 14 4 0 2\n% 15 3 1 2\n% 16 2 2 2\n% 17 1 3 2\n% 18 0 4 2\n% 19 3 0 3\n% 20 2 1 3\n% 21 1 2 3\n% 22 0 3 3\n% 23 2 0 4\n% 24 1 1 4\n% 25 0 2 4\n% 26 1 0 5\n% 27 0 1 5\n% 28 0 0 6\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms for Computers and Calculators,\n% Second Edition,\n% Academic Press, 1978,\n% ISBN: 0-12-519260-6,\n% LC: QA164.N54.\n%\n% Parameters:\n%\n% Input, integer N, the integer whose compositions are desired.\n%\n% Input, integer K, the number of parts in the composition.\n%\n% Input, integer A(K), the previous composition. On the first call,\n% with MORE = FALSE, set A = []. Thereafter, A should be the \n% value of A output from the previous call.\n%\n% Input, logical MORE. The input value of MORE on the first\n% call should be FALSE, which tells the program to initialize.\n% On subsequent calls, MORE should be TRUE, or simply the\n% output value of MORE from the previous call.\n%\n% Input, integer H, T, two internal parameters needed for the\n% computation. The user may need to initialize these before the\n% very first call, but these initial values are not important.\n% The user should not alter these parameters once the computation\n% begins.\n%\n% Output, integer A(K), the next composition.\n%\n% Output, logical MORE, will be TRUE unless the composition \n% that is being returned is the final one in the sequence.\n%\n% Output, integer H, T, the updated values of the two internal \n% parameters.\n%\n if ( ~more )\n\n t = n;\n h = 0;\n a(1) = n;\n a(2:k) = 0;\n\n else\n \n if ( 1 < t )\n h = 0;\n end\n\n h = h + 1;\n t = a(h);\n a(h) = 0;\n a(1) = t - 1;\n a(h+1) = a(h+1) + 1;\n\n end\n\n more = ( a(k) ~= n );\n\n return\nend\nfunction value = i4_modp ( i, j )\n\n%*******************************************************************************\n%\n%% I4_MODP returns the nonnegative remainder of I4 division.\n%\n% Discussion:\n%\n% If\n% NREM = I4_MODP ( I, J )\n% NMULT = ( I - NREM ) / J\n% then\n% I = J * NMULT + NREM\n% where NREM is always nonnegative.\n%\n% The MOD function computes a result with the same sign as the\n% quantity being divided. Thus, suppose you had an angle A,\n% and you wanted to ensure that it was between 0 and 360.\n% Then mod(A,360) would do, if A was positive, but if A\n% was negative, your result would be between -360 and 0.\n%\n% On the other hand, I4_MODP(A,360) is between 0 and 360, always.\n%\n% Example:\n%\n% I J MOD I4_MODP Factorization\n%\n% 107 50 7 7 107 = 2 * 50 + 7\n% 107 -50 7 7 107 = -2 * -50 + 7\n% -107 50 -7 43 -107 = -3 * 50 + 43\n% -107 -50 -7 43 -107 = 3 * -50 + 43\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the number to be divided.\n%\n% Input, integer J, the number that divides I.\n%\n% Output, integer VALUE, the nonnegative remainder when I is\n% divided by J.\n%\n if ( j == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MODP - Fatal error!\\n' );\n fprintf ( 1, ' Illegal divisor J = %d\\n', j );\n error ( 'I4_MODP - Fatal error!' );\n end\n\n value = mod ( i, j );\n\n if ( value < 0 )\n value = value + abs ( j );\n end\n\n return\nend\nfunction value = index_to_level_closed ( dim_num, t, order, level_max )\n\n%*******************************************************************************\n%\n%% INDEX_TO_LEVEL_CLOSED determines the level of a point given its index.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer T(DIM_NUM), the grid indices of a point in a 1D closed rule.\n% 0 <= T(I) <= ORDER.\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, integer LEVEL_MAX, the level with respect to which the\n% index applies.\n%\n% Output, integer VALUE, the first level on which\n% the point associated with the given index will appear.\n%\n value = 0;\n \n for dim = 1 : dim_num\n\n s = i4_modp ( t(dim), order );\n\n if ( s == 0 )\n\n level = 0;\n\n else\n\n level = level_max;\n\n while ( mod ( s, 2 ) == 0 )\n s = floor ( s / 2 );\n level = level - 1;\n end\n\n end\n\n if ( level == 0 )\n level = 1;\n elseif ( level == 1 )\n level = 0;\n end\n\n value = value + level;\n\n end\n\n return\nend\nfunction order = level_to_order_closed ( dim_num, level )\n\n%*******************************************************************************\n%\n%% LEVEL_TO_ORDER_CLOSED converts a level to an order for closed rules.\n%\n% Discussion:\n%\n% Sparse grids can naturally be nested. A natural scheme is to use\n% a series of one-dimensional rules arranged in a series of \"levels\"\n% whose order roughly doubles with each step.\n%\n% The arrangement described here works naturally for the Clenshaw Curtis\n% and Newton Cotes closed rules. \n%\n% The following table shows how the growth will occur:\n%\n% Level Order\n%\n% 0 1\n% 1 3 = 2 + 1\n% 2 5 = 4 + 1\n% 3 9 = 8 + 1\n% 4 17 = 16 + 1\n% 5 33 = 32 + 1\n%\n% For the Clenshaw Curtis and Newton Cotes Closed rules, the point growth\n% is nested. If we have ORDER points on a particular LEVEL, the next\n% level includes all these old points, plus ORDER-1 new points, formed\n% in the gaps between successive pairs of old points.\n%\n% Level Order = New + Old\n%\n% 0 1 = 1 + 0\n% 1 3 = 2 + 1\n% 2 5 = 2 + 3\n% 3 9 = 4 + 5\n% 4 17 = 8 + 9\n% 5 33 = 16 + 17\n%\n% In this routine, we assume that a vector of levels is given,\n% and the corresponding orders are desired.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL(DIM_NUM), the nesting level.\n%\n% Output, integer ORDER(DIM_NUM), the order (number of points) of the rule.\n%\n order = zeros ( dim_num, 1 );\n \n for dim = 1 : dim_num\n\n if ( level(dim) < 0 )\n order(dim) = -1;\n elseif ( level(dim) == 0 )\n order(dim) = 1;\n else\n order(dim) = ( 2^level(dim) ) + 1;\n end\n\n end\n\n return\nend\nfunction indx = multigrid_index0 ( dim_num, order_1d, order_nd )\n\n%*******************************************************************************\n%\n%% MULTIGRID_INDEX0 returns an indexed multidimensional grid.\n%\n% Discussion:\n%\n% For dimension DIM, the second index of INDX may vary from \n% 0 to ORDER_1D(DIM)-1.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension of the points.\n%\n% Input, integer ORDER_1D(DIM_NUM), the order of the\n% rule in each dimension.\n%\n% Input, integer ORDER_ND, the product of the entries of ORDER_1D.\n%\n% Output, integer INDX(DIM_NUM,ORDER_ND), the indices of the points in\n% the grid. The second dimension of this array is equal to the\n% product of the entries of ORDER_1D.\n%\n p = 0;\n indx = zeros(dim_num,order_nd);\n\n a = [];\n more = 0;\n\n while ( 1 )\n\n [ a, more ] = vec_colex_next2 ( dim_num, order_1d, a, more );\n\n if ( ~more )\n break\n end\n\n p = p + 1;\n\n indx(1:dim_num,p) = a(1:dim_num)';\n\n end\n\n return\nend\nfunction grid_index = multigrid_scale_closed ( dim_num, order_nd, level_max, ...\n level_1d, grid_index )\n\n%*******************************************************************************\n%\n%% MULTIGRID_SCALE_CLOSED renumbers a grid as a subgrid on a higher level.\n%\n% Discussion:\n%\n% This routine takes a grid associated with a given value of\n% LEVEL, and multiplies all the indices by a power of 2, so that\n% the indices reflect the position of the same points, but in\n% a grid of level LEVEL_MAX.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer ORDER_ND, the number of points in the grid.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer LEVEL_1D(DIM_NUM), the level in each dimension.\n%\n% Input, integer GRID_INDEX(DIM_NUM,POINT_NUM), the index\n% values for each grid point, based in the level for which the grid \n% was generated.\n%\n% Output, integer GRID_INDEX(DIM_NUM,POINT_NUM), the index\n% values for each grid point, appropriate for the grid as a subgrid \n% of a grid of level LEVEL_MAX.\n%\n for dim = 1 : dim_num\n\n if ( level_1d(dim) == 0 )\n\n if ( 0 == level_max )\n order_max = 1;\n else\n order_max = 2^level_max + 1;\n end\n\n grid_index(dim,1:order_nd) = floor ( ( order_max - 1 ) / 2 );\n\n else\n\n factor = 2^( level_max - level_1d(dim) );\n\n grid_index(dim,1:order_nd) = grid_index(dim,1:order_nd) * factor;\n\n end\n\n end\n\n return\nend\nfunction w_nd = product_weights_cc ( dim_num, order_1d, order_nd )\n\n%*******************************************************************************\n%\n%% PRODUCT_WEIGHTS_CC computes weights for a Clenshaw Curtis product rule.\n%\n% Discussion:\n%\n% This routine computes the weights for a quadrature rule which is\n% a product of 1D closed rules of varying order.\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer ORDER_1D(DIM_NUM), the order of the 1D rules.\n%\n% Input, integer ORDER_ND, the order of the product rule.\n%\n% Output, real W_ND(DIM_NUM,ORDER_ND), the product rule weights.\n%\n w_nd(1:order_nd) = 1.0;\n\n for dim = 1 : dim_num\n\n w_1d = cc_weights ( order_1d(dim) );\n\n w_nd = r8vec_direct_product2 ( dim, order_1d(dim), w_1d, dim_num, ...\n order_nd, w_nd );\n \n end\n\n return\nend\nfunction r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*******************************************************************************\n%\n%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,N), an M by N matrix to be printed.\n%\n% Input, integer ILO, JLO, the first row and column to print.\n%\n% Input, integer IHI, JHI, the last row and column to print.\n%\n% Input, string TITLE, an optional title.\n%\n incx = 5;\n\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )\n\n i2hi = i2lo + incx - 1;\n i2hi = min ( i2hi, m );\n i2hi = min ( i2hi, ihi );\n\n inc = i2hi + 1 - i2lo;\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row: ' );\n for i = i2lo : i2hi\n fprintf ( 1, '%7d ', i );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col\\n' );\n\n j2lo = max ( jlo, 1 );\n j2hi = min ( jhi, n );\n\n for j = j2lo : j2hi\n\n fprintf ( 1, '%5d ', j );\n for i2 = 1 : inc\n i = i2lo - 1 + i2;\n fprintf ( 1, '%12f', a(i,j) );\n end\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction w = r8vec_direct_product2 ( factor_index, factor_order, ...\n factor_value, factor_num, point_num, w )\n\n%*******************************************************************************\n%\n%% R8VEC_DIRECT_PRODUCT2 creates a direct product of R8VEC's.\n%\n% Discussion:\n%\n% To explain what is going on here, suppose we had to construct\n% a multidimensional quadrature rule as the product of K rules\n% for 1D quadrature.\n%\n% The product rule will be represented as a list of points and weights.\n%\n% The J-th item in the product rule will be associated with\n% item J1 of 1D rule 1,\n% item J2 of 1D rule 2, \n% ..., \n% item JK of 1D rule K.\n%\n% In particular, \n% X(J) = ( X(1,J1), X(2,J2), ..., X(K,JK))\n% and\n% W(J) = W(1,J1) * W(2,J2) * ... * W(K,JK)\n%\n% So we can construct the quadrature rule if we can properly\n% distribute the information in the 1D quadrature rules.\n%\n% This routine carries out that task for the weights W.\n%\n% Another way to do this would be to compute, one by one, the\n% set of all possible indices (J1,J2,...,JK), and then index\n% the appropriate information. An advantage of the method shown\n% here is that you can process the K-th set of information and\n% then discard it.\n%\n% Example:\n%\n% Rule 1: \n% Order = 4\n% W(1:4) = ( 2, 3, 5, 7 )\n%\n% Rule 2:\n% Order = 3\n% W(1:3) = ( 11, 13, 17 )\n%\n% Rule 3:\n% Order = 2\n% W(1:2) = ( 19, 23 )\n%\n% Product Rule:\n% Order = 24\n% W(1:24) =\n% ( 2 * 11 * 19 )\n% ( 3 * 11 * 19 )\n% ( 4 * 11 * 19 )\n% ( 7 * 11 * 19 )\n% ( 2 * 13 * 19 )\n% ( 3 * 13 * 19 )\n% ( 5 * 13 * 19 )\n% ( 7 * 13 * 19 )\n% ( 2 * 17 * 19 )\n% ( 3 * 17 * 19 )\n% ( 5 * 17 * 19 )\n% ( 7 * 17 * 19 )\n% ( 2 * 11 * 23 )\n% ( 3 * 11 * 23 )\n% ( 5 * 11 * 23 )\n% ( 7 * 11 * 23 )\n% ( 2 * 13 * 23 )\n% ( 3 * 13 * 23 )\n% ( 5 * 13 * 23 )\n% ( 7 * 13 * 23 )\n% ( 2 * 17 * 23 )\n% ( 3 * 17 * 23 )\n% ( 5 * 17 * 23 )\n% ( 7 * 17 * 23 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer FACTOR_INDEX, the index of the factor being processed.\n% The first factor processed must be factor 1.\n%\n% Input, integer FACTOR_ORDER, the order of the factor.\n%\n% Input, real FACTOR_VALUE(FACTOR_ORDER), the factor values for\n% factor FACTOR_INDEX.\n%\n% Input, integer FACTOR_NUM, the number of factors.\n%\n% Input, integer POINT_NUM, the number of elements in the direct product.\n%\n% Input/output, real W(POINT_NUM), the elements of the\n% direct product, updated by the latest factor.\n%\n% Local Parameters:\n%\n% Local, integer START, the first location of a block of values to set.\n%\n% Local, integer CONTIG, the number of consecutive values to set.\n%\n% Local, integer SKIP, the distance from the current value of START\n% to the next location of a block of values to set.\n%\n% Local, integer REP, the number of blocks of values to set.\n%\n persistent contig;\n persistent rep;\n persistent skip;\n\n if ( factor_index == 1 )\n contig = 1;\n skip = 1;\n rep = point_num;\n w(1:point_num) = 1.0;\n end\n\n rep = rep / factor_order;\n skip = skip * factor_order;\n\n for j = 1 : factor_order\n\n start = 1 + ( j - 1 ) * contig;\n\n for k = 1 : rep\n w(start:start+contig-1) = w(start:start+contig-1) * factor_value(j);\n start = start + skip;\n end\n\n end\n\n contig = contig * factor_order;\n\n return\nend\nfunction r8vec_print_some ( n, a, i_lo, i_hi, title )\n\n%*******************************************************************************\n%\n%% R8VEC_PRINT_SOME prints \"some\" of an R8VEC.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8 values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the vector.\n%\n% Input, real A(N), the vector to be printed.\n%\n% Input, integer MAX_PRINT, the maximum number of lines to print.\n%\n% Input, string TITLE, an optional title.\n%\n if ( 0 < s_len_trim ( title ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n end\n\n fprintf ( 1, '\\n' );\n\n for i = max ( 1, i_lo ) : min ( n, i_hi )\n fprintf ( 1, ' %8d %12f\\n', i, a(i) );\n end\n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*******************************************************************************\n%\n%% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LEN, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\n function [ grid_weight, grid_point ] = sparse_grid_cc ( dim_num, ...\n level_max, point_num )\n\n%*******************************************************************************\n%\n%% SPARSE_GRID_CC computes a sparse grid of Clenshaw Curtis points.\n%\n% Discussion:\n%\n% This program computes a quadrature rule and writes it to a file.\n%\n% The quadrature rule is associated with a sparse grid derived from\n% a Smolyak construction using a closed 1D quadrature rule. \n%\n% The user specifies:\n% * the spatial dimension of the quadrature region,\n% * the level that defines the Smolyak grid.\n% * the closed 1D quadrature rule (Clenshaw-Curtis or Newton-Cotes Closed).\n%\n% License:\n%\n% This software is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, controls the size of the final sparse grid.\n%\n% Input, integer POINT_NUM, the number of points in the grid, as determined\n% by SPARSE_GRID_CC_SIZE.\n%\n% Output, real GRID_WEIGHTS(POINT_NUM), the weights.\n%\n% Output, real GRID_POINTS(DIM_NUM,POINT_NUM), the points.\n%\n\n%\n% Determine the index vector, relative to the full product grid,\n% that identifies the points in the sparse grid.\n%\n grid_index = sparse_grid_cc_index ( dim_num, level_max, point_num );\n%\n% Compute the physical coordinates of the abscissas.\n%\n if ( 0 == level_max )\n order_max = 1;\n else\n order_max = 2^level_max + 1;\n end\n\n grid_point = zeros ( dim_num, point_num );\n \n for point = 1 : point_num\n for dim = 1 : dim_num\n grid_point(dim,point) = ... \n cc_abscissa ( order_max, grid_index(dim,point) + 1 );\n end\n end\n%\n% Gather the weights.\n%\n grid_weight = sparse_grid_cc_weights ( dim_num, level_max, point_num, ...\n grid_index );\n\n return\nend\nfunction grid_index = sparse_grid_cc_index ( dim_num, level_max, point_num )\n\n%*******************************************************************************\n%\n%% SPARSE_GRID_CC_INDEX indexes the points forming a sparse grid.\n%\n% Discussion:\n%\n% The points forming the sparse grid are guaranteed to be a subset\n% of a certain product grid. The product grid is formed by DIM_NUM\n% copies of a 1D rule of fixed order. The orders of the 1D rule,\n% (called ORDER_1D) and the order of the product grid, (called ORDER)\n% are determined from the value LEVEL_MAX.\n%\n% Thus, any point in the product grid can be identified by its grid index,\n% a set of DIM_NUM indices, each between 1 and ORDER_1D.\n%\n% This routine creates the GRID_INDEX array, listing (uniquely) the\n% points of the sparse grid. \n%\n% An assumption has been made that the 1D rule is closed (includes\n% the interval endpoints) and nested (points that are part of a rule\n% of a given level will be part of every rule of higher level).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer POINT_NUM, the total number of points in the grids.\n%\n% Output, integer GRID_INDEX(DIM_NUM,POINT_NUM), a list of point indices,\n% representing a subset of the product grid of level LEVEL_MAX,\n% representing (exactly once) each point that will show up in a\n% sparse grid of level LEVEL_MAX.\n%\n grid_index = zeros ( dim_num, point_num );\n%\n% The outer loop generates LEVELs from 0 to LEVEL_MAX.\n%\n point_num2 = 0;\n\n for level = 0 : level_max\n%\n% The middle loop generates the next partition LEVEL_1D(1:DIM_NUM)\n% that adds up to LEVEL.\n%\n level_1d = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n%\n% Transform each 1D level to a corresponding 1D order.\n%\n order_1d = level_to_order_closed ( dim_num, level_1d );\n%\n% The product of the 1D orders gives us the number of points in this grid.\n%\n order_nd = prod ( order_1d(1:dim_num) );\n%\n% The inner (hidden) loop generates all points corresponding to given grid.\n%\n grid_index2 = multigrid_index0 ( dim_num, order_1d, order_nd );\n%\n% Adjust these grid indices to reflect LEVEL_MAX.\n%\n grid_index2 = multigrid_scale_closed ( dim_num, order_nd, level_max, level_1d, ...\n grid_index2 );\n%\n% Determine the first level of appearance of each of the points.\n%\n grid_level = abscissa_level_closed_nd ( level_max, dim_num, order_nd, ....\n grid_index2 );\n%\n% Only keep those points which first appear on this level.\n%\n for point = 1 : order_nd\n\n if ( grid_level(point) == level )\n\n point_num2 = point_num2 + 1;\n\n grid_index(1:dim_num,point_num2) = grid_index2(1:dim_num,point);\n\n end\n\n end\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\nfunction point_num = sparse_grid_cfn_size ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_CFN_SIZE sizes a sparse grid using Closed Fully Nested rules.\n%\n% Discussion:\n%\n% The grid is defined as the sum of the product rules whose LEVEL\n% satisfies:\n%\n% 0 <= LEVEL <= LEVEL_MAX.\n%\n% This calculation is much faster than a previous method. It simply\n% computes the number of new points that are added at each level in the\n% 1D rule, and then counts the new points at a given DIM_NUM dimensional\n% level vector as the product of the new points added in each dimension.\n%\n% This approach will work for nested families, and may be extensible\n% to other families, and to mixed rules.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Output, integer POINT_NUM, the total number of unique \n% points in the grids.\n%\n\n%\n% Special case.\n%\n if ( level_max < 0 )\n point_num = 0;\n return\n end\n\n if ( level_max == 0 )\n point_num = 1;\n return\n end\n%\n% Construct the vector that counts the new points in the 1D rule.\n%\n new_1d = zeros ( level_max+1, 1 );\n\n new_1d(0+1) = 1;\n new_1d(1+1) = 2;\n\n j = 1;\n for i = 2 : level_max\n j = j * 2;\n new_1d(i+1) = j;\n end\n%\n% Count the number of points by counting the number of new points \n% associated with each level vector.\n%\n level_1d = zeros ( dim_num, 1 );\n\n point_num = 0;\n\n for level = 0 : level_max\n\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n\n point_num = point_num + prod ( new_1d(level_1d(1:dim_num)+1) );\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\nfunction grid_weight = sparse_grid_cc_weights ( dim_num, level_max, point_num, ...\n grid_index )\n\n%*******************************************************************************\n%\n%% SPARSE_GRID_CC_WEIGHTS gathers the weights.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer POINT_NUM, the total number of points in the grids.\n%\n% Input, integer GRID_INDEX(DIM_NUM,POINT_NUM), a list of point indices,\n% representing a subset of the product grid of level LEVEL_MAX,\n% representing (exactly once) each point that will show up in a\n% sparse grid of level LEVEL_MAX.\n%\n% Output, real GRID_WEIGHT(POINT_NUM), the weights\n% associated with the sparse grid points.\n%\n if ( level_max == 0 )\n grid_weight(1:point_num) = 2.0^dim_num;\n return\n end\n\n grid_weight(1:point_num) = 0.0;\n\n level_min = max ( 0, level_max + 1 - dim_num );\n\n for level = level_min : level_max\n%\n% The middle loop generates the next partition LEVEL_1D(1:DIM_NUM)\n% that adds up to LEVEL.\n%\n level_1d = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more, h, t ] = comp_next ( level, dim_num, level_1d, more, h, t );\n%\n% Transform each 1D level to a corresponding 1D order.\n%\n order_1d = level_to_order_closed ( dim_num, level_1d );\n%\n% The product of the 1D orders gives us the number of points in this grid.\n%\n order_nd = prod ( order_1d(1:dim_num) );\n%\n% Generate the indices of the points corresponding to the grid.\n%\n grid_index2 = multigrid_index0 ( dim_num, order_1d, order_nd );\n%\n% Compute the weights for this grid.\n%\n grid_weight2 = product_weights_cc ( dim_num, order_1d, order_nd );\n%\n% Adjust the grid indices to reflect LEVEL_MAX.\n%\n grid_index2 = multigrid_scale_closed ( dim_num, order_nd, level_max, ...\n level_1d, grid_index2 );\n%\n% Now determine the coefficient.\n%\n coeff = (-1)^( level_max - level ) ...\n * choose ( dim_num - 1, level_max - level );\n\n for point2 = 1 : order_nd\n\n for point = 1 : point_num\n\n if ( all ( ...\n grid_index2(1:dim_num,point2) == grid_index(1:dim_num,point) ...\n ) )\n grid_weight(point) = grid_weight(point) ...\n + coeff * grid_weight2(point2);\n break\n end\n\n end\n\n end\n\n if ( ~more )\n break\n end\n\n end\n\n end\n\n return\nend\nfunction timestamp ( )\n\n%*******************************************************************************\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\nfunction [ a, more ] = vec_colex_next2 ( dim_num, base, a, more )\n\n%*******************************************************************************\n%\n%% VEC_COLEX_NEXT2 generates vectors in colex order.\n%\n% Discussion:\n%\n% The vectors are produced in colexical order, starting with\n% (0,0,...,0),\n% (1,0,...,0),\n% ...\n% (BASE(1)-1,BASE(2)-1,...,BASE(DIM_NUM)-1).\n%\n% Example:\n%\n% DIM_NUM = 2, \n% BASE = [ 3, 3]\n%\n% 0 0\n% 1 0\n% 2 0\n% 0 1\n% 1 1\n% 2 1\n% 0 2\n% 1 2\n% 2 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dennis Stanton, Dennis White,\n% Constructive Combinatorics,\n% Springer, 1986,\n% ISBN: 0387963472,\n% LC: QA164.S79.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer BASE(DIM_NUM), the base to be used in each dimension.\n%\n% Input, integer A(DIM_NUM), except on the first call, this should\n% be the output value of A on the last call.\n%\n% Input, logical MORE, should be FALSE on the first call, and\n% thereafter should be the output value of MORE from the previous call. \n%\n% Output, integer A(DIM_NUM), the next vector.\n%\n% Output, logical MORE, is TRUE if another vector was computed.\n% If MORE is FALSE on return, then ignore the output value A, and\n% stop calling the routine.\n%\n if ( ~more )\n\n a(1:dim_num) = 0;\n more = 1;\n\n else\n \n for i = 1 : dim_num\n\n a(i) = a(i) + 1;\n\n if ( a(i) < base(i) )\n return\n end\n\n a(i) = 0;\n\n end\n\n more = 0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_cc_dataset/sparse_grid_cc_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388209992571, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6328813397347938}} {"text": "function s = resampstr(p,m,n)\n%RESAMPSTR Stratified resampling\n%\n% Description\n% S = RESAMPSTR(P) returns a new set of indices according to \n% the probabilities P. P is array of probabilities, which are\n% not necessarily normalized, though they must be\n% non-negative, and not all zero. The size of S is the size of P.\n%\n% S = RESAMPSTR(P,M,N) returns an M by N matrix.\n%\n% Default is to use no-sort resampling. For sorted resampling use\n% [PS,PI]=SORT(P);\n% S=PI(RESAMPSTR(PS));\n% Sorted re-sampling is slower but has slightly smaller\n% variance. Stratified resampling is unbiased, almost as fast as\n% deterministic resampling (RESAMPDET), and has only a slightly\n% larger variance.\n%\n% In stratified resampling indices are sampled using random\n% numbers u_j~U[(j-1)/n,j/n], where n is length of P. Compare\n% this to simple random resampling where u_j~U[0,1].\n%\n% Reference\n% Kitagawa, G., Monte Carlo Filter and Smoother for Non-Gaussian\n% Nonlinear State Space Models, Journal of Computational and\n% Graphical Statistics, 5(1):1-25, 1996.\n%\n% See also \n% RESAMPSIM, RESAMPRES, RESAMPDET\n%\n% Copyright (c) 2003-2004,2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin<2\n [m,n]=size(p);\nelseif nargin==2\n n=m;\nend\nmn=m.*n;\npn=p./sum(p(:)).*mn;\ns=zeros(m,n);\nr=rand(1,mn);\nk=0;\nc=0;\nfor i=1:numel(pn)\n c=c+pn(i);\n if c>=1\n a=floor(c);\n c=c-a;\n s(k+[1:a])=i;\n k=k+a;\n end\n if k=r(k+1)\n c=c-1;\n k=k+1;\n s(k)=i;\n end\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/mc/resampstr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6327018055184108}} {"text": "function p = prior_corrunif(varargin)\n% * PRIOR_R Correlation prior structure \n% \n% * Description:\n% \n% - REFERENCE: prior for correlation matrix\n% Barnard, J.; McCulloch, R. & li Meng, X. \n% Modelling covariance matrices in terms of standart deviations and correlations\n% with applications to shrinkage. Statistical Sinica, 2000\n%\n% - P = PRIOR_CORRUNIF('PARAM1', VALUE1, ...) \n% creates the prior structure in which the\n% named parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% - P = PRIOR_CORRUNIF(P, 'PARAM1', VALUE1, ...)\n% modify a prior structure with the named parameters altered\n% with the specified values.\n%\n% - Parameters for correlation prior [default]\n% nu - degree of freedom [15]\n% prior_nu - prior for nu [prior_fixed]\n%\n% - some inverse-Wishart properties\n% if W ~ InvWish_d (v, A) then E[W] = A/(v-d-1)\n% nu > = d\n% d = number os species (dimension of the square matrix)\n% the construction for this prior assumes A = I.\n% \n% - dimension of the correlation vector: (numberClass^2 - numberClass)/2\n%\n% * See also\n% PRIOR_*\n%\n% Copyright (c) 2000-2001,2010 Aki Vehtari\n% Copyright (c) 2009,2015 Jarno Vanhatalo\n% Copyright (c) 2010 Jaakko Riihimäki\n% ------------ 2015 Marcelo Hartmann \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 = 'PRIOR_CORRUNIF';\n ip.addOptional('p', [], @isstruct);\n ip.addParamValue('nu', 15, @(x) isscalar(x) && x > 0);\n ip.addParamValue('prior_nu', [], @(x) isstruct(x) || isempty(x));\n ip.addParamValue('numberClass', 2, @(x) mod(x, 1) == 0 && x > 1);\n ip.addParamValue('aValue', 1, @(x) isreal(x) && x > 0);\n ip.parse(varargin{:});\n p = ip.Results.p;\n \n if isempty(p)\n init = true;\n p.type = 'CORRUNIF';\n \n else\n if ~isfield(p, 'type') && ~isequal(p.type, 'CORRUNIF')\n error('First argument does not seem to be a valid prior structure')\n end\n \n init = false;\n end\n\n % transformation to the real line (aValue stretches or squeeze the real line).\n p.aValue = ip.Results.aValue;\n \n % Initialize parameters\n % check the condition nu > numberSpecies\n if init || ~ismember('nu', ip.UsingDefaults)\n p.nu = ip.Results.nu;\n end\n \n if init || ~ismember('numberClass', ip.UsingDefaults)\n p.numberClass = ip.Results.numberClass;\n p.vectSize = (p.numberClass^2 - p.numberClass)/2;\n end\n \n if p.nu < (p.numberClass - 1)\n error('Degrees of freedom (nu) should be greater than number of classes')\n end\n \n % Initialize prior structure\n if init\n p.p = [];\n end\n if init || ~ismember('nu_prior', ip.UsingDefaults)\n p.p.nu = ip.Results.prior_nu;\n end\n \n if init\n % set functions\n p.fh.pak = @prior_corrunif_pak;\n p.fh.unpak = @prior_corrunif_unpak;\n % p.fh.RealToRho = @prior_corrunif_RealToRho;\n p.fh.lp = @prior_corrunif_lp;\n p.fh.lpg = @prior_corrunif_lpg;\n p.fh.recappend = @prior_corrunif_recappend;\n end\n\nend\n\nfunction [w, s, h] = prior_corrunif_pak(p)\n% This is a mandatory subfunction used for example \n% in energy and gradient computations.\n \n w = []; s = {}; h = [];\n \n if ~isempty(p.p.nu)\n w = [w p.nu];\n s = [s; 'R.nu'];\n h = [h 1];\n end\n \nend\n\nfunction [p, w] = prior_corrunif_unpak(p, w)\n% This is a mandatory subfunction used for example \n% in energy and gradient computations.\n\n if ~isempty(p.p.nu)\n i1 = 1;\n p.nu = w(i1);\n w = w(i1 + 1:end);\n end\n \nend\n\nfunction lp = prior_corrunif_lp(x, p)\n% This is a mandatory subfunction used for example \n% in energy computations.\n\n % Evaluating log-prior(R)\n % correlation vector\n rho = x'; \n \n % create entries\n seq = 1:p.vectSize;\n i = ceil(0.5 + 0.5 * sqrt(1 + 8*(seq)));\n j = seq - (i - 2).*(i - 1)/2;\n ind1 = (j - 1) * p.numberClass + i;\n ind2 = (i - 1) * p.numberClass + j;\n \n % build correlation matrix\n R = eye(p.numberClass); \n\n % filling elements in lower and upper part\n R([ind1, ind2]) = [rho; rho];\n detR = det(R);\n \n if eps < detR && ~any(abs(rho) > 1) \n % cholesk decompostion\n L = chol(R, 'lower');\n \n % parameters of the distribution\n a = 0.5*(p.nu - 1)*(p.numberClass - 1) - 1;\n b = - p.nu/2;\n \n % building principal submatrices and evaluating log determinant\n sDetlogSub = 0;\n for k = 1:p.numberClass\n A = R;\n A(:, k) = []; A(k, :) = [];\n Lsub = chol(A, 'lower');\n sDetlogSub = sDetlogSub + sum(log(diag(Lsub)));\n end\n \n % evaluating unnormalized log-prior\n lp = 2 * (a*sum(log(diag(L))) + b*sDetlogSub);\n \n else\n lp = -Inf;\n \n end\n\n% adding log-hyperprior(nu)\nif ~isempty(p.p.nu)\n lp = lp + p.p.nu.fh.lp(p.nu, p.p.nu) + log(p.nu);\nend\n\nend\n\nfunction lpg = prior_corrunif_lpg(x, p)\n% This is a mandatory subfunction used for example \n% in gradient computations.\n \n % taking the correlation vector\n rho = x';\n \n % creating entries\n seq = 1:p.vectSize;\n i = ceil(0.5 + 0.5 * sqrt(1 + 8*(seq)));\n j = seq - (i - 2).*(i - 1)/2;\n ind1 = (j - 1) * p.numberClass + i;\n ind2 = (i - 1) * p.numberClass + j;\n \n % building corr matrix\n R = eye(p.numberClass); \n \n % filling elements in lower and upper part\n R([ind1, ind2]) = [rho; rho];\n \n % all(eig(R) > 0)\n if ~any(abs(rho) > 1)\n \n % grad vector\n lpg = ones(1, p.vectSize);\n \n % cholesk decompostion\n % L = chol(R, 'lower');\n \n % parameters of the distribution\n a = 0.5*(p.nu - 1)*(p.numberClass - 1) - 1;\n b = - p.nu/2;\n \n % building principal submatrices and evaluating log determinant\n invR = inv(R);\n \n % COULD WE USE COFACTOR MATRIX ?\n % Id1 = eye(p.numberClass-1);\n aux = 0;\n \n for j = 2:p.numberClass\n for i = 1:(j-1)\n sumtrDer = 0;\n sumtrDer = sumtrDer + 2*a*invR(j, i);\n for k = 1:p.numberClass \n if k == i || k == j\n % sumtrDer = sumtrDer + 0;\n continue\n else\n A = R;\n A(:, k) = []; A(k, :) = [];\n % L = chol(A, 'lower');\n invAk = inv(A); \n if k < j && (i == 1 || k > i)\n m = j-1;\n sumtrDer = sumtrDer + 2*b*invAk(m, i);\n elseif k < j && k < i \n l = i-1; \n m = j-1;\n sumtrDer = sumtrDer + 2*b*invAk(m, l);\n else\n sumtrDer = sumtrDer + 2*b*invAk(j, i);\n end\n end\n end\n aux = aux + 1;\n lpg(aux) = sumtrDer;\n end\n end\n \n else\n lpg = repmat(-Inf, 1, p.vectSize);\n end\n \n if ~isempty(p.p.nu)\n lpgnu = p.p.nu.fh.lpg(p.nu, p.p.nu).*p.nu + 1;\n lpg = [lpg lpgnu];\n end\nend\n\nfunction rec = prior_corrunif_recappend(rec, ri, p)\n% This subfunction is needed when using MCMC sampling (gp_mc).\n% The parameters are not sampled in any case.\n\nrec = rec;\nif ~isempty(p.p.nu)\n rec.nu(ri,:) = p.nu;\nend\n\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/prior_corrunif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6327017988383403}} {"text": "function cvt_test04 ( )\n\n%*****************************************************************************80\n%\n%% CVT_TEST04 repeats test 1 with uniform initialization and Halton sampling.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST04\\n' );\n fprintf ( 1, ' CVT computes a Centroidal Voronoi Tessellation.\\n' );\n fprintf ( 1, ' Repeat test 1, but with Halton sampling.\\n' );\n\n dim_num = 2;\n n = 10;\n batch = 1000;\n init = 0;\n init_string = 'uniform';\n it_max = 40;\n it_fixed = 1;\n sample = 1;\n sample_num = 10000;\n sample_string = 'halton';\n seed = 123456789;\n r = [];\n\n seed_init = seed;\n\n [ r, seed, it_num, it_diff, energy ] = cvt ( dim_num, n, batch, init, ...\n sample, sample_num, it_max, it_fixed, seed, r );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Dimension DIM_NUM = %12d\\n', dim_num );\n fprintf ( 1, ' Number of points N = %12d\\n', n );\n fprintf ( 1, ' Initial SEED = %12d\\n', seed_init );\n fprintf ( 1, ' Current SEED = %12d\\n', seed );\n fprintf ( 1, ' INIT = \"%s\".\\n', init_string );\n fprintf ( 1, ' Max iterations IT_MAX = %12d\\n', it_max );\n fprintf ( 1, ' IT_FIXED (fixed samples) = %12d\\n', it_fixed );\n fprintf ( 1, ' Iterations IT_NUM = %12d\\n', it_num );\n fprintf ( 1, ' Difference IT_DIFF = %14f\\n', it_diff );\n fprintf ( 1, ' CVT ENERGY = %14f\\n', energy );\n fprintf ( 1, ' SAMPLE = \"%s\".\\n', sample_string );\n fprintf ( 1, ' Samples SAMPLE_NUM = %12d\\n', sample_num );\n fprintf ( 1, ' Sampling BATCH size = %12d\\n', batch );\n fprintf ( 1, ' EPSILON (unit roundoff) = %12e\\n', eps );\n \n r8mat_transpose_print ( dim_num, n, r, ' Generators (rows):' );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cvt/cvt_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.632669857453124}} {"text": "function [blockedIrrRxns, sol, tol] = findBlockedIrrRxns(model, tol, varargin)\n% find all blocked irreversible reactions by solving one single LP problem:\n% min sum(z_pos + z_neg)\n% s.t. Sv = 0\n% lb <= v <= ub\n% v_j + tol*z_pos_j >= tol for each reaction j with lb_j >= 0\n% v_j - tol*z_neg_j <= -tol for each reaction j with ub_j <= 0\n%\n% USAGE:\n% [blockedIrrRxns, fluxes] = findBlockedIrrRxns(model, tol, parameters)\n%\n% INPUT:\n% model: COBRA model\n%\n% OPTIONAL INPUTL\n% tol: tolerance for zeros (default feasTol*10, use default if the input is smaller)\n% parameters: COBRA and solver-specific parameters, as a input structure or parameter/value inputs\n%\n% OUTPUTS:\n% blockedIrrRxns: cell array of blocked irreversible reactions\n% sol: solution structure from solveCobraLP\n% tol: tolerance for zeros used (might be different from the input)\n\nif nargin < 2\n tol = 0;\nend\n\n[~, cobraParams, solverVarargin] = parseCobraVarargin(varargin, {}, {}, {}, {'LP'});\n% if tol < feasTol * 10, v, z_pos, z_neg = 0 may be feasible due to tolerance\ntol = max([tol, cobraParams.LP.feasTol * 10]);\n\nLP = struct();\nif 0\n rxnFwdOnly = find(model.lb >= 0);\n rxnRevOnly = find(model.ub <= 0);\nelse\n %avoid reactions bound at zero\n rxnFwdOnly = find(model.lb >= 0 & model.ub>0);\n rxnRevOnly = find(model.ub <= 0 & model.lb<0);\nend\n[nF, nR] = deal(numel(rxnFwdOnly), numel(rxnRevOnly));\n[m, n] = size(model.S);\nLP.A = [model.S, sparse(m, nF + nR); ... % Sv = 0\n sparse(1:nF, rxnFwdOnly, 1, nF, n), sparse(1:nF, 1:nF, tol, nF, nF + nR); ... % v + tol*z_pos >= tol\n sparse(1:nR, rxnRevOnly, 1, nR, n), sparse(1:nR, (nF + 1):(nF + nR), -tol, nR, nF + nR)]; % v - tol*z_neg <= -tol\nLP.b = [model.b; tol * ones(nF, 1); -tol * ones(nR, 1)];\nLP.c = [zeros(n, 1); ones(nF + nR, 1)];\nLP.lb = [model.lb; zeros(nF + nR, 1)];\nLP.ub = [model.ub; ones(nF + nR, 1)];\nLP.csense = [repmat('E', m, 1); repmat('G', nF, 1); repmat('L', nR, 1)];\nLP.osense = 1;\n\nsol = solveCobraLP(LP, solverVarargin.LP{:});\n\nif sol.stat ~= 1\n warning('The model is infeasible')\n blockedIrrRxns = {};\n return\nend\n\nblockedIrrRxns = model.rxns((abs(sol.full(1:n)) < tol * (1 - cobraParams.LP.optTol)) & (model.lb >= 0 | model.ub <= 0));\n\n\n ", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/exploration/findBlockedIrrRxns.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6326492311102506}} {"text": "% maximally flat delay LC filter pp 323 A. I. Zveref \n% Copyright 2004-2013 The MathWorks, Inc.\nR=8; % load resistance\nfc=80e3; % bandpass corner\n\nw=2*pi*fc;\n\nc1=1.5012; l2=0.978; c3=.612;l4=.211; % Rs=inf, Rl = 1 \n% scale for freq and impedance ...\nC1=c1/(R*w)\nL2=l2*R/w\nC3=c3/(R*w)\nL4=l4*R/w\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1320-analog-mixed-signal-examples/circuit_level/bessel_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.632580878715135}} {"text": "function [A] = tapas_uniqc_spm_matrix(P, order)\n% Return an affine transformation matrix\n% copy of spm_matrix from Version 6906 (SPM12) 20-Oct-16\n% FORMAT [A] = spm_matrix(P [,order])\n% P(1) - x translation\n% P(2) - y translation\n% P(3) - z translation\n% P(4) - x rotation about - {pitch} (radians)\n% P(5) - y rotation about - {roll} (radians)\n% P(6) - z rotation about - {yaw} (radians)\n% P(7) - x scaling\n% P(8) - y scaling\n% P(9) - z scaling\n% P(10) - x affine\n% P(11) - y affine\n% P(12) - z affine\n%\n% order - application order of transformations [Default: 'T*R*Z*S']\n%\n% A - affine transformation matrix\n%__________________________________________________________________________\n%\n% spm_matrix returns a matrix defining an orthogonal linear (translation,\n% rotation, scaling or affine) transformation given a vector of\n% parameters (P). By default, the transformations are applied in the\n% following order (i.e., the opposite to which they are specified):\n%\n% 1) shear\n% 2) scale (zoom)\n% 3) rotation - yaw, roll & pitch\n% 4) translation\n%\n% This order can be changed by calling spm_matrix with a string as a\n% second argument. This string may contain any valid MATLAB expression\n% that returns a 4x4 matrix after evaluation. The special characters 'S',\n% 'Z', 'R', 'T' can be used to reference the transformations 1)-4)\n% above. The default order is 'T*R*Z*S', as described above.\n%\n% SPM uses a PRE-multiplication format i.e. Y = A*X where X and Y are 4 x n\n% matrices of n coordinates.\n%__________________________________________________________________________\n%\n% See also: tapas_uniqc_spm_imatrix.m\n%__________________________________________________________________________\n% Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n\n\n\n%-Special case: translation only\n%--------------------------------------------------------------------------\nif numel(P) == 3\n A = eye(4);\n A(1:3,4) = P(:);\n return;\nend\n \n%-Pad P with 'null' parameters\n%--------------------------------------------------------------------------\nq = [0 0 0 0 0 0 1 1 1 0 0 0];\nP = [P q((length(P) + 1):12)];\n\n%-Translation / Rotation / Scale / Shear\n%--------------------------------------------------------------------------\nT = [1 0 0 P(1);\n 0 1 0 P(2);\n 0 0 1 P(3);\n 0 0 0 1];\n\nR1 = [1 0 0 0;\n 0 cos(P(4)) sin(P(4)) 0;\n 0 -sin(P(4)) cos(P(4)) 0;\n 0 0 0 1];\n\nR2 = [cos(P(5)) 0 sin(P(5)) 0;\n 0 1 0 0;\n -sin(P(5)) 0 cos(P(5)) 0;\n 0 0 0 1];\n\nR3 = [cos(P(6)) sin(P(6)) 0 0;\n -sin(P(6)) cos(P(6)) 0 0;\n 0 0 1 0;\n 0 0 0 1];\n\nR = R1*R2*R3;\n\nZ = [P(7) 0 0 0;\n 0 P(8) 0 0;\n 0 0 P(9) 0;\n 0 0 0 1];\n\nS = [1 P(10) P(11) 0;\n 0 1 P(12) 0;\n 0 0 1 0;\n 0 0 0 1];\n\n%-Affine transformation matrix\n%--------------------------------------------------------------------------\nif nargin < 2\n A = T*R*Z*S;\nelse\n A = eval(sprintf('%s;', order));\n if ~isnumeric(A) || ~isequal(size(A),[4 4])\n error('tapas:uniqc:SpmMatrix:InvalidOrderExpression', ...\n 'Invalid order expression ''%s''.', order);\n end\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/utils/compatibility/tapas_uniqc_spm_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6325608094731775}} {"text": "% MRC_scheme.m\n% Receiver diversity - MRC \nclear, clf\nL_frame=130;\nN_packet=4000; \nb=2; % Set to 1/2/3/4 for BPSK/QPSK/16QAM/64QAM\nSNRdBs=[0:2:20]; \nsq2=sqrt(2);\n%SNRdBs=[0:10:20]; sq2=sqrt(2);\nfor iter=1:3\n if iter==1\n NT=1;\n NR=1; \n gs='-kx'; % SISO\n elseif iter==2\n NT=1; \n NR=2; \n gs='-^'; \n else\n NT=1;\n NR=4; \n gs='-ro'; \n end\n sq_NT=sqrt(NT);\n for i_SNR=1:length(SNRdBs)\n SNRdB=SNRdBs(i_SNR); \n sigma=sqrt(0.5/(10^(SNRdB/10)));\n for i_packet=1:N_packet\n symbol_data=randi([0,1],L_frame*b,NT);\n [temp,sym_tab,P]=modulator(symbol_data.',b);\n X=temp.';\n Hr = (randn(L_frame,NR)+j*randn(L_frame,NR))/sq2;\n H = reshape(Hr,L_frame,NR);\n Habs = sum(abs(H).^2,2); \n Z=0;\n for i=1:NR\n R(:,i) = sum(H(:,i).*X,2)/sq_NT + sigma*(randn(L_frame,1)+j*randn(L_frame,1));\n Z = Z + R(:,i).*conj(H(:,i));\n end\n for m=1:P\n d1(:,m)=abs(sum(Z,2)-sym_tab(m)).^2+(-1+sum(Habs,2))*abs(sym_tab(m))^2;\n end\n [y1,i1] = min(d1,[],2); \n Xd=sym_tab(i1).';\n temp1 = X>0; \n temp2 = Xd>0;\n noeb_p(i_packet)=sum(sum(temp1~=temp2));\n end\n BER(iter,i_SNR) = sum(noeb_p)/(N_packet*L_frame*b);\n end\n semilogy(SNRdBs,BER(iter,:),gs);\n hold on;\n axis([SNRdBs([1 end]) 1e-6 1e0])\nend\ntitle('BER perfoemancde of MRC Scheme');\nxlabel('SNR[dB]');\nylabel('BER') \ngrid on;\nset(gca,'fontsize',9)\nlegend('SISO','MRC (Tx:1,Rx:2)','MRC (Tx:1,Rx:4)')\n", "meta": {"author": "LyricYang", "repo": "MIMO_OFDM", "sha": "df25e1837bc4019f2bbcd946bc49b0942827a847", "save_path": "github-repos/MATLAB/LyricYang-MIMO_OFDM", "path": "github-repos/MATLAB/LyricYang-MIMO_OFDM/MIMO_OFDM-df25e1837bc4019f2bbcd946bc49b0942827a847/第10章 天线分集与空时编码技术/瑞利衰落信道下MRC性能/MRC_scheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6325607908779026}} {"text": "function [Btuph] = TW2Btuph(TW)\n% Convert power from terawatts to British thermal units per hour. \n% Chad A. Greene 2012\nBtuph = TW*3.412141633e+12;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/TW2Btuph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770431, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6325294778656754}} {"text": "% Gives estimate of T0-normalized LF parameters given an Rd value\n%\n% Description\n% The Rd shape parameter [1] of the Liljencrants-Fant (LF) glottal model [2]\n% expresses a regression of the original shape parameters {te,tp,ta}. This\n% function gives the shape parameters {te,tp,ta} which correspond to a given Rd\n% value.\n%\n% Input\n% Rd : The Rd shape parameter to convert.\n%\n% Output\n% te : Glottal shape parameter, see [1]p.6 (assuming T0=1 ! (T0-normalized))\n% tp : Glottal shape parameter, see [1]p.6 (assuming T0=1 ! (T0-normalized))\n% ta : Glottal shape parameter, see [1]p.6 (assuming T0=1 ! (T0-normalized))\n%\n% See Also\n% gfm_spec_lf.m\n% \n% References\n% [1] G. Fant, \"The LF-model revisited. Transformations and frequency domain\n% analysis\", STL-QPSR 36(2-3):119-156, 1995.\n% [2] G. Fant, J. Liljencrants and Q. Lin, \"A four-parameter model of glottal\n% flow\", STL-QPSR, vol. 4, pp. 1-13, 1985.\n%\n% Copyright (c) 2011 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 [te tp ta] = Rd2tetpta(Rd)\n\n\tRap = (-1+4.8.*Rd)/100; % [1](2)\n\tRkp = (22.4+11.8.*Rd)/100; % [1](3)\n\tRgp = 1./(4*((0.11.*Rd./(1/2+1.2.*Rkp))-Rap)./Rkp); % [1] indirectly (4)\n\n\ttp = 1./(2.*Rgp); % [1]p.121\n\tte = tp.*(Rkp+1); % [1]p.121\n\tta = Rap; % [1]p.121\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/glottal_models/Rd2tetpta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6325294778541687}} {"text": "function t = logtform(rmin, rmax, nr, nw)\n% LOGTFORM makes a log-polar transform structure for imtransform\n% T = LOGTFORM(RMIN, RMAX, NR, NW) returns the transform structure for\n% a system with minimum ring radius RMIN, maximum ring radius RMAX, NR\n% rings and NR wedges. The empty matrix may be given for any one (but\n% only one) of these in which case the circular-samples condition\n% RMAX=RMIN*exp(2*pi*(NR-1)/NW) will be applied (with an adjustment\n% to RMIN if necessary to make NR and NW integers.\n%\n% See also LOGSAMPLE, LOGSAMPBACK\n\n% Copyright David Young 2010\n\n[rmin, rmax, nr, nw, k] = complete_args(rmin, rmax, nr, nw);\ntdata = struct('rmin', rmin, 'rmax', rmax, 'nr', nr, 'nw', nw, 'k', k);\nt = maketform('custom', 2, 2, @contorth, @rthtocon, tdata);\nend\n\nfunction x = contorth(u, t)\n% Conventional to log-polar. See maketform.\ntd = t.tdata;\n[th, p] = cart2pol(u(:,1), u(:, 2));\np(~p) = td.rmin/2; % Omit centre point\nx = [td.k * log(p/td.rmin), td.nw*mod(th/(2*pi), 1)];\nend\n\nfunction u = rthtocon(x, t)\n% Log-polar to conventional. See maketform.\ntd = t.tdata;\np = td.rmin * exp(x(:, 1)/td.k);\nth = (2*pi/td.nw) * x(:, 2);\n[x, y] = pol2cart(th, p);\nu = [x, y];\nend\n\nfunction [rmin, rmax, nr, nw, k] = complete_args(rmin, rmax, nr, nw)\n% Circular pixels condition\nif isempty(rmin)\n k = nw / (2*pi);\n rmin = rmax * exp((1-nr)/k);\nelseif isempty(rmax)\n k = nw / (2*pi);\n rmax = rmin * exp((nr-1)/k);\nelseif isempty(nw)\n k = (nr-1) / log(rmax/rmin);\n nw = round(2 * pi * k);\n k = nw / (2*pi);\n rmin = rmax * exp((1-nr)/k);\nelseif isempty(nr)\n k = nw / (2*pi);\n nr = round(k * log(rmax/rmin) + 1);\n rmin = rmax * exp((1-nr)/k);\nelse\n k = (nr-1) / log(rmax/rmin);\nend\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/27023-log-polar-image-sampling/logtform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6324845727085838}} {"text": "function [xyZ,sigma,gammaVal]=ellips2PolarStereo(latLon,lambda0,k0,xyPole,a,f)\n%%ELLIPS2POLARSTEREO Convert a point on the reference ellipsoid in\n% ellipsoidal (geodetic) coordinates gives as a latitude and a\n% longitude into a point on the polar stereographic projection.\n% Stereographic projections tend to be used near the poles. The\n% Uniform Polar Stereographic (UPS) coordinate system, which is\n% a specific realization of the polar stereographic coordinate\n% system, is typically only used at latitudes >=84 degrees and\n% those < -80 degrees.\n%\n%INPUTS: latLon A 2XN set of N [latitude;longitude] pairs given in radians\n% to be converted into polar stereographic coordinates.\n% lambda0 The location in raidns of the central meridian. If this\n% parameter is omitted or an empty matrix is passed, the\n% default of 0 is used, which is the value used in the UPS\n% system.\n% k0 The unitless central scale factor. If this parameter is\n% omitted or an empty matrix is passed, then the default of\n% 0.994 is used, which is the value used in the UPS.\n% xyPole A 2X1 vector holding the false Easting and False\n% Northing of the origin. This is typically given in meters.\n% If this parameter is omitted or an empty matrix is passed,\n% then the default of [2000000;2000000] is used, which is the\n% value in meters used for the UPS system.\n% a The semi-major axis of the reference ellipsoid. If this\n% argument is omitted, the value in\n% Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the reference ellipsoid. If this\n% argument is omitted, the value in Constants.WGS84Flattening\n% is used.\n%\n%OUTPUTS: xyZ A 3XN set of points in polar stereographic coordinates\n% consisting of [Easting;Northing;Z], where Z=sign(latitude),\n% so 1 for the northern hemisphere and -1 for the southern\n% hemisphere and 0 on the equator. Easting and Northing will be\n% in meters if a and xyPole are in meters.\n% sigma The NX1 set of point scales. This indicates how the map\n% projections enlarges or reduces small distances in this type\n% of map projection.\n% gammaVal The NX1 set of convergence of meridians in radians. This\n% gives the angles of intersection between the meridian and\n% vertical lines on the map projection that are given by\n% x=constant value. This value\n%\n%If lambda0, k0, xyPole, a and f are all omitted, then the conversion is\n%for the UPS on the WGS-84 reference ellipsoid.\n%\n%Chapter 21 of [1] discusses the polar stereographic projection. The\n%implementation is taken from Sections 8 and 9 of [1]. Section 10 of 2\n%provides the values for the UPS.\n%\n%REFERENCES:\n%[1] J. P. Snyder, \"Map projections- a working manual,\" U.S. Geological\n% Survey, Tech. Rep. 1395, 1987.\n%[2] Office of Geomatics, \"National geospatial-intelligence agency\n% standardization document: Implementation practice: The universal\n% grids and the transverse mercator and polar stereographic map\n% projections,\" National Geospatial-Intelligence Agency, Tech. Rep.\n% NGA.SIG.0012 2.0.0 UTMUPS, 25 Mar. 2014. [Online]. Available:\n% http://earth-info.nga.mil/GandG/publications/NGA_SIG_0012_2_0_0_UTMUPS/NGA.SIG.0012_2.0.0_UTMUPS.pdf\n%\n%July 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(lambda0))\n lambda0=0;%Central meridian location for UPS.\nend\n\nif(nargin<3||isempty(k0))\n k0=0.994;%Central scale factor for UPS\nend\n\nif(nargin<4||isempty(xyPole))\n xyPole=[2000000;2000000];%Easting and Northing of the pole for UPS.\nend\n\nif(nargin<5||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(nargin<6||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\n%The first numerical eccentricity of the ellipsoid.\ne=sqrt(2*f-f^2);\n\nN=size(latLon,2);\n\nxyZ=zeros(3,N);\nsigma=zeros(N,1);\ngammaVal=zeros(N,1);\nfor curPoint=1:N\n phi=latLon(1,curPoint);\n lambda=latLon(2,curPoint);\n lambda=lambda-lambda0;\n\n Z=sign(phi);\n if(Z==-1)\n phi=-phi;\n end\n\n sinPhi=sin(phi);\n sinLambda=sin(lambda);\n cosLambda=cos(lambda);\n\n [sinChi,cosChi]=ellipsLat2SinCosConformLat(phi,f);\n\n k90=sqrt(1-e^2)*exp(e*atanh(e));\n denom=k90*(1+sinChi);\n x=2*k0*a*sinLambda*cosChi/denom;\n y=-2*k0*a*cosLambda*cosChi/denom;\n sigma(curPoint)=k0*2*sqrt(1-e^2*sinPhi^2)*exp(e*atanh(e*sinPhi))/(k90*(1+sinPhi));\n gammaVal(curPoint)=lambda;\n\n if(Z==-1)\n y=-y;\n gammaVal(curPoint)=-gammaVal(curPoint);\n end\n\n xyZ(:,curPoint)=[x;y;Z]+[xyPole;0];\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/ellips2PolarStereo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6324845626359528}} {"text": "%kvpml 'Estimate Fractal Dimension of Image Based on P(m,L) (K1)'\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vpml.pane file\n%\n% Parameters: \n% InputFile: i 'Input Image ', required: 'input image'\n% Integer: l 'Lower window size', default: 3: 'select the initial size of the sliding window'\n% Integer: u 'Upper window size', default: 5: 'select the final size of the sliding window'\n% Integer: s 'Window step size ', default: 2: 'select the window step size or interval'\n% Integer: q 'Range of moments ', default: 3: 'select the range of moments (-r/2 <= 0 >= r/2)'\n% OutputFile: o1 'Output Image ', required: 'resulting multiband fractal dimension output image'\n% OutputFile: o2 'Output FD Image ', required: 'output image specifying fractal dimension of each class'\n% OutputFile: f1 'Output ASCII File', optional: 'output file for P(m,L) statistics'\n%\n% Example: [o1, o2, f1] = kvpml(i, {'i','';'l',3;'u',5;'s',2;'q',3;'o1','';'o2','';'f1',''})\n%\n% Khoros helpfile follows below:\n%\n% PROGRAM\n% vpml - Estimate Fractal Dimension of Image Based on P(m,L) (K1)\n%\n% DESCRIPTION\n% .I vpml\n% estimates the fractal dimension of an image based on the probability \n% that there are m pixels within a window of size L centered on a pixel \n% from a particular class. For a selected range of window sizes (L), \n% the window is centered on the first occurrence of the pixel belonging \n% to a particular class. The number of pixels within a window of size L, \n% belonging to a specific class are counted (including the center pixel \n% of the window), and a \"histogram\" is formed as the window is moved over \n% the image. This \"histogram\" represents the total number of occurrences,\n% m, of a class of pixels in a window of size L. From this, a normalized \n% histogram is formed, which yields an estimate of the probability density \n% function, P(m,L), for each window size L. \n% \n% All selected moments (q) of the P(m,L) distributions for each of the \n% desired window sizes are determined, and a linear regression or \"best fit\n% line\" is found for the moment generating function, log(M(L))^1/q, versus\n% the log of the window size, log(L). The slope of the \"best fit line\"\n% provides an estimate for the fractal dimension, D.\n% \n% The center pixel of the largest window, Lmax, is replaced with the computed\n% fractal dimension based on the probability density function, P(m,L).\n% The largest window size, Lmax, determines the resulting size of the fractal\n% dimension image. This results in a border of size (Lmax / 2) around the\n% image, which is set to zero. \n% \n% The input arguments are described as follows:\n% \n% \"-i\" 15\n% specifies the input image, which must be of data type BYTE or INTEGER. \n% The input image must be a single band image.\n% \n% \"-o1\" 15\n% specifies the output image, which will be a multiband image representing\n% the fractal dimension of the input image for each of the specified\n% moments. The resulting output image will be of data storage type\n% FLOAT, and will have a border of pixels of value zero. The size of\n% the border will be determined by the size of the largest window\n% specified. This can be determined from the following formulation,\n% (Lmax -1) / 2 = border size. Where Lmax is the size of the largest\n% window used. For example, if the largest window size is 9, then the\n% border size will be (9 - 1) / 2 = 4 pixels.\n% \n% \"-o2\" 15\n% specifies fractal dimension image, representing the fractal dimension \n% vectors for each class and moment. This image will always have a row \n% size of 1 and a column size determined by the number of classes in the\n% input image. The number of data bands will be equal to the number of\n% moments used in the estimation of the fractal dimension.\n% \n% \"-f1\" 15\n% uses an ASCII file as output for the image information specifying the\n% size of the input image, number of classes in the input image, and the\n% range of moments used in the estimation of the fractal dimension. Also\n% included is a listing of the fractal dimensions for each class and \n% moment.\n% \n% \"-l\" 15\n% specifies the initial or lower size of the sliding window. This MUST be\n% an odd number resulting in a window with a center pixel. This means that\n% the minimum size of the sliding window is 3 x 3. The default value is\n% 3, resulting in an initial window size of 3 x 3.\n% \n% \"-u\" 15\n% specifies the final or upper size of the sliding window. This MUST also\n% be an odd number resulting in a window with a center pixel. The size of\n% the upper window MUST be at least one step greater than the lower window\n% size. That is, if the lower window is 3 x 3, then the minimum size of \n% the upper window must be 5 x 5, or one step greater than the lower window.\n% This is necessary, since there must be at least two points for a best\n% fit line to be formed determining the slope and ultimately the fractal\n% dimension.\n% \n% \"-s\" 15\n% specifies the step size or interval used when specifying a range of\n% window sizes. The default value is two, corresponding to the next odd\n% window size with a center pixel. This may be helpful when a wide range \n% of window sizes is required, as it will reduce the number of points \n% generated for the best fit line and hence the number of calculations.\n% \n% \"-q\" 15\n% specifies the range of moments to base the P(m,L) fractal dimension\n% calculations on. This must be an odd number, corresponding to the\n% number of moments centered on zero. For example, a value of 5 would\n% result in the computation of the fractal dimension for the range of\n% moments, -2, -1, 0, 1, 2. The default value is 3, resulting in the\n% range of -1, 0, 1.\n% \n% The input image MUST be of data storage type BYTE or INTEGER.\n%\n% \n%\n% EXAMPLES\n% \n% vpml -i in_img -o1 out_img1 -o2 out_img2 -f1 file1 -u 11 -s 4 -q 5\n% this will estimate the fractal dimension of the in_img using a\n% range of sliding window sizes from 3 x 3 (default lower value of 3)\n% to an upper size of 11 x 11, with a step size of 4. This means that\n% windows of size 3 x 3, 7 x 7, and 11 x 11 will be used in the fractal\n% dimension calculation. A value of 5 was selected for the number of\n% moments to be calculated, meaning that the fractal dimension will be\n% computed for the range of moments, -2, -1, 0, 1, 2. The resulting\n% output image, out_img1 will consist of a five-band FLOAT image with \n% each band representing the fractal dimension for a particular moment, q.\n% The out_img2 will consist of a single row, five-band image specifying \n% the fractal dimension for each class of the input image and moment, q.\n% The ASCII file1 will provide the user with information on the size of \n% the input image, number of classes, and the resulting fractal dimensions \n% for each class and moment.\n%\n% \"SEE ALSO\"\n% vfractal(1)\n%\n% RESTRICTIONS \n% \n% The input image MUST be of data storage type BYTE or INTEGER. \n% The output images are of data storage type FLOAT.\n%\n% REFERENCES \n% A reference for the pml algorithm is p. 67 of The Science of Fract.\n% Images edited by Hienz-Otto Peitgen and Dietmar Saupe.\n%\n% COPYRIGHT\n% Copyright (C) 1993 - 1997, Khoral Research, Inc. (\"KRI\") All rights reserved.\n% \n\n\nfunction varargout = kvpml(varargin)\nif nargin ==0\n Inputs={};arglist={'',''};\nelseif nargin ==1\n Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kvpml(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i', '__input';'l', 3;'u', 5;'s', 2;'q', 3;'o1', '__output';'o2', '__output';'f1', '__output'};\nmaxval={0,10000,10000,10000,1000,0,0,1};\nminval={0,3,5,2,3,0,0,1};\nistoggle=[0,1,1,1,1,0,0,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','Integer','Integer','Integer','Integer','OutputFile','OutputFile','OutputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=2; nextinput=1; nextoutput=1;\n for ii=1:size(arglist,1)\n wasmatched=0;\n for jj=1:size(narglist,1)\n if strcmp(arglist{ii,1},narglist{jj,1}) % a given argument was matched to the possible arguments\n wasmatched = 1;\n was_set(jj) = 1;\n if strcmp(narglist{jj,2}, '__input')\n if (nextinput > length(Inputs)) \n error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n end\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n elseif strcmp(narglist{jj,2}, '__output')\n if (nextoutput > nargout) \n error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n end\n if (isempty(arglist{ii,2}))\n narglist{jj,2} = 'OK_out';\n else\n narglist{jj,2} = arglist{ii,2};\n end\n\n nextoutput = nextoutput + 1;\n if (minval{jj} == 0) \n NumReqOutputs = NumReqOutputs - 1;\n end\n elseif isstr(arglist{ii,2})\n narglist{jj,2} = arglist{ii,2};\n else\n if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n end\n if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n end\n end\n end\n if ~strcmp(narglist{jj,2},'OK_out') & ~strcmp(narglist{jj,2},'OK_in') \n narglist{jj,2} = arglist{ii,2};\n end\n end\n end\n if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n if strcmp(paramtype{jj}, 'Toggle')\n if (narglist{jj,2} ==0)\n narglist{jj,1} = ''; \n end;\n narglist{jj,2} = ''; \n end;\n if ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n narglist{jj,1} = ''; \n narglist{jj,2} = ''; \n end;\n if strcmp(narglist{jj,2}, '__input')\n if (minval{jj} == 0) % meaning this input is required\n if (nextinput > size(Inputs)) \n error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n else\n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n end\n else % this is an optional input\n if (nextinput <= length(Inputs)) \n narglist{jj,2} = 'OK_in';\n nextinput = nextinput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end;\n else \n if strcmp(narglist{jj,2}, '__output')\n if (minval{jj} == 0) % this is a required output\n if (nextoutput > nargout & nargout > 1) \n error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n else\n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n NumReqOutputs = NumReqOutputs-1;\n end\n else % this is an optional output\n if (nargout - nextoutput >= NumReqOutputs) \n narglist{jj,2} = 'OK_out';\n nextoutput = nextoutput + 1;\n else \n narglist{jj,1} = '';\n narglist{jj,2} = '';\n end;\n end\n end\n end\nend\nif nargout\n varargout = cell(1,nargout);\nelse\n varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'vpml\" '],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kvpml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6324845573259962}} {"text": "function pic_serial ( )\n\n%*****************************************************************************80\n%\n%% PIC_SERIAL applies the Particle in Cell method to an electrostatic problem.\n%\n% Discussion:\n%\n% Simple Electrostatic Particle In Cell (PIC) code in MATLAB\n% Flow of solar wind around a charged plate\n%\n% For more, visit http://www.particleincell.com/2010/es-pic-method/\n% and http://www.particleincell.com/2011/particle-in-cell-example/\n%\n% Modified:\n%\n% 27 July 2013\n%\n% Parameters:\n%\n% Local, real A(NX*NY,NX*NY), the finite difference stencil matrix.\n%\n% Local, real ACC, the acceleration experienced by a particle.\n%\n% Local, real AMU, the atomic mass unit.\n%\n% Local, integer BOX(2,2), the indices of the lower left and upper right \n% corners of the internal obstruction.\n%\n% Local, real CHG(NX,NY), the charge distribution.\n%\n% Local, real DEBYE, the Debye length.\n%\n% Local, real DEN(NX,NY), the charge density.\n%\n% Local, real DH, the \"diameter\" of a single cell.\n%\n% Local, real DT, the time step.\n%\n% Local, real E(2), the electric field experienced by a particle.\n%\n% Local, real EFX(NX,NY), the X component of the electric field.\n%\n% Local, real EFY(NX,NY), the Y component of the electric field.\n%\n% Local, real EPS0, the permittivity of free space.\n%\n% Local, real F, the Lorentz force experienced by a particle.\n%\n% Local, real FLUX, the flux of entering particles.\n%\n% Local, real K, the Boltzmann constant.\n% Oddly enough, this value seems never to be used.\n%\n% Local, real M, the ion mass for molecular oxygen.\n%\n% Local, real MP_Q, the macro-particle charge.\n%\n% Local, integer N0, the average particle density per cubic meter.\n%\n% Local, integer NN, the total number of nodes.\n%\n% Local, integer NP, the number of particles.\n%\n% Local, integer NP_INSERT, the number of (computational) particles inserted\n% per time step.\n%\n% Local, real NPT, the number of real particles created per time step.\n%\n% Local, integer NX, the number of nodes in the X direction.\n%\n% Local, integer NY, the number of nodes in the Y direction.\n%\n% Local, integer PART_MAX, the maximum number of particles.\n% Here, this is set to 20,000.\n%\n% Local, real PART_V(NP,2), the X and Y velocities for each particle.\n%\n% Local, real PART_X(NP,2), the X and Y coordinates for each particle.\n%\n% Local, real PHI(NX,NY), the potential.\n%\n% Local, real PHI_P, the wall potential.\n%\n% Local, real PHI0, the reference potential.\n%\n% Local, real QE, the elementary charge.\n%\n% Local, integer SEED, a seed for the random number generator.\n%\n% Local, real SPWT, the specific weight, real particles per macroparticle.\n%\n% Local, integer STEP, the current time step.\n%\n% Local, integer STEP_NUM, the number of time steps.\n%\n% Local, real TE, the electron temperature in eV.\n%\n% Local, real TI, the ion velocity in eV.\n%\n% Local, real V_DRIFT, the ion injection velocity, 7 km/s.\n%\n% Local, real VTH, the thermal velocity.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PIC_SERIAL\\n' );\n fprintf ( 1, ' MATLAB version.\\n' );\n fprintf ( 1, ' Apply the Particle in Cell (PIC) method to\\n' );\n fprintf ( 1, ' an electrostatic problem that models the flow of\\n' )\n fprintf ( 1, ' the \"solar wind\" around an electrically charged plate.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' It is worth considering how to turn this serial program\\n' );\n fprintf ( 1, ' into one that uses parallel programming techniques.\\n' );\n%\n% Initialize the random number generator.\n%\n seed = 123456789;\n% rng ( seed );\n%\n% Set physical constants.\n%\n eps0 = 8.854e-12;\n qe = 1.602e-19;\n k = 1.381e-23;\n amu = 1.661e-27;\n m = 32.0 * amu;\n%\n% Set problem parameters.\n%\n n0 = 1.0e12;\n phi0 = 0.0;\n te = 1.0;\n ti = 0.1;\n v_drift = 7000.0;\n phi_p = -5.0;\n%\n% Calculate plasma parameters.\n%\n debye = sqrt ( eps0 * te / ( n0 * qe ) );\n vth = sqrt ( 2.0 * qe * ti / m );\n%\n% Set the simulation domain.\n%\n nx = 16;\n ny = 10;\n nn = nx * ny;\n step_num = 200;\n dh = debye;\n np_insert = ( ny - 1 ) * 15;\n%\n% Compute other quantities.\n%\n dt = 0.1 * dh / v_drift;\n width = ( nx - 1 ) * dh;\n height = ( ny - 1 ) * dh;\n%\n% Indices of the corners of the obstruction.\n%\n ox1 = floor ( nx / 3 );\n ox2 = floor ( nx / 3 ) + 2;\n oy1 = 1;\n oy2 = floor ( ny / 2 );\n%\n% Indices of the corners of the obstruction, in an array.\n%\n box(1,1) = floor ( nx / 3 );\n box(1,2) = floor ( nx / 3 ) + 2;\n box(2,1) = 1;\n box(2,2) = floor ( ny / 2 );\n%\n% Calculate the specific weight.\n%\n flux = n0 * v_drift * height;\n npt = flux * dt;\n spwt = npt / np_insert;\n mp_q = 1.0;\n part_max = 20000;\n%\n% Allocate particle arrays.\n% \n part_x = zeros(part_max,2);\n part_v = zeros(part_max,2);\n%\n% Set the finite difference stencil matrix.\n%\n A = stencil ( nx, ny, dh, box );\n\n phi = ones ( nx, ny ) * phi0;\n\n np = 0;\n%\n% Time loop\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Time Particles\\n' );\n fprintf ( 1, '\\n' );\n\n for step = 1 : step_num\n%\n% 1. CALCULATE THE CHARGE DENSITY.\n%\n chg = zeros(nx,ny);\n\n for p = 1 : np\n\n fi = 1.0 + part_x(p,1) / dh;\n i = floor ( fi );\n hx = fi - i;\n\n fj = 1.0 + part_x(p,2) / dh;\n j = floor ( fj );\n hy = fj - j;\n\n chg(i, j) = chg(i, j) + ( 1.0 - hx ) * ( 1.0 - hy );\n chg(i+1,j) = chg(i+1,j) + hx * ( 1.0 - hy );\n chg(i, j+1) = chg(i, j+1) + ( 1.0 - hx ) * hy;\n chg(i+1,j+1) = chg(i+1,j+1) + hx * hy;\n\n end\n%\n% Calculate the density.\n% Along the boundaries, the calculated density must be doubled.\n% Add a density floor for plotting, and to help the solver.\n%\n den(1:nx,1:ny) = spwt * mp_q * chg(1:nx,1:ny) / ( dh * dh );\n\n den(1,:) = 2.0 * den(1,:);\n den(nx,:) = 2.0 * den(nx,:);\n den(:,1) = 2.0 * den(:,1);\n den(:,ny) = 2.0 * den(:,ny);\n\n den = den + 10000.0;\n%\n% 2. CALCULATE THE POTENTIAL.\n%\n phi = eval_2dpot_gs ( nx, ny, phi, A, den, n0, phi0, te, phi_p, box, ...\n eps0, qe );\n%\n% 3. CALCULATE THE ELECTRIC FIELD.\n% Use central differences at internal nodes,\n% forward or backward differences at boundaries.\n%\n efx = zeros(nx,ny);\n efy = zeros(nx,ny);\n\n efx(2:nx-1,:) = ( phi(1:nx-2,:) - phi(3:nx,:) ) / ( 2.0 * dh );\n efy(:,2:ny-1) = ( phi(:,1:ny-2) - phi(:,3:ny) ) / ( 2.0 * dh );\n\n efx(1,:) = ( phi(1,:) - phi(2,:) ) / dh;\n efx(nx,:) = ( phi(nx-1,:) - phi(nx,:) ) / dh;\n efy(:,1) = ( phi(:,1) - phi(:,2) ) / dh;\n efy(:,ny) = ( phi(:,ny-1) - phi(:,ny) ) / dh;\n%\n% 4. GENERATE NEW PARTICLES\n%\n if ( part_max - np <= np_insert )\n% np_insert = part_max - np;\n end\n%\n% The new particles have coordinates randomly chosen within the first X layer,\n% and any Y layer.\n%\n part_x(np+1:np+np_insert,1) = rand ( np_insert, 1 ) * dh;\n part_x(np+1:np+np_insert,2) = rand ( np_insert, 1 ) * height;\n%\n% Sample Maxwellian in x and y, add drift velocity in x.\n%\n part_v(np+1:np+np_insert,1) = v_drift ...\n + ( - 1.5 + rand(np_insert,1) + rand(np_insert,1) ...\n + rand(np_insert,1) ) * vth;\n\n part_v(np+1:np+np_insert,2) = 0.5 ...\n * ( - 1.5 + rand(np_insert,1) + rand(np_insert,1) ...\n + rand(np_insert,1) ) * vth;\n\n np = np + np_insert;\n%\n% 5. MOVE ALL THE PARTICLES\n%\n p = 1;\n\n while ( p <= np )\n\n fi = 1.0 + part_x(p) / dh;\n i = floor ( fi );\n hx = fi - i;\n\n fj = 1.0 + part_x(p,2) / dh;\n j = floor ( fj );\n hy = fj - j;\n\n e = [ 0.0, 0.0 ];\n e = [ efx(i,j), efy(i,j) ] * ( 1.0 - hx ) * ( 1.0 - hy );\n e = e + [ efx(i+1,j), efy(i+1,j) ] * hx * ( 1.0 - hy );\n e = e + [ efx(i,j+1), efy(i+1,j) ] * ( 1.0 - hx ) * hy;\n e = e + [ efx(i+1,j+1), efy(i+1,j+1) ] * hx * hy;\n%\n% Compute the Lorentz force and the corresponding acceleration.\n% Then update the particle velocity and position.\n%\n f = qe * e;\n acc = f / m;\n part_v(p,:) = part_v(p,:) + acc * dt;\n part_x(p,:) = part_x(p,:) + part_v(p,:) * dt;\n%\n% The bottom boundary is reflective.\n%\n if ( part_x(p,2) < 0 )\n part_x(p,2) = - part_x(p,2);\n part_v(p,2) = - part_v(p,2);\n end\n%\n% Is the particle inside the plate?\n%\n in_box = ( box(1,1) <= i && i < box(1,2) && ...\n box(2,1) <= j && j < box(2,2) );\n%\n% Particle is absorbed if it passes left, right or top boundaries, \n% or is inside the plate.\n% Kill the particle by replacing it with the last particle.\n%\n if ( part_x(p,1) < 0.0 || width <= part_x(p,1) || height <= part_x(p,2) || in_box )\n part_x(p,:) = part_x(np,:);\n part_v(p,:) = part_v(np,:);\n np = np - 1;\n p = p - 1;\n end\n\n p = p + 1;\n\n end\n%\n% 6. PLOT RESULTS\n%\n if ( mod ( step, 25 ) == 0 || step == step_num )\n\n figure ( 1 );\n clf\n hold on\n contourf ( den' );\n colorbar;\n patch ( [ ox1 ox2 ox2 ox1 ], [ oy1, oy1, oy2, oy2 ], 'w' )\n title ( sprintf ( 'Density on step %i', step ), 'Fontsize', 16 );\n hold off;\n\n figure ( 2 );\n clf\n hold on\n contourf ( phi' );\n patch ( [ ox1 ox2 ox2 ox1 ], [ oy1, oy1, oy2, oy2 ], 'w' )\n title ( sprintf ( 'Potential on step %i', step ), 'Fontsize', 16 );\n colorbar;\n hold off\n\n drawnow;\n\n end\n\n fprintf ( 1, ' %6i %9i\\n', step, np );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PIC_SERIAL\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction phi = eval_2dpot_gs ( nx, ny, phi, A, den, n0, phi0, te, phi_p, ...\n box, eps0, qe )\n\n%*****************************************************************************80\n%\n%% EVAL_2DPOT_GS computes the 2D potential using Gauss-Seidel iteration.\n%\n% Discussion:\n%\n% For more information, refer to \n% http://www.particleincell.com/2010/es-pic-method/\n% and \n% http://www.particleincell.com/2011/particle-in-cell-example/\n%\n% Modified:\n%\n% 05 July 2013\n%\n% Parameters:\n%\n% Input, integer NX, NY, the number of nodes in the X and Y directions.\n%\n% Input, real PHI(NX,NY), the current potential function.\n%\n% Input, real A(NX*NY,NX*NY), the finite difference stencil matrix.\n%\n% Input, real DEN(NX,NY), the charge density.\n%\n% Input, real PHI0, the reference potential.\n%\n% Input, real TE, the electron temperature in eV.\n%\n% Input, real EPS0, the permittivity of free space.\n%\n% Input, real QE, the elementary charge.\n%\n% Output, real PHI(NX,NY), the updated potential function.\n%\n nn = nx * ny;\n%\n% Solver tolerance.\n%\n tol = 0.1;\n%\n% Convert the density and potential into column vectors.\n%\n den = reshape ( den, numel(den), 1 );\n phi = reshape ( phi, numel(phi), 1 );\n%\n% Carry out the Gauss-Seidel iteration.\n%\n for it = 1 : 2000\n% \n% Recalculate the right hand side, adding Boltzmann term for the electrons.\n%\n b = den - n0 * exp ( ( phi - phi0 ) / te );\n b = - b * qe / eps0;\n% \n% Set the boundaries.\n% Zero electric field on y = 0, y = L, x = L.\n% Fixed potential on X = 0.\n%\n b(1:nx) = 0.0;\n b(nn-nx+1:nn) = 0.0;\n b(nx:nx:nn) = 0.0;\n b(1:nx:nn) = phi0;\n%\n% Set the potential on the fixed nodes.\n%\n for j = box(2,1) : box(2,2)\n b([box(1,1):box(1,2)]+(j-1)*nx) = ones ( box(1,2)-box(1,1)+1, 1 ) * phi_p;\n end\n%\n% Apply the Gauss-Seidel update to the current solution estimate.\n%\n for i = 1 : nn\n phi(i) = ( b(i) - A(i,1:i-1) * phi(1:i-1) ...\n - A(i,i+1:nn) * phi(i+1:nn) ) / A(i,i);\n end\n%\n% Compute the residual.\n%\n if ( mod ( it, 10 ) == 0 )\n res = norm ( b - A * phi );\n if ( res <= tol )\n phi = reshape ( phi, nx, ny );\n return;\n end\n end\n\n end\n%\n% Check if the solver converged.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EVAL_2DPOT_GS - Warning\\n' );\n fprintf ( 1, ' The Gauss-Seidel iteration did not converge.\\n' );\n fprintf ( 1, ' Residual norm = %g\\n', res );\n\n phi = reshape ( phi, nx, ny );\n\n return\nend\nfunction A = stencil ( nx, ny, dh, box )\n\n%*****************************************************************************80\n%\n%% STENCIL sets up the finite difference stencil matrix.\n%\n% Modified:\n%\n% 05 July 2013\n%\n% Parameters:\n%\n% Input, integer NX, NY, the number of nodes in the X and Y directions.\n%\n% Local, real DH, the \"diameter\" of a single cell.\n%\n% Input, integer BOX(2,2), contains the coordinates of the lower left\n% and upper right corners of the box.\n%\n% Output, real A(NX*NY,NX*NY), the finite difference stencil matrix.\n%\n A = zeros ( nx*ny, nx*ny );\n%\n% For internal nodes, here are the node numberings for the\n% north, west, central, east, and south locations:\n%\n% u-nx\n% u-1 u u+1\n% u+nx\n%\n for j = 2 : ny - 1\n for i = 2 : nx - 1\n\n u = ( j - 1 ) * nx + i;\n\n A(u,u) = -4.0 / ( dh * dh );\n A(u,u-1) = 1.0 / ( dh * dh );\n A(u,u+1) = 1.0 / ( dh * dh );\n A(u,u-nx) = 1.0 / ( dh * dh );\n A(u,u+nx) = 1.0 / ( dh * dh );\n\n end \n end\n%\n% Neumann boundary on y=0\n%\n j = 1;\n for i = 1 : nx\n u = ( j - 1 ) * nx + i;\n A(u,u) = -1.0 / dh;\n A(u,u+nx) = 1.0 / dh;\n end\n%\n% Neumann boundary on y=height\n%\n j = ny;\n for i = 1 : nx\n u = ( j - 1 ) * nx + i;\n A(u,u-nx) = 1.0 / dh;\n A(u,u) = -1.0 / dh;\n end\n%\n% Neumann boundary on x=width\n%\n i = nx;\n for j = 1 : ny\n u = ( j - 1 ) * nx + i;\n A(u,:) = zeros ( 1, nx * ny );\n A(u,u-1) = 1.0 / dh;\n A(u,u) = -1.0 / dh;\n end\n%\n% Dirichlet boundary on x=0\n%\n i = 1;\n for j = 1 : ny\n u = ( j - 1 ) * nx + i;\n A(u,:) = zeros ( 1, nx * ny );\n A(u,u) = 1.0;\n end\n%\n% Dirichlet boundary on nodes corresponding to the plate\n%\n for j = box(2,1) : box(2,2)\n for i = box(1,1) : box(1,2)\n u = ( j - 1 ) * nx + i;\n A(u,:) = zeros ( 1, nx * ny );\n A(u,u) = 1.0;\n end\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pic_serial/pic_serial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6324629272974162}} {"text": "function s=AAFT(x,c)\n%Syntax: s=AAFT(x,c)\n%___________________\n%\n% Makes c Amplitude Adjusted Fourier Transformed (AAFT) surrogates of a time\n% series x.\n%\n% s is the AAFT time series.\n% x is the original time series.\n% c is the number of surrogates.\n%\n%\n% References:\n%\n% Theiler J, Galdrikian B, Longtin A, Eubank S, Farmer D J (1992): Using \n% Surrogate Data to Detect Nonlinearity in Time Series. In Nonlinear Modeling\n% and Forecasting, eds. Casdagli M & Eubank S. 163-188. Addison-Wesley\n%\n% Theiler J, Eubank S,Galdrikian B, Longtin A, Farmer D J (1992): Testing\n% for nonlinearity in time series: the method of surrogate data. Physica D\n% 58: 77-94\n%\n% \n% Alexandros Leontitsis\n% Department of Education\n% University of Ioannina\n% 45110 - Dourouti\n% Ioannina\n% Greece\n%\n% University e-mail: me00743@cc.uoi.gr\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n%\n% 12 Apr 2001.\n\nif nargin<1 | isempty(x)==1\n error('You should provide a time series.');\nelse\n % x must be a vector\n if min(size(x))>1\n error('Invalid time series.');\n end\n x=x(:);\nend\n\nif nargin<2 | isempty(c)==1\n c=1;\nelse\n % c must be scalar\n if sum(size(c))>2\n error('c must be scalar.');\n end\n % c must be greater or equal than 1\n if c<1\n error('c must be greater or equal than 1.');\n end\nend\n\nfor i=1:c\n % Initialize\n y=x;\n % Make n normal random devaiates\n normal=sort(randn(size(y)));\n % Sort y and extract the ranks\n [y,T]=sort(y);\n [T,r]=sort(T);\n % Assign the ranks of y to the normal deviates and apply the phase\n % randomization\n normal=phaseran(normal(r));\n % Extract the ranks of the phase randomized normal deviates\n [normal,T]=sort(normal);\n [T,r]=sort(T);\n % Assign the ranks of the phase randomized normal deviates to y and\n % obtain the AAFT surrogates\n s(:,i)=y(r);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1597-chaotic-systems-toolbox/AAFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6324438916585683}} {"text": "function [ xy, w ] = triangle_nco_rule ( rule, order_num )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NCO_RULE returns the points and weights of an NCO rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Peter Silvester,\n% Symmetric Quadrature Formulae for Simplexes,\n% Mathematics of Computation,\n% Volume 24, Number 109, January 1970, pages 95-100.\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n%\n% Input, integer ORDER_NUM, the order (number of points) of the rule.\n%\n% Output, real XY(2,ORDER_NUM), the points of the rule.\n%\n% Output, real W(ORDER_NUM), the weights of the rule.\n%\n\n%\n% Get the suborder information.\n%\n suborder_num = triangle_nco_suborder_num ( rule );\n\n suborder = triangle_nco_suborder ( rule, suborder_num );\n\n [ suborder_xyz, suborder_w ] = triangle_nco_subrule ( rule, suborder_num );\n%\n% Expand the suborder information to a full order rule.\n%\n o = 0;\n\n for s = 1 : suborder_num\n\n if ( suborder(s) == 1 )\n\n o = o + 1;\n xy(1:2,o) = suborder_xyz(1:2,s);\n w(o) = suborder_w(s);\n\n elseif ( suborder(s) == 3 )\n\n for k = 1 : 3\n o = o + 1;\n xy(1,o) = suborder_xyz ( i4_wrap(k, 1,3), s );\n xy(2,o) = suborder_xyz ( i4_wrap(k+1,1,3), s );\n w(o) = suborder_w(s);\n end\n\n elseif ( suborder(s) == 6 )\n\n for k = 1 : 3\n o = o + 1;\n xy(1,o) = suborder_xyz ( i4_wrap(k, 1,3), s );\n xy(2,o) = suborder_xyz ( i4_wrap(k+1,1,3), s );\n w(o) = suborder_w(s);\n end\n\n for k = 1 : 3\n o = o + 1;\n xy(1,o) = suborder_xyz ( i4_wrap(k+1,1,3), s );\n xy(2,o) = suborder_xyz ( i4_wrap(k, 1,3), s );\n w(o) = suborder_w(s);\n end\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_NCO_RULE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal SUBORDER(%d) = %d\\n', s, suborder(s) );\n error ( 'TRIANGLE_NCO_RULE - Fatal error!' );\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_nco_rule/triangle_nco_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6324438867109954}} {"text": "function value = imDynamicRange(img, bRobust, type)\n%\n%\n% value = imDynamicRange(img, bRobust, type)\n%\n%\n% Input:\n% -img: the input image\n% -bRobust: if bRobust > 0 --> robust statistics for min and max \n% luminance values. bRboust becomes the percentile!\n% -type: 'Classic', 'Michelson', and 'Weber' \n%\n% Output:\n% -value(1): dynamic range of img\n% -value(2): dynamic range of img in f-stops (if 'Classic')\n% -value(3): dynamic range of img in log10 space space (if\n% 'Classic')\n%\n% Copyright (C) 2011-20 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\nif(~exist('bRobust', 'var'))\n bRobust = 0;\nend\n\nif(~exist('type', 'var'))\n type = 'Classic';\nend\n\nif(bRobust >= 0.5)\n bRobust = 0.01; \nend\n\nL = lum(img);\n\nif(bRobust > 0.0)\n minL = MaxQuart(L, bRobust);\n maxL = MaxQuart(L, 1 - bRobust);\nelse\n minL = min(L(:));\n maxL = max(L(:));\nend\n\nif(minL < 1e-6)\n warning('minL is less than 1e-6 cd/m^2');\nend\n\nif(minL <= 0.0)\n warning('minL is 0.0 is set to the first value greater than zero.');\n\n minL = min(min(L(L > 0)));\nend\n\nswitch type\n \n case 'Classic'\n value(1) = maxL / minL; \n value(2) = log2(value(1));\n value(3) = log10(value(1)); \n \n case 'Michelson'\n value = (maxL - minL) / (maxL + minL);\n \n case 'Weber'\n value = (maxL - minL) / minL;\nend\n\nend", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Analysis/imDynamicRange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6323601890813872}} {"text": "function [Mc, Mc95, Mc90] = calc_McBest(magnitudes, binInterval)\n % CALC_MCBEST calculate best Magnitude of Completion\n % [fMc, fMc95, fMc90] = calc_McBest(magnitudes, binInterval)\n % each row of magitudes gets its own calculation\n \n % report_this_filefun();\n \n % Magnitude increment\n if ~exist('binInterval','var')\n binInterval = 0.1;\n end\n magnitudes = sort(magnitudes);\n \n \n half_bin = binInterval / 2;\n % First estimation of magnitude of completeness (maximum curvature)\n McStarts = maxCurvature(magnitudes, [-2 : binInterval : 6] , half_bin); % vectorized\n \n \n % cheat to allow this to handle multiple rows of magnitudes (independently)\n for jj = 1:size(magnitudes,2)\n valid = ~isnan(magnitudes(:,jj));\n [Mc(jj), Mc95(jj), Mc90(jj)] = calc_McBest_unvectorized(McStarts(jj), magnitudes(valid,jj), binInterval, half_bin);\n end\nend\n\nfunction [fMc, fMc95, fMc90] = calc_McBest_unvectorized(McStart, magnitudes, binInterval, half_fBin)\n magCenters = (McStart - 0.9) : binInterval : (McStart + 1.5);\n eachedge = [magCenters - half_fBin , magCenters(end) + half_fBin]; \n \n magnitudes = flipud(magnitudes); % from biggest to smallest\n nGtEdge = sum(magnitudes > eachedge((end-1) : -1 : 1)); % magnitudes(nGtEdge) gives last event above threshhold\n nGtEdge = fliplr(nGtEdge);\n too_few = nGtEdge < 25;\n \n results=nan(numel(magCenters),1);\n for idx = 1:numel(magCenters)\n if too_few(idx)\n continue\n end\n hypotheticalMc = magCenters(idx);\n results(idx) = doCalculation(magnitudes(1:nGtEdge(idx)), binInterval, hypotheticalMc);\n end\n \n % Evaluation of results\n \n % Is fMc90 available\n nSel = find(results < 10, 1, 'first' );\n if isempty(nSel)\n fMc90 = NaN;\n else\n fMc90 = magCenters(nSel);\n end\n \n % Is fMc95 available\n nSel = find(results < 5, 1 );\n if isempty(nSel)\n fMc95 = NaN;\n else\n fMc95 = magCenters(nSel);\n end\n \n % take results from bins. (I tested against discretize, and this was faster -CGR)\n \n j = find(results < 10 , 1, 'first');\n if isempty(j)\n j = find(results < 15 , 1, 'first' ); \n end\n if isempty(j)\n j = find(results < 20 , 1, 'first' ); \n end\n if isempty(j)\n j = find(results < 25 , 1, 'first' ); \n end\n fMc = magCenters(j);\n if isempty(fMc)\n fMc = NaN;\n end\nend\n\nfunction [result] = doCalculation(theseMags, binInterval, hypotheticalMc)\n fBValue = calc_bmemag(theseMags, binInterval);\n half_fBin = binInterval ./ 2;\n \n % log10(N)=A-B*M\n vMag = hypotheticalMc:binInterval:15; % Ending magnitude must be sufficiently high (???what is \"sufficently high\")\n vNumber = 10.^(log10(numel(theseMags)) - fBValue*(vMag - hypotheticalMc));\n vNumber = round(vNumber);\n \n \n % PM=vMag(1:ct);\n PMedges = [vMag-half_fBin , vMag(end)+half_fBin]; \n [bval, ~] = histcounts(theseMags, PMedges);\n b3 = cumsum(bval,'reverse'); % N for M >= (counted backwards)\n result = sum(abs(b3 - vNumber)) / sum(b3)*100; %res2\nend\n\nfunction Mc = maxCurvature(m, centers, halfBinwidth)\n % MAXCURVATURE First estimation of magnitude of completeness (maximum curvature)\n % Mc = MAXCURVATURE(m, min_max, binwidth)\n %\n % vectorized\n edges = [centers - halfBinwidth , centers(end) + halfBinwidth];\n [vEvents, ~] = histc(m, edges, 1);\n [~,idx] = max(flipud(vEvents));\n nSel = size(vEvents,1) - idx + 1;\n % nSel = find(vEvents == max(vEvents), 1, 'last' );\n Mc = centers(nSel);\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/danijel/calc/calc_McBest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6323386927748497}} {"text": "function [out] = evap_18(p1,p2,p3,S,Ep)\n%evap_18 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Exponentially declining evaporation from deficit store\n% Constraints: -\n% @(Inputs): p1 - linear scaling parameter [-]\n% p2 - linear scaling parameter [-]\n% p3 - storage scaling parameter [mm]\n% S - current storage [mm]\n% Ep - potential evapotranspiration rate [mm/d]\n\nout = p1.*exp(-1.*p2.*S./p3).*Ep;\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/evap_18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6323110853755384}} {"text": "function A = nnls_spatial(Y, A, C, active_pixel, maxN)\n%% run HALS by fixating all spatial components\n% input:\n% Y: d*T, fluorescence data\n% A: d*K, spatial components\n% C: K*T, temporal components\n% active_pixel: d*T binary matrix, indicating the nonzero elements of A\n% maxN: scalar, maximum number of neurons overlapping at one pixel\n% output:\n% A: d*K, updated spatial components\n\n% Author: Pengcheng Zhou, Carnegie Mellon University, adapted from Johannes\n\n%% options for HALS\nd = size(Y, 1); \nK = size(C, 1); \nif nargin<5; maxN = 5; end; %maximum iteration number\nif nargin<4; active_pixel=true(d, K);\nelseif isempty(active_pixel)\n active_pixel = true(d, K);\nelse\n active_pixel = logical(active_pixel);\nend; %determine nonzero pixels\n\n%% initialization\nYmean = mean(Y,2); \nY = bsxfun(@minus, Y, Ymean); \nC = bsxfun(@minus, C, mean(C,2)); \nCC = C*C';\nYC = C*Y';\nind_fit = find(sum(active_pixel,2)>1e-9);\nA = zeros(size(A)); \n\n%% updating\nfor m=1:length(ind_fit)\n ind = active_pixel(ind_fit(m), :);\n A(ind_fit(m), ind) = nnls(CC(ind, ind), YC(ind, ind_fit(m)), [], 1e-4, maxN);\nend\n\n\nfunction s = nnls(A, b, s, tol, maxIter)\n%% fast algorithm for solving nonnegativity constrained least squared\n% problem minize norm(y-K*s, 2), s.t. s>=0.\n\n%% inputs:\n% A: n x p matrix, K'*K\n% b: n x 1 vector, K'*y\n% s: p x 1 vector, warm started s\n% tol: scalar, smallest nonzero values\n% maxIter: scalar, maximum nonzero values\n\n%% outputs:\n% s: p x 1 vector, solution\n\n%% Authors: Pengcheng Zhou, Carnegie Mellon University, 2016\n% ported from the Python implementation from Johannes Friedrich\n\n%% References\n% Friedrich J et.al., NIPS 2016, Fast Active Set Method for Online Spike Inference from Calcium Imaging\n% Bro R & Jong S, Journal of Chemometrics 1997, A FAST NON-NEGATIVITY-CONSTRAINED LEAST SQUARES ALGORITHM\n\n%% input arguments\np = size(A,2); % dimension of s\nif ~exist('s', 'var') || isempty(s)\n s = zeros(p, 1);\nend\nif ~exist('tol', 'var') || isempty(tol)\n tol = 1e-9;\nend\nif ~exist('maxIter', 'var') || isempty(maxIter)\n maxIter = p;\nend\nif sum(s>0)>maxIter\n s = zeros(p,1);\nend\nfor miter=1:maxIter\n l = b - A*s; % negative gradient\n Pset = (s>0); % passive set\n \n if max(l) < tol % no more passive set\n break;\n end\n \n [~, temp] = max(l); % choose the one with the largest gradient\n Pset(temp) = true; % add it to the passive set\n if sum(Pset)>maxIter\n break;\n end\n % correct nonnegativity violations\n while any(Pset)\n % run unconstrained least squares for variables in passive sets\n try\n mu = A(Pset, Pset) \\ b(Pset);\n catch\n mu = (A(Pset, Pset) + tol*eye(sum(Pset))) \\ b(Pset);\n end\n \n if all(mu>tol)\n break;\n end\n \n temp = s(Pset) ./ (s(Pset)-mu);\n temp(mu>tol) = [];\n a = min(temp);\n s(Pset) = s(Pset) + a*(mu-s(Pset));\n Pset(s10\n\t\tum=-0.3;\n\tend;\n\t[ng,ng]=size(G);\n\trvec=[eyp(i);-yf;xm;um];\n\tv1=Qp*eyp(i)-Qf*yf;\n\tup=inv(eye(ng)-G*rvec'*Tbar*rvec)*(xout(i,[6:9])+v1*rvec'*Tbar)*rvec;\n\tv=v1+G*up;\n\tkp=v*rvec'*Tbar;\n\tkpe(i)=kp(1,1);\n\tkpf(i)=kp(1,2);\nend;\n\nz=max(length(tout),length(ym(1,:)));\nif z>length(tout)\n\tfor i=length(tout):length(ym(1,:))\n\t\ttout(i,:)=tout((length(tout)),:);\n\tend;\nend;\nfigure(1)\nplot(tout,yp,tout,ym,'--')\naxis([0 20 -.5 .5])\ntext(.41, 1.05, 'Ym', 'color', [1 0 1], 'FontSize', 12, 'Units', 'normal');\ntext(.51, 1.05, 'Yp', 'color', [1 1 0], 'FontSize', 12, 'Units', 'normal');\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/6262-direct-adaptive-control-algorithms-theory-and-applications-2e-companion-software/kaufman/ex2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.632310754875463}} {"text": "%sculling (essentially sculling+rotation) correction for each minor\n%interval\n%gyro & acc must be increment type (3,length) outputs. alg is the desired\n%sculling algorithm\nfunction [vinc, ainc, corr]=sculling_minor(gyro, acc, alg)\ninlen=size(acc,2);\nswitch (alg)\n case (0)\n %ignagni(1998):algorithm 1 -> (1996):algo2\n outlen=floor((inlen-3)/2)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=3:2:inlen\n vinc(:,ind)=sum(acc(:,i-1:i),2);\n ainc(:,ind)=sum(gyro(:,i-1:i),2);\n \n rot=0.5*cross(ainc(:,ind), vinc(:,ind));\n vr_a=cross(((-1/30)*gyro(:,i-2)+(11/15)*gyro(:,i-1)), acc(:,i));\n vr_b=cross(((-1/30)*acc(:,i-2)+(11/15)*acc(:,i-1)), gyro(:,i));\n corr(:,ind)=rot+vr_a+vr_b;\n ind=ind+1;\n end\n case (1)\n %ignagni(1998):algorithm 2 -> (1996):algo3\n outlen=floor((inlen-3)/3)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=3:3:inlen\n vinc(:,ind)=sum(acc(:,i-2:i),2);\n ainc(:,ind)=sum(gyro(:,i-2:i),2);\n \n rot=0.5*cross(ainc(:,ind), vinc(:,ind));\n vr_a=cross(((9/20)*gyro(:,i-2)+(27/20)*gyro(:,i-1)), acc(:,i));\n vr_b=cross(((9/20)*acc(:,i-2)+(27/20)*acc(:,i-1)), gyro(:,i));\n corr(:,ind)=rot+vr_a+vr_b;\n ind=ind+1;\n end\n case(2)\n %ignagni(1998):algorithm 3 -> (1996):algo5\n outlen=floor((inlen-4)/3)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=4:3:inlen\n vinc(:,ind)=sum(acc(:,i-2:i),2);\n ainc(:,ind)=sum(gyro(:,i-2:i),2);\n \n rot=0.5*cross(ainc(:,ind), vinc(:,ind));\n vr_a=cross(((3/280)*gyro(:,i-3)+(57/140)*gyro(:,i-2)+(393/280)*gyro(:,i-1)), acc(:,i));\n vr_b=cross(((3/280)*acc(:,i-3)+(57/140)*acc(:,i-2)+(393/280)*acc(:,i-1)), gyro(:,i));\n corr(:,ind)=rot+vr_a+vr_b;\n ind=ind+1;\n end\n case(3)\n %ignagni(1998):algorithm 4 -> (1996):algo6\n outlen=floor((inlen-5)/3)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=5:3:inlen\n vinc(:,ind)=sum(acc(:,i-2:i),2);\n ainc(:,ind)=sum(gyro(:,i-2:i),2);\n \n rot=0.5*cross(ainc(:,ind), vinc(:,ind));\n vr_a=cross(((-1/420)*gyro(:,i-4)+(1/40)*gyro(:,i-3)+(157/420)*gyro(:,i-2)+(1207/840)*gyro(:,i-1)), acc(:,i));\n vr_b=cross(((-1/420)*acc(:,i-4)+(1/40)*acc(:,i-3)+(157/420)*acc(:,i-2)+(1207/840)*acc(:,i-1)), gyro(:,i));\n corr(:,ind)=rot+vr_a+vr_b;\n ind=ind+1;\n end\n case(4)\n %ignagni(1998):algorithm 5 -> (1996):algo7\n outlen=floor((inlen-4)/4)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n\n ind=1;\n for i=4:4:inlen\n vinc(:,ind)=sum(acc(:,i-3:i),2);\n ainc(:,ind)=sum(gyro(:,i-3:i),2);\n \n rot=0.5*cross(ainc(:,ind), vinc(:,ind));\n vr_a=cross(((54/105)*gyro(:,i-3)+(92/105)*gyro(:,i-2)+(214/105)*gyro(:,i-1)), acc(:,i));\n vr_b=cross(((54/105)*acc(:,i-3)+(92/105)*acc(:,i-2)+(214/105)*acc(:,i-1)), gyro(:,i));\n corr(:,ind)=rot+vr_a+vr_b;\n ind=ind+1;\n end\n case(5) %%quadratic fit to both gyro and accel outputs (similar to the coning algorithm in ignagni(1990):algoD\n outlen=floor((inlen-3)/3)+1;\n vinc=zeros(3,outlen);\n ainc=zeros(3,outlen);\n corr=zeros(3,outlen);\n \n \n ind=1;\n for i=3:3:inlen\n vinc(:,ind)=sum(acc(:,i-2:i),2);\n ainc(:,ind)=sum(gyro(:,i-2:i),2);\n \n %compute the polynomial coefficients\n b=(11/6)*gyro(:,i-2)+(-7/6)*gyro(:,i-1)+(1/3)*gyro(:,i);\n c=(-2)*gyro(:,i-2)+(3)*gyro(:,i-1)+(-1)*gyro(:,i);\n d=(1/2)*gyro(:,i-2)+(-1)*gyro(:,i-1)+(1/2)*gyro(:,i);\n \n e=(11/6)*acc(:,i-2)+(-7/6)*acc(:,i-1)+(1/3)*acc(:,i);\n f=(-2)*acc(:,i-2)+(3)*acc(:,i-1)+(-1)*acc(:,i);\n g=(1/2)*acc(:,i-2)+(-1)*acc(:,i-1)+(1/2)*acc(:,i);\n \n %Compute sculling(+rotation)\n corr(:,ind)=(3^2/2)*cross(b,e)+(3^3/3)*(cross(b,f)+cross(c,e)/2)+(3^4/4)*(cross(b,g)+cross(c,f)/2+cross(d,e)/3)+...\n (3^5/5)*(cross(c,g)/2+cross(d,f)/3)+(3^6/6)*cross(d,g)/3;\n \n ind=ind+1;\n end\n \n otherwise\n disp('undefined algorithm');\nend\n\n\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/conscull/sculling_minor_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6323018650148579}} {"text": "function indx = r8vec2_sort_heap_index_a ( n, x, y )\n\n%*****************************************************************************80\n%\n%% R8VEC2_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R8VEC2.\n%\n% Discussion:\n%\n% An R8VEC2 is two R8VEC's.\n%\n% An R8VEC is a vector of R8 values.\n%\n% The sorting is not actually carried out. Rather an index array is\n% created which defines the sorting. This array may be used to sort\n% or index the array, or to sort or index related arrays keyed on the\n% original array.\n%\n% ( X(I), Y(I) ) < ( X(J), Y(J) ) if:\n%\n% * X(I) < X(J), or\n%\n% * X(I) = X(J), and Y(I) < Y(J).\n%\n% Once the index array is computed, the sorting can be carried out\n% \"implicitly:\n%\n% ( X(INDX(1:N)), Y(INDX(1:N) ), is sorted,\n%\n% or explicitly, by the call\n%\n% call dvec_permute ( n, x, indx )\n% call dvec_permute ( n, y, indx )\n%\n% after which ( X(1:N), Y(1:N) ), is sorted.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the array.\n%\n% Input, real X(N),Y(N), pairs of X, Y coordinates of points.\n%\n% Output, integer INDX(N), the sort index. The\n% I-th element of the sorted array has coordinates ( X(INDX(I)), Y(INDX(I) ).\n%\n if ( n < 1 )\n indx = [];\n return\n end\n\n indx(1:n) = 1 : n;\n\n if ( n == 1 )\n return\n end\n\n l = floor ( n / 2 ) + 1;\n ir = n;\n\n while ( 1 )\n\n if ( 1 < l )\n\n l = l - 1;\n indxt = indx(l);\n xval = x(indxt);\n yval = y(indxt);\n\n else\n\n indxt = indx(ir);\n xval = x(indxt);\n yval = y(indxt);\n indx(ir) = indx(1);\n ir = ir - 1;\n\n if ( ir == 1 )\n indx(1) = indxt;\n break\n end\n\n end\n\n i = l;\n j = l + l;\n\n while ( j <= ir )\n\n if ( j < ir )\n\n if ( x(indx(j)) < x(indx(j+1)) || ...\n ( x(indx(j)) == x(indx(j+1)) && y(indx(j)) < y(indx(j+1)) ) )\n j = j + 1;\n end\n\n end\n\n if ( xval < x(indx(j)) || ...\n ( xval == x(indx(j)) && yval < y(indx(j)) ) )\n indx(i) = indx(j);\n i = j;\n j = j + j;\n else\n j = ir + 1;\n end\n\n end\n\n indx(i) = indxt;\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec2_sort_heap_index_a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.6322094943930513}} {"text": "function normals = vertexNormal(vertices, faces)\n%VERTEXNORMAL Compute normals to a mesh vertices.\n%\n% N = vertexNormal(V, F)\n% Computes vertex normals of the mesh given by vertices V and F. \n% V is a vertex array with 3 columns, F is either a NF-by-3 or NF-by-4\n% index array, or a cell array with NF elements.\n%\n% Example\n% % Draw the vertex normals of a sphere\n% s = [10 20 30 40];\n% [v f] = sphereMesh(s);\n% drawMesh(v, f);\n% view(3);axis equal; light; lighting gouraud;\n% normals = vertexNormal(v, f);\n% drawVector3d(v, normals);\n%\n% See also \n% meshes3d, meshFaceNormals, triangulateFaces\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-12-19, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\nnv = size(vertices, 1);\nnf = size(faces, 1);\n\n% unit normals to the faces\nfaceNormals = normalizeVector3d(meshFaceNormals(vertices, faces));\n\n% compute normal of each vertex: sum of normals to each face\nnormals = zeros(nv, 3);\nif isnumeric(faces)\n for i = 1:nf\n face = faces(i, :);\n for j = 1:length(face)\n v = face(j);\n normals(v, :) = normals(v,:) + faceNormals(i,:);\n end\n end\nelse\n for i = 1:nf\n face = faces{i};\n for j = 1:length(face)\n v = face(j);\n normals(v, :) = normals(v,:) + faceNormals(i,:);\n end\n end\nend\n\n% normalize vertex normals to unit vectors\nnormals = normalizeVector3d(normals);\n\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/meshes3d/vertexNormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.6321677945685482}} {"text": "% Constructing a random graph based on a given degree sequence.\n% Idea source: Molloy M. & Reed, B. (1995) Random Structures and Algorithms 6, 161-179\n% \n% INPUTs: a graphic sequence of numbers, 1xn\n% OUTPUTs: adjacency matrix of resulting graph, nxn\n% \n% Note: The simple version of this algorithm gets stuck about half\n% of the time, so in this implementation the last problematic\n% edge is rewired.\n%\n% Other routines used: adj2edgeL.m, rewireThisEdge.m, edgeL2adj.m\n% GB: last updated, Oct 25 2012\n\n\nfunction adj= randomGraphFromDegreeSequence(Nseq)\n\n\nstubs=Nseq; % assign degrees to stubs\nadj = zeros(length(Nseq)); % initialize adjacency matrix\n\n\nold_sum = 0;\ncnt=0;\n\nwhile sum(stubs)>0 % while no more stubs are left to connect\n \n if cnt>5 % if rewiring did not work 5 times\n \n el = adj2edgeL(adj);\n ind = find(stubs>0);\n \n if length(ind) == 1; elr = rewireThisEdge([el; ind(1) ind(1) 1],ind(1),ind(1)); end\n if length(ind) == 2; elr = rewireThisEdge([el; ind(1) ind(2) 1; ind(2) ind(1) 1],ind(1),ind(2)); end\n \n if length(ind)>2 || isempty(elr) % restart algorithm\n printf('randomGraphFromDegreeSequence(): restarting ...\\n')\n stubs = Nseq;\n adj = zeros(length(Nseq));\n old_sum = 0;\n cnt=0;\n \n else\n adj = edgeL2adj(elr); % return matrix with last edge rewired\n return\n \n end\n \n end\n \n \n new_sum = sum(stubs);\n \n if old_sum==new_sum; cnt = cnt+1; end % no new nodes have been connected, counter+1\n if old_sum~=new_sum; cnt=0; end % new connections, restart count\n \n \n [~,n1] = max(stubs); % pick the node with highest number of remaining stubs\n \n old_sum = sum(stubs);\n \n ind = find(stubs>0);\n n2 = ind(randi(length(ind)));\n \n if n1==n2; continue; end % no self-loops\n \n if adj(n1,n2)>0; continue; end % no double edges\n adj(n1,n2)=1; adj(n2,n1)=1;\n stubs(n1) = stubs(n1) - 1;\n stubs(n2) = stubs(n2) - 1;\n \nend", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/randomGraphFromDegreeSequence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6321510364156472}} {"text": "function [ a, info ] = spofa ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% SPOFA factors a real symmetric positive definite matrix.\n%\n% Discussion:\n%\n% SPOFA is usually called by SPOCO, but it can be called\n% directly with a saving in time if RCOND is not needed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the symmetric matrix to be factored. Only the \n% diagonal and upper triangle are used.\n%\n% Input, integer LDA, the leading dimension of the array A.\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(LDA,N), an upper triangular matrix R so that A = R'*R\n% where R' is the transpose. The strict lower triangle is unaltered.\n% If INFO /= 0, the factorization is not complete.\n%\n% Output, integer INFO, error flag.\n% 0, for normal return.\n% K, signals an error condition. The leading minor of order K is not \n% positive definite.\n%\n for j = 1 : n\n\n s = 0.0;\n\n for k = 1 : j-1\n t = a(k,j) - sdot ( k-1, a(1:k-1,k), 1, a(1:k-1,j), 1 );\n t = t / a(k,k);\n a(k,j) = t;\n s = s + t * t;\n end\n\n s = a(j,j) - s;\n\n if ( s <= 0.0 )\n info = j;\n return\n end\n\n a(j,j) = sqrt ( s );\n\n end\n\n info = 0;\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_s/spofa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6321510293789401}} {"text": "%%**********************************************************\n%% cheby0: \n%%\n%% minimize || p(d) ||_infty \n%% p = polynomial of degree <= m such that p(0) = 1.\n%% \n%% Here d = n-vector \n%%----------------------------------------------------------\n%% [blk,Avec,C,b,X0,y0,Z0,objval,p] = cheby0(d,m,solve);\n%%\n%% d = a vector. \n%% m = degree of polynomial. \n%% feas = 1 if want feasible starting point\n%% = 0 if otherwise.\n%% solve = 0 if just want initialization\n%% = 1 if want to solve the problem\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\nfunction [blk,Avec,C,b,X0,y0,Z0,objval,p] = cheby0(d,m,solve);\n\n if nargin <= 2; solve = 0; end;\n if (size(d,1) < size(d,2)); d = d.'; end;\n cmp = 1-isreal(d); \n\n tstart=cputime; \n n = length(d);\n e = ones(n,1);\n V(1:n,1) = e/norm(e); R(1,1) = 1/norm(e);\n for i =1:m \n v = d.*V(:,i); \n for j = 1:i %% Arnoldi iterations:\n H(j,i) = (V(:,j))'*v; %% constructing upper-Hessenberg matrix.\n v = v - H(j,i)*V(:,j); %% orthonormaliztion of Krylov basis.\n end;\n H(i+1,i) = norm(v);\n V(:,i+1) = v/H(i+1,i);\n R(1:i+1,i+1) = (1/H(i+1,i))*([0; R(1:i,i)] - [R(1:i,1:i)*H(1:i,i); 0]);\n end \n if (cmp)\n blk{1,1} = 'q'; blk{1,2} = 3*ones(1,n);\n C = zeros(3*n,1); C(2:3:3*n) = ones(n,1);\n b = [zeros(2*m,1); -1];\n Atmp = [];\n II = [0:3:3*n-3]'; ee = ones(n,1); \n for k=1:m\n dVk = d.*V(:,k);\n Atmp = [Atmp; [2+II, k*ee, real(dVk)]; [3+II, k*ee, imag(dVk)]]; \n Atmp = [Atmp; [2+II, (m+k)*ee, -imag(dVk)]; [3+II, (m+k)*ee, real(dVk)]]; \n end\n Atmp = [Atmp; [1+II, (2*m+1)*ee, -ones(n,1)]]; \n else\n blk{1,1} = 'l'; blk{1,2} = 2*ones(1,n);\n b = [zeros(m,1); -1];\n C = [ones(n,1); -ones(n,1)];\n Atmp = [];\n II = [1:n]'; ee = ones(n,1); \n for k=1:m\n dVk = d.*V(:,k);\n Atmp = [Atmp; [II, k*ee, dVk]; [n+II, k*ee, -dVk]]; \n end \n Atmp = [Atmp; [II, (m+1)*ee, -ee]; [n+II, (m+1)*ee, -ee]];\n end\n Avec = spconvert(Atmp);\n [X0,y0,Z0] = infeaspt(blk,Avec,C,b); \n%% \n if (solve)\n [obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);\n if (cmp)\n y = y(1:m) + sqrt(-1)*y(m+1:2*m); \n else\n y = y(1:m); \n end \n x1 = R(1:m,1:m)*y(1:m); \n p = [-x1(m:-1:1); 1]; \n objval = -mean(obj);\n else\n objval = []; p = [];\n end \n%%**********************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Examples/cheby0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6320933171894233}} {"text": "function [vdeg] = trideg2(pp,tt)\n%TRIDEG2 calc. topological degree for vertices in a 2-simpl-\n%ex triangulation.\n% [VDEG] = TRIDEG2(VERT,TRIA) returns the no. of triangles \n% incident to each vertex. VDEG is a V-by-1 array of vert-\n% ex degrees, VERT is a V-by-D array of XY coordinates, \n% and TRIA is a T-by-3 array of vertex indexing, where \n% each row defines a triangle, such that \n% VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and \n% VERT(TRIA(II,3),:) are the coordinates of the II-TH tri-\n% angle.\n%\n% See also TRISCR2, TRIVOL2, TRIANG2, TRIBAL2\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 10/07/2018\n\n%---------------------------------------------- basic checks \n if (~isnumeric(pp) || ~isnumeric(tt) )\n error('trideg2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n \n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ndims(tt) ~= +2 )\n error('trideg2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(pp,2) < +2 || size(tt,2) < +3 )\n error('trideg2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n nvrt = size(pp,1) ;\n ntri = size(tt,1) ;\n\n%---------------------------------------------- basic checks\n if (min(min(tt(:,1:3))) < +1 || ...\n max(max(tt(:,1:3))) > nvrt )\n error('trideg2:invalidInputs', ...\n 'Invalid TRIA input array.') ;\n end\n\n%------------------------------------- compute vertex degree\n vdeg = sum(sparse( ...\n tt(:,1:3),repmat( ...\n (1:ntri)',1,3),+1,nvrt,ntri),2) ;\n \nend\n\n\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/mesh-cost/trideg2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6320933166274758}} {"text": "function bas = bas3DP1(p,t)\n\n%% USAGE: coefficient of Lagrange P1 basis for tetrahedral mesh\n%\n% INPUTS:\n% p --- np-by-3 vector\n% t --- nt-by-4 vector\n%\n% OUTPUTS:\n% bas --- nt-4-4 matrix stores the coefficient of basis value(s)\n% The k-i-j th entry denotes the j-th basis function on k-th cell\n% with the i-th coefficient where c_i (i=1,2,3,4) stands for\n% c_1 + c_2*x + c_3*y + c_4*z\n\n% Last Modified: 08/07/2020 by Xu Zhang\n\n%%\nx1 = p(t(:,1),1); y1 = p(t(:,1),2); z1 = p(t(:,1),3); \nx2 = p(t(:,2),1); y2 = p(t(:,2),2); z2 = p(t(:,2),3); \nx3 = p(t(:,3),1); y3 = p(t(:,3),2); z3 = p(t(:,3),3); \nx4 = p(t(:,4),1); y4 = p(t(:,4),2); z4 = p(t(:,4),3); \n\nA = -x2.*y3.*z1 + x2.*y4.*z1 + x1.*y3.*z2 - x1.*y4.*z2 + x2.*y1.*z3 ...\n -x1.*y2.*z3 + x1.*y4.*z3 - x2.*y4.*z3 + x4.*(-y2.*z1 + y3.*z1 + ...\n y1.*z2 - y3.*z2 - y1.*z3 + y2.*z3) + (-x2.*y1 + x1.*y2 - x1.*y3 + ...\n x2.*y3).*z4 + x3.*(-y4.*z1 - y1.*z2 + y4.*z2 + y2.*(z1 - z4) + y1.*z4);\n\nnt = size(t,1); bas = zeros(nt,4,4);\nbas(:,1,1) = (-x4.*y3.*z2 + x3.*y4.*z2 + x4.*y2.*z3 - x2.*y4.*z3 - x3.*y2.*z4 + x2.*y3.*z4);\nbas(:,2,1) =-(-y3.*z2 + y4.*z2 + y2.*z3 - y4.*z3 - y2.*z4 + y3.*z4);\nbas(:,3,1) = (-x3.*z2 + x4.*z2 + x2.*z3 - x4.*z3 - x2.*z4 + x3.*z4);\nbas(:,4,1) =-(-x3.*y2 + x4.*y2 + x2.*y3 - x4.*y3 - x2.*y4 + x3.*y4);\nbas(:,1,2) =-(-x4.*y3.*z1 + x3.*y4.*z1 + x4.*y1.*z3 - x1.*y4.*z3 - x3.*y1.*z4 + x1.*y3.*z4);\nbas(:,2,2) = (-y3.*z1 + y4.*z1 + y1.*z3 - y4.*z3 - y1.*z4 + y3.*z4);\nbas(:,3,2) =-(-x3.*z1 + x4.*z1 + x1.*z3 - x4.*z3 - x1.*z4 + x3.*z4);\nbas(:,4,2) = (-x3.*y1 + x4.*y1 + x1.*y3 - x4.*y3 - x1.*y4 + x3.*y4);\nbas(:,1,3) = (-x4.*y2.*z1 + x2.*y4.*z1 + x4.*y1.*z2 - x1.*y4.*z2 - x2.*y1.*z4 + x1.*y2.*z4);\nbas(:,2,3) =-(-y2.*z1 + y4.*z1 + y1.*z2 - y4.*z2 - y1.*z4 + y2.*z4);\nbas(:,3,3) = (-x2.*z1 + x4.*z1 + x1.*z2 - x4.*z2 - x1.*z4 + x2.*z4);\nbas(:,4,3) =-(-x2.*y1 + x4.*y1 + x1.*y2 - x4.*y2 - x1.*y4 + x2.*y4);\nbas(:,1,4) =-(-x3.*y2.*z1 + x2.*y3.*z1 + x3.*y1.*z2 - x1.*y3.*z2 - x2.*y1.*z3 + x1.*y2.*z3);\nbas(:,2,4) = (-y2.*z1 + y3.*z1 + y1.*z2 - y3.*z2 - y1.*z3 + y2.*z3);\nbas(:,3,4) =-(-x2.*z1 + x3.*z1 + x1.*z2 - x3.*z2 - x1.*z3 + x2.*z3);\nbas(:,4,4) = (-x2.*y1 + x3.*y1 + x1.*y2 - x3.*y2 - x1.*y3 + x2.*y3);\nbas = bas./A;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/bas3DP1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6319474241807778}} {"text": "function [u,p] = StokesIUzawa(u,p,f,g,A,B,auxMat,elem,smootherOpt)\n%% STOKESIUzawa Inexact Uzawa smoother for the Stokes eqns.\n%\n% In matrix form, we solve the Stokes equations\n%\n% |A B'| |u| = |f|\n% |B 0 | |p| = |g|\n%\n% Define\n% M = |I -S_u^-1 B'| T = |S_u 0|\n% | I | |B -S_p|\n% The matrix form DGS update can be written as\n%\n% |uk+1| |uk| |ru| with ru = f-Auk -B'pk,\n% | | = | | + M*inv(T)*| |\n% |pk+1| |pk| |rp| and rp = 0-Buk\n%\n% Created by Ming Wang (with discussion of Long Chen) at Jan, 2012. \n% Revised at Sept 2012.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Parameters\nitStep = smootherOpt.itStep;\nSu = auxMat.DA; % DA = 2*diag(A)\nBt = auxMat.Bt;\nBinvDABt = auxMat.BinvDABt; % invDA = 1/(2*diag(A));\n% mg options\nmgoption.printlevel = 0; \nmgoption.maxIt = 1; \nmgoption.N0=50;\nmgoption.solver = 'Vcycle'; \nmgoption.mu = 2;\n\n%% DGS relaxation step\nfor k = 1: itStep\n % Step 1: relax Momentum eqns\n if isempty(u) && isempty(p)\n ru = f;\n u = zeros(size(f)); \n p = zeros(size(g));\n else\n ru = f-Bt*p-A*u;\n end\n u = u + ru./Su;\n rp = g-B*u;\n rp = rp - mean(rp);\n % Step 2: relax transformed Continuity eqns\n dp = mg(BinvDABt,-rp,elem,mgoption);\n % Step 3: transform the correction back to the original variables.\n p = p + dp;\n u = u - (Bt*dp)./Su;\nend\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/StokesIUzawa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6318956689450355}} {"text": "function rcov = cov_blockgeom(X,blocksize)\n% like cov(), just robust (using the blockwise geometric median)\n% The blocksize allows to reduce the memory requirements, at the cost of reduced robustness\n% against outliers that occupy fewer samples than the blocksize.\n\n% Copyright (C) Christian Kothe, SCCN, 2013, christian@sccn.ucsd.edu\n%\n% This program is free software; you can redistribute it and/or modify it under the terms of the GNU\n% General Public License as published by the Free Software Foundation; either version 2 of the\n% License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n% even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License along with this program; if not,\n% write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n% USA\n\nif ~exist('blocksize','var')\n blocksize = 10; end\n\n[n,m] = size(X);\nX = bsxfun(@minus,X,median(X));\nU = zeros(length(1:blocksize:n),m*m);\nfor k=1:blocksize\n range = min(n,k:blocksize:(n+k-1));\n U = U + reshape(bsxfun(@times,reshape(X(range,:),[],1,m),reshape(X(range,:),[],m,1)),size(U));\nend\nrcov = real(reshape(geometric_median(U/blocksize),m,m));\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/misc/cov_blockgeom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.631895666820877}} {"text": "function [e, edata, eprior] = rbferr(net, x, t)\n%RBFERR\tEvaluate error function for RBF network.\n%\n%\tDescription\n%\tE = RBFERR(NET, X, T) takes a network data structure NET together\n%\twith a matrix X of input vectors and a matrix T of target vectors,\n%\tand evaluates the appropriate error function E depending on\n%\tNET.OUTFN. Each row of X corresponds to one input vector and each\n%\trow of T contains the corresponding target vector.\n%\n%\t[E, EDATA, EPRIOR] = RBFERR(NET, X, T) additionally returns the data\n%\tand prior components of the error, assuming a zero mean Gaussian\n%\tprior on the weights with inverse variance parameters ALPHA and BETA\n%\ttaken from the network data structure NET.\n%\n%\tSee also\n%\tRBF, RBFFWD, RBFGRAD, RBFPAK, RBFTRAIN, RBFUNPAK\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Check arguments for consistency\nswitch net.outfn\ncase 'linear'\n errstring = consist(net, 'rbf', x, t);\ncase 'neuroscale'\n errstring = consist(net, 'rbf', x);\notherwise\n error(['Unknown output function ', net.outfn]);\nend\nif ~isempty(errstring);\n error(errstring);\nend\n\nswitch net.outfn\ncase 'linear'\n y = rbffwd(net, x);\n edata = 0.5*sum(sum((y - t).^2));\ncase 'neuroscale'\n y = rbffwd(net, x);\n y_dist = sqrt(dist2(y, y));\n % Take t as target distance matrix\n edata = 0.5.*(sum(sum((t-y_dist).^2)));\notherwise\n error(['Unknown output function ', net.outfn]);\nend\n\n% Compute Bayesian regularised error\n[e, edata, eprior] = errbayes(net, edata);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/rbferr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6317499525262912}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code.\n\nfunction y = svol_2(a, b, r, n, f, k, t)\n% computes the SABR implied BS volatility due to Hagan's formula\n\n\tz = n./a.*(f*k).^((1-b)/2).*log(f./k);\n\tx = log((sqrt(1 - 2*r*z + z.^2) + z - r)/(1-r));\n\tTerm1 = a ./ (f*k).^((1-b)/2) ./ (1 + (1-b)^2/24*log(f./k).^2 ...\n + (1-b)^4/1920*log(f./k).^4);\n\tTerm2 = z ./ x;\n\tTerm2(abs(x-z) < 1e-008) = 1; % account for ATM\n\tTerm3 = 1 + ((1-b)^2/24*a^2./(f*k).^(1-b) ...\n + r*b*n*a/4./(f*k).^((1-b)/2) + (2-3*r^2)/24*n.^2)*t;\n\ty = Term1.*Term2.*Term3;\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/svol_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.631749927530189}} {"text": "% Dasslc test problem with classical pendulum\n% requires files: pend.m\n\ndae_index = 3;\t\t% differential index of the DAE\ng = 9.8;\t\t\t% gravity acceleration\nL\t = 1.0;\t\t\t% pendulum cord lenght\nt0 = 0.0; % initial value for independent variable\ntf = 10; % final value for independent variable\ny0 = [1 0 0 0 0]'; % initial state variables (overwritten by pend.dat)\nrpar=[g L dae_index]; % optional arguments passed to residual and jacobian functions\n\nindex = [0 0 0 0 0\t% index 0 formulation (with drift-off effect)\n\t\t 1 1 1 1 1\t% index 1 formulation\n\t\t\t1 1 2 2 2\t% index 2 formulation\n 1 1 2 2 3];\t% index 3 formulation\n\ntspan=[t0:0.001:tf];\n[t,y]=dasslc('pend',tspan,y0,rpar,[],[],index(dae_index+1,:),'pend.dat','jacpend');\n\nplot(t,y);\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/17001-dasslc-mex-file-compilation-to-matlab-5-3-and-6-5/run_pend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6316714013099822}} {"text": "function [varargout]=repop(varargin)\n% Replicating arithemetical and logical operators.\n%\n% [Z]=repop(X,operator,Y [,options])\n%\n% Does element by element operations on X and Y where non-same sized\n% dimensions are implicity wrapped round to match the size of the larger\n% to give a result matrix Z with size max(size(X),size(Y));\n%\n% What this means is that if you give a [Nx1] and a [1xM] input you get \n% a [NxM] output, or if you give it a [Nx1xQ] and a [NxMx1xP] you get \n% [NxMxQxP] output etc.. \n% Note that the size of the input *completely and uniquely* determines the \n% size of the output.\n%\n% In general this is at least 2x faster than the equivalent matlab code\n% using repmats and has the advantage of requiring no additional memory.\n%\n% Example Usage:\n% X = randn(10000,10); % example signal with data in rows\n% stdX = repop(X,'-',mean(X,1)); % subtract the mean vector\n% stdX = repop(stdX,'/',std(stdX,0,1)); % divide by std-deviation\n%\n% Operator can be one of:\n%\n% Arthemetical -- returns a double matrix\n% '+','.+',plus - Implicitly repmatted elementwise addition\n% '-','.-',minus - Implicitly repmatted elementwise addition\n% '*','.*',times - Implicitly repmatted elementwise multiplication\n% '^','.^',power - Implicitly repmatted elementwise raise X to power Y\n% '\\','.\\',ldivide- Implicitly repmatted elementwise divide Y by X\n% '/','./',rdivide- Implicitly repmatted elementwise divide X by Y\n% 'min' - Implicitly repmatted elementwise min of X by Y\n% 'max' - Implicitly repmatted elementwise max of X by Y\n%\n% Relational -- returns a logical matrix\n% N.B. for complex inputs the <,>,<=,>= operators are based upon abs(x) \n% (not real(x) as in matlab)\n% '==',eq - Implicitly repmatted elementwise equality\n% '~=',ne - Implicitly repmatted elementwise dis-equality\n% '<' ,lt - Implicitly repmatted elementwise less than\n% '>' ,gt - Implicitly repmatted elementwise greater than\n% '<=',le - Implicitly repmatted elementwise less than equal\n% '>=',ge - Implicitly repmatted elementwise greater than equal\n%\n% N.B. the operator can go in any of the 3 argument positions, i.e.\n% these are all valid: repop(X,'-',Y), repop(X,Y,'-'), repop('-',X,Y)\n%\n% The optional final argument is a string of single letter switches\n% consisting off\n% 'm' -- allows replication of non-unit dimensions if the larger\n% dimensions size is an integer multiple of the smaller ones\n% 'n' -- allow replication of non-unit dimensions in *all* cases\n% 'i' -- perform \"inplace\" operation. This means that we use a\n% *dangerous* matlab *hack* to perform the operation *without*\n% allocating new memory for the output, but by simply overwriting\n% the memory used for X in the input. Thus the following code is\n% a memory (and time) efficient way to increment X.\n% X = repop(X,'+',1,'i');\n%\n%\n% Class support of input P:\n% float: double, single\n% \n% SEE ALSO: repop_testcases rplus rminus rtimes rpower rldivide rrdivide\n% req rne rlt rgt rle rge\n%\n% Copyright 2006- by Jason D.R. Farquhar (jdrf@zepler.org)\n% Permission is granted for anyone to copy, use, or modify this\n% software and accompanying documents for any uncommercial\n% purposes, provided this copyright notice is retained, and note is\n% made of any changes that have been made. This software and\n% documents are distributed without any warranty, express or\n% implied\n%\n% Inspired by code from Douglas M. Schwarz and & Aki Vehtari.\n\n% The rest of this code is a mex-hiding mechanism which compilies the mex if\n% this runs and recursivly calls itself. \n% Based upon code from: http://theoval.sys.uea.ac.uk/matlab\ncwd = pwd; % store the current working directory\nname = mfilename('fullpath'); % get the directory where we are\n% find out what directory it is defined in\nname(name=='\\')='/'; % deal with dos'isms\ndir=name(1:max(find(name == '/')-1)); % dir is everything before final '/'\ntry % try changing to that directory\n cd(dir);\ncatch % this should never happen, but just in case!\n cd(cwd);\n error(['unable to locate directory containing ''' name '.m''']);\nend\n\ntry % try recompiling the MEX file\n fprintf(['Compiling ' mfilename ' for first use\\n']);\n mex('ddrepop.c','dsrepop.c','sdrepop.c','ssrepop.c','repop_util.c','repop_mex.c','mxInfo.c','mxInfo_mex.c','-O','-output',mfilename);\n fprintf('done\\n');\ncatch\n % this may well happen happen, get back to current working directory!\n cd(cwd);\n error('unable to compile MEX version of ''%s''%s\\n%s%s', name, ...\n ', please make sure your', 'MEX compiler is set up correctly', ...\n ' (try ''mex -setup'').');\nend\n\ncd(cwd); % change back to the current working directory\nrehash; % refresh the function and file system caches\n\n% recursively invoke MEX version using the same input and output arguments\n[varargout{1:nargout}] = feval(mfilename, varargin{:});\n\n% bye bye...\n\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/dmlt/external/svm/repop/repop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.6316713823533803}} {"text": "function x = typeIV(alpha)\n%4 times of Bit-wise MAP\nalpha_1 = alpha(1 : end/4);\n% llr_1 = 2*atanh(prod(tanh(alpha_1/2)));\nllr_1 = prod(sign(alpha_1))*min(abs(alpha_1));\n\nalpha_2 = alpha(end/4 + 1 : end/2);\n% llr_2 = 2*atanh(prod(tanh(alpha_2/2)));\nllr_2 = prod(sign(alpha_2))*min(abs(alpha_2));\n\nalpha_3 = alpha(end/2 + 1 : end*3/4);\n% llr_3 = 2*atanh(prod(tanh(alpha_3/2)));\nllr_3 = prod(sign(alpha_3))*min(abs(alpha_3));\n\nalpha_4 = alpha(end*3/4 + 1 : end);\n% llr_4 = 2*atanh(prod(tanh(alpha_4/2)));\nllr_4 = prod(sign(alpha_4))*min(abs(alpha_4));\n\n\n%Even Parity check\ncheck_bit = (llr_1 + llr_2 + llr_3 + llr_4) < 0;\n%Wagner Decoder\nx1 = alpha_1 < 0;\nif mod(sum(x1), 2) ~= check_bit\n x1(abs(alpha_1) == min(abs(alpha_1))) = mod(x1(abs(alpha_1) == min(abs(alpha_1))) + 1, 2);\nend\n\nx2 = alpha_2 < 0;\nif mod(sum(x2), 2) ~= check_bit\n x2(abs(alpha_2) == min(abs(alpha_2))) = mod(x2(abs(alpha_2) == min(abs(alpha_2))) + 1, 2);\nend\n\nx3 = alpha_3 < 0;\nif mod(sum(x3), 2) ~= check_bit\n x3(abs(alpha_3) == min(abs(alpha_3))) = mod(x3(abs(alpha_3) == min(abs(alpha_3))) + 1, 2);\nend\n\nx4 = alpha_4 < 0;\nif mod(sum(x4), 2) ~= check_bit\n x4(abs(alpha_4) == min(abs(alpha_4))) = mod(x4(abs(alpha_4) == min(abs(alpha_4))) + 1, 2);\nend\n\nx_tmp = [x1; x2; x3; x4];\n\nx = x_tmp(:);\n\nend", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarConventionalCASCL/NodeProcess/typeIV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6316324732157202}} {"text": "function [newRO, newRR] = mstep_update_rotation(P, S_bar, V, E_z, E_zz, RO, c, Tr)\n%[newRO, newRR] = mstep_update_rotation(P, S_bar, V, E_z, E_zz, RO, Tr)\n\n% Linearizes the expression in Eq 24 using exponential maps and \n% solves for an improved rotation\n\n% update step\ntw_step = 0.3;\n\n[K, T] = size(E_z);\nJ = size(S_bar, 2);\n\nPc = P - Tr(:)*ones(1,J);\n\nnewRR = zeros(2*T,3);\nnewRO = RO;\n\nfor iter=1:1, \n for t = 1:T, \n A = zeros(3);\n B = zeros(2,3);\n \n zz_hat_t = [1 E_z(:,t)'; E_z(:,t) E_zz((t-1)*K+1:t*K,:)];\n \n for j=1:J,\n H_j = [S_bar(:,j) reshape(V(:,j), 3, K)];\n \n A = A + H_j*zz_hat_t*H_j';\n \n B = B + ([Pc(t,j); Pc(t+T,j)] * [1 E_z(:,t)'] * H_j');\n end\n \n oldRO_t = RO{t};\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%% Changed code here %%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %C = oldRO_t*A;\n %D = B - oldRO_t(1:2,:)*A;\n\n C = c(t,1)^2*oldRO_t*A;\n D = c(t,1)*B - c(t,1)^2*oldRO_t(1:2,:)*A;\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n \n % now we solve the system: [1 0 0; 0 1 0]*twist*C = D \n CC = [0 C(3,1) -C(2,1)\n -C(3,1) 0 C(1,1)\n 0 C(3,2) -C(2,2)\n -C(3,2) 0 C(1,2)\n 0 C(3,3) -C(2,3)\n -C(3,3) 0 C(1,3)];\n \n DD = D(:);\n \n % twist optimization \n twist_vect = tw_step*pinv(CC)*DD;\n \n twh = [0 -twist_vect(3) twist_vect(2)\n twist_vect(3) 0 -twist_vect(1)\n -twist_vect(2) twist_vect(1) 0 ];\n dR = expm(twh);\n newRO_t = dR*oldRO_t;\n \n newRO{t} = newRO_t;\n newRR(t,:) = newRO_t(1,:);\n newRR(t+T,:) = newRO_t(2,:); \n end\n \n RO = newRO;\nend", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/nrsfm/mstep_update_rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.631632460272847}} {"text": "% Figure 10.32 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% Fig. 10.32 Script for computation of the root locus of yaw response, \n% with no compensation, direct feedback \n\n\nf =[-0.0558 -0.9968 0.0802 0.0415;\n 0.5980 -0.1150 -0.0318 0 ;\n -3.0500 0.3880 -0.4650 0 ;\n 0 0.0805 1.0000 0] ;\ng =[0.0073;\n -0.4750;\n 0.1530;\n 0];\nh = [0 1 0 0];\nj =[0];\n% the equations of the actuator:\n\nna=[0 10];\nda=[1 10];\n[fa,ga,ha,ja]=tf2ss(na,da);\n\n% the equations of the aircraft with actuator:\n\n[fp,gp,hp,jp]=series(fa,ga,ha,ja,f,g,h,j);\n% the uncompensated rootlocus\n hold off; clf\n rlocus(fp,-gp,hp,jp);\n axis([-2, 2, -1.5, 1.5]);\n grid;\n title('Fig. 10.32 Root locus of the aircraft with positive feedback')\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_32.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6315290007238474}} {"text": "function [AR, lambdamax]=sim_genRndVARcoeffs(varargin)\n% Generate random coefficients for a VAR model of given order and with a\n% specified degree of interaction sparsity.\n% Coefficients are drawn from a normal distribution with specified standard\n% deviation (sigma).\n% \n% The function will repeatedly generate random models until it obtains a\n% stable VAR process (all eigenvalues of the system matrix are less than or\n% equal to 1 in magnitude).\n%\n% \n% See Also: sim_genTVARcoeffs()\n%\n% References:\n% [1] This function is adapted from Stefan Haufe's gen_ar_sech.m\n%\n% Author: Tim Mullen 2011-2013, SCCN/INC, UCSD.\n% Email: tim@sccn.ucsd.edu\n\n% This function is part of the Source Information Flow Toolbox (SIFT)\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\ng = arg_define(varargin,...\n arg({'nchs','NumChans'},10,[],'Number of channels (variables)'), ...\n arg({'morder','ModelOrder'},10,[],'Model order'), ...\n arg({'sigma','Sigma'},0.2,[0 Inf],'Scale (std) of random VAR parameters. This determines the variance of the determinstic component of the generated process.'), ...\n arg({'maxinter','MaxNumInter'},0.5,[],'Maximum number of interactions. If >= 1, this is the expected number of interacting variables (chosen randomly). If < 1, this represents the proportion of interacting variable (out of nchs^2-nchs max possible interactions). This can also be a vector specifying the linear (column-major) index of each nonzero (non-diagonal) element of the interaction (connectivity) matrix'), ...\n arg({'probinter','PerLagInteractProb'},1,[0 1],'Percent of nonzero AR coefficients for a given interaction. This applies to auto-interactions as well as cross-interactions. For instance, a value of 1 will generate nonzero gaussian iid AR filter coefficients. A value of 0.5 will generate a mixed sparse AR filter with 50% zero coefficients and remaining nonzero iid gaussian coefficients'), ...\n arg({'maxtrys','MaxAttempts','maxattempts'},Inf,[],'Max number of retries for stable model gen.'), ...\n arg({'maxlambda','MaxLambdaMag'},1,[0 1],'Largest allowable eigenvalue (magnitude) of system matrix. This determines the stability of the process. The smaller this value the more stable the process. All eigenvalues must be <= 1 in magnitude for a stable process.') ... \n );\n \n% RandStream.setDefaultStream(RandStream('mt19937ar','seed',sum(100*clock)));\n\nif g.maxinter < 1\n g.maxinter = ceil(g.maxinter*(g.nchs^2-g.nchs));\nend\n \n% generate canonical interaction indices\nif length(g.maxinter) == 1\n inddiag = linspace(1, g.nchs^2, g.nchs);\n indndiag = setdiff(1:g.nchs^2, inddiag);\n per = randperm(length(indndiag));\n indndiag = indndiag(per);\n indndiag = indndiag(1:g.maxinter);\n ind = [inddiag indndiag];\nelse\n inddiag = linspace(1, g.nchs^2, g.nchs);\n ind = unique([inddiag g.maxinter]);\nend\nind = sort(ind); \n% generate interaction indices for all model orders\nind = tensorsum(0:g.nchs^2:g.nchs^2*(g.morder-1),ind);\n\n% generate random coefficients for interacting variables\nlambdamax = Inf; ntrys = 0;\nwhile lambdamax > g.maxlambda && ntrys < g.maxtrys\n AR = zeros(g.nchs,g.nchs*g.morder);\n AR(ind) = double(rand(length(ind), 1) <= g.probinter).*randn(length(ind), 1)*g.sigma;\n \n% for k=1:g.morder\n% aloc = zeros(g.nchs);\n% aloc(ind) = double(rand(length(ind), 1) < g.probinter).*randn(length(ind), 1)*g.sigma;\n% AR(:,:,(k-1)*g.nchs+1:k*g.nchs) = aloc;\n% end\n\n % check model stability\n E = eye(g.nchs*g.morder);\n AA = [AR;E(1:end-g.nchs,:)];\n lambda = eig(AA);\n lambdamax = max(abs(lambda));\n \n ntrys = ntrys + 1;\nend\nif ntrys>=g.maxtrys\n fprintf('Unable to find a stable model. Maximum number of attempts exceeded\\n');\n AR = [];\n return;\nend\n\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/sim/sim_genRndVARcoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6314886832139004}} {"text": "function [I,src] = rayMeasure(ray,Xmes,rad,rMax)\n%+========================================================================+\n%| |\n%| OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING |\n%| openRay is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : rayMeasure.m |\n%| # | VERSION : 0.41 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.04.2018 |\n%| ( === ) | SYNOPSIS : Spherical measurement |\n%| `---' | |\n%+========================================================================+\n\n% Initialization\nI = cell(1,length(ray.pos)-1);\nsrc = cell(length(ray.pos)-1,1);\ndst = zeros(length(ray),1);\n\n% Loop \nfor i = 1:size(I,2)\n % Ray positions\n Pi = ray.pos{i};\n Pip1 = ray.pos{i+1};\n \n % Ray direction and length\n U = (Pip1 - Pi);\n lgt = sqrt(sum(U.^2,2));\n U = U ./ (lgt * [1 1 1]);\n\n % Initial position -> micro\n PM = ones(size(Pi,1),1)*Xmes - Pi;\n \n % Measure triangle (pythagore)\n hyp2 = sum(PM.^2,2);\n adj = sum(PM.*U,2);\n opp2 = hyp2 - adj.^2;\n \n % Measured ray\n I{i} = find( (hyp2 < lgt.^2) & (adj >= 0) & (opp2 <= rad^2) & (dst + sqrt(hyp2) < rMax) );\n\n % Sources (focusing)\n if ~isempty(I{i})\n src{i} = Pi(I{i},:) - (dst(I{i})*[1 1 1]) .* U(I{i},:);\n else\n src{i} = zeros(0,3);\n end\n \n % Total distance from initial position\n dst = dst + lgt; \nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openRay/rayMeasure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6314795112430216}} {"text": "function [S] = lukfPropagation(dt,chi,chiAnt,omega_b,a_b,S,omega,acc,Qc,g)\n%Left-UKF on Lie Groups\nq = length(S); % state size\nS_aug = blkdiag(S,Qc);\nN_aug = length(S_aug);\n\n%scaled unsented transform\nW0 = 1-N_aug/3;\nWj = (1-W0)/(2*N_aug);\ngamma = sqrt(N_aug/(1-W0));\n\n% Prediction\nichi = invSE3(chi);\nomega = omega-omega_b; % unbiased inputs\nacc = acc-a_b;\nX = gamma*[zeros(N_aug,1) S_aug' -S_aug'];% sigma-points\nX(10:15,:) = X(10:15,:)+X(q+7:q+12,:)*dt; % add bias noise\nfor j = 2:2*N_aug+1\n xi_j = X([1:9,16:q],j); %do not take bias\n w_j = X(q+1:N_aug,j);\n omega_bj = X(10:12,j);\n a_bj = X(13:15,j);\n chi_j = chiAnt*exp_multiSE3(xi_j);\n Rot = chi_j(1:3,1:3)*expSO3((omega+w_j(1:3)-omega_bj)*dt);\n v = chi_j(1:3,4)+(Rot*(acc+w_j(4:6)-a_bj)+g)*dt;\n x = chi_j(1:3,5)+v*dt;\n chi = state2chi(Rot,v,x,chi_j(1:3,6:end));\n Xi_j = ichi*chi; % can be more time efficient\n X([1:9,16:q],j) = log_multiSE3(Xi_j); %propagated sigma points\nend\nX = sqrt(Wj)*X;\n[~,Rs] = qr(X(1:q,2:2*N_aug+1)');\nS = Rs(1:q,1:q);\nend\n", "meta": {"author": "mbrossar", "repo": "FUSION2018", "sha": "ff97d009d80151b2ce2b2c62ffe792a90e1ed7de", "save_path": "github-repos/MATLAB/mbrossar-FUSION2018", "path": "github-repos/MATLAB/mbrossar-FUSION2018/FUSION2018-ff97d009d80151b2ce2b2c62ffe792a90e1ed7de/filters/lukfPropagation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6314515065592579}} {"text": "clear;\nclc\nclose all;\n\naddpath('../../library/nav_lib'); \n\n%% attidude\n\ntrue_attitude = deg2rad([4 -6 30])';\nroll_meas_err = deg2rad(0.1);\npitch_meas_err = deg2rad(-0.15);\n\n%% Earth's Magnetic Field\nflux = 45;\ndeclination= deg2rad(10);\ninclination = deg2rad(40);\n\ndelta_alpha_nE= deg2rad(0.3);\n\n%% Other Souces of Magnetism\nMAn = [2 -1.8 3]'; % local magnetic anomalies(N,E,D)\nhard = [-1 -0.5 1]'; % hard-iron magnetism(body-frame axes)\nsoft = [0.012 -0.014 0.006; -0.008 0.007 0.017; 0.003 -0.019 -0.011]; % soft-iron magnetism, body-rame-axes\n\n\n%% \nCn2b = ch_eul2m(true_attitude);\n\n%% flux desity of Earth's magnetic filed\nm_En = [cos(declination)*cos(inclination) sin(declination)*cos(inclination) sin(inclination)]'*flux;\n\n%% Total magnetic flux density\nm_mb = hard + (eye(3) + soft)*Cn2b*(m_En + MAn);\n\n%% Calculate Magnetic Heading Measurement\nroll_meas = true_attitude(1) + roll_meas_err;\npitch_meas = true_attitude(2) +pitch_meas_err;\n\nyaw = atan2(-m_mb(2)*cos(roll_meas) + m_mb(3)*sin(roll_meas), m_mb(1)*cos(pitch_meas) + m_mb(2)*sin(pitch_meas)*sin(roll_meas) + m_mb(3)*cos(roll_meas)*sin(pitch_meas));\n\n\n%% Calculate True Heading\ndata_base_magnetic_declination = declination + delta_alpha_nE\n\n%% True heading\ntrue_heading = yaw+ data_base_magnetic_declination;\n%rad2deg(true_heading)\n\n%% Heading error\nerror = true_heading - true_attitude(3);\nrad2deg(error)\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/Principles_of_GNSS_Inertial_and_Multi-Sensor_Integrated_Navigation_System_Second/example6_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6314515030707273}} {"text": "% RANSACFITLINE - fits line to 3D array of points using RANSAC\n%\n% Usage [L, inliers] = ransacfitline(XYZ, t, feedback)\n%\n% This function uses the RANSAC algorithm to robustly fit a line\n% to a set of 3D data points.\n%\n% Arguments:\n% XYZ - 3xNpts array of xyz coordinates to fit line to.\n% t - The distance threshold between data point and the line\n% used to decide whether a point is an inlier or not.\n% feedback - Optional flag 0 or 1 to turn on RANSAC feedback\n% information.\n%\n% Returns:.\n% V - Line obtained by a simple fitting on the points that\n% are considered inliers. The line goes through the\n% calculated mean of the inlier points, and is parallel to\n% the principal eigenvector. The line is scaled by the\n% square root of the largest eigenvalue.\n% This line is a n*2 matrix. The first column is the\n% beginning point, the second column is the end point of the\n% line.\n% L - The two points in the data set that were found to\n% define a line having the most number of inliers.\n% The two columns of L defining the two points.\n% inliers - The indices of the points that were considered\n% inliers to the fitted line.\n%\n% See also: RANSAC, FITPLANE, RANSACFITPLANE\n\n% Copyright (c) 2003-2006 Peter Kovesi and Felix Duvallet (CMU)\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% Aug 2006 - created ransacfitline from ransacfitplane\n% author: Felix Duvallet\n\nfunction [V, L, inliers] = ransacfit3Dline(XYZ, t, feedback)\n \n if nargin == 2\n\tfeedback = 0;\n end\n \n [rows, npts] = size(XYZ);\n \n if rows ~=3\n error('data is not 3D');\n end\n \n if npts < 2\n error('too few points to fit line');\n end\n \n s = 2; % Minimum No of points needed to fit a line.\n \n fittingfn = @defineline;\n distfn = @lineptdist;\n degenfn = @isdegenerate;\n\n [L, inliers] = ransac(XYZ, fittingfn, distfn, degenfn, s, t, feedback);\n \n % Find the line going through the mean, parallel to the major\n % eigenvector\n V = fitline3d(XYZ(:, inliers));\n \n%------------------------------------------------------------------------\n% Function to define a line given 2 data points as required by\n% RANSAC.\n\nfunction L = defineline(X);\n L = X;\n \n%------------------------------------------------------------------------\n% Function to calculate distances between a line and an array of points.\n% The line is defined by a 3x2 matrix, L. The two columns of L defining\n% two points that are the endpoints of the line.\n%\n% A line can be defined with two points as:\n% lambda*p1 + (1-lambda)*p2\n% Then, the distance between the line and another point (p3) is:\n% norm( lambda*p1 + (1-lambda)*p2 - p3 )\n% where\n% (p2-p1).(p2-p3)\n% lambda = ---------------\n% (p1-p2).(p1-p2)\n%\n% lambda can be found by taking the derivative of:\n% (lambda*p1 + (1-lambda)*p2 - p3)*(lambda*p1 + (1-lambda)*p2 - p3)\n% with respect to lambda and setting it equal to zero\n\nfunction [inliers, L] = lineptdist(L, X, t)\n\n p1 = L(:,1);\n p2 = L(:,2);\n \n npts = length(X);\n d = zeros(npts, 1);\n \n for i = 1:npts\n p3 = X(:,i);\n \n lambda = dot((p2 - p1), (p2-p3)) / dot( (p1-p2), (p1-p2) );\n \n d(i) = norm(lambda*p1 + (1-lambda)*p2 - p3);\n end\n \n inliers = find(abs(d) < t);\n \n%------------------------------------------------------------------------\n% Function to determine whether a set of 2 points are in a degenerate\n% configuration for fitting a line as required by RANSAC.\n% In this case two points are degenerate if they are the same point\n% or if they are exceedingly close together.\n\nfunction r = isdegenerate(X)\n %find the norm of the difference of the two points\n % this will be 0 iff the two points are the same (the norm of their\n % difference is zero)\n r = norm(X(:,1) - X(:,2)) < eps;", "meta": {"author": "DrGabor", "repo": "LiDAR", "sha": "707ca635db955cf00d833578ad1236f0790cdf98", "save_path": "github-repos/MATLAB/DrGabor-LiDAR", "path": "github-repos/MATLAB/DrGabor-LiDAR/LiDAR-707ca635db955cf00d833578ad1236f0790cdf98/RoadSegmenter/Ransac/ransacfit3Dline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6313100626433386}} {"text": "function W = tess_smooth_sources(Vertices, Faces, VertConn, FWHM, Method)\n% TESS_SMOOTH_SOURCES: Gaussian smoothing matrix over a mesh.\n%\n% USAGE: W = tess_smooth_sources(Vertices, Faces, VertConn=[], FWHM=0.010, Method='average')\n%\n% INPUT:\n% - Vertices : Vertices positions ([X(:) Y(:) Z(:)])\n% - Faces : Triangles matrix\n% - VertConn : Vertices connectivity, logical sparse matrix [Nvert,Nvert]\n% - FWHM : Full width at half maximum, in meters (default=0.010)\n% - Method : {'euclidian', 'path', 'average', 'surface'}\n% OUPUT:\n% - W: smoothing matrix (sparse)\n%\n% DESCRIPTION: \n% - The distance between two points is an average of:\n% - the direct euclidian between the two points and\n% - the number of edges between the two points * the average length of an edge\n% - Gaussian smoothing function on the euclidian distance:\n% f(r) = 1 / sqrt(2*pi*sigma^2) * exp(-(r.^2/(2*sigma^2)))\n% - Full Width at Half Maximum (FWHM) is related to sigma by:\n% FWHM = 2 * sqrt(2*log2(2)) * sigma\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2010-2013\n\n\n% ===== PARSE INPUTS =====\nif (nargin < 5) || isempty(Method)\n Method = 'average';\nend\nif (nargin < 4) || isempty(FWHM)\n FWHM = 0.010;\nend\nif (nargin < 3) || isempty(VertConn)\n VertConn = tess_vertconn(Vertices, Faces);\nend\nif ~islogical(VertConn)\n error('Invalid vertices connectivity matrix.');\nend\nnv = size(Vertices,1);\n\n\n% ===== ANALYZE INPUT =====\n% Calculate Gaussian kernel properties\nSigma = FWHM / (2 * sqrt(2*log2(2)));\n% FWTM = 2 * sqrt(2*log2(10)) * Sigma;\n% Get the average edge length\n[vi,vj] = find(VertConn);\nmeanDist = mean(sqrt((Vertices(vi,1) - Vertices(vj,1)).^2 + (Vertices(vi,2) - Vertices(vj,2)).^2 + (Vertices(vi,3) - Vertices(vj,3)).^2));\n% Guess the number of iterations\nnIter = min(10, ceil(FWHM / meanDist));\n\n% ===== COMPUTE DISTANCE =====\nswitch lower(Method)\n % === METHOD 1: USE EUCLIDIAN DISTANCE ===\n case 'euclidian'\n % Get the neighborhood around each vertex\n VertConn = mpower(VertConn, nIter);\n [vi,vj] = find(VertConn);\n % Use Euclidean distance \n d = sqrt((Vertices(vi,1) - Vertices(vj,1)).^2 + (Vertices(vi,2) - Vertices(vj,2)).^2 + (Vertices(vi,3) - Vertices(vj,3)).^2);\n Dist = sparse(vi, vj, d, nv, nv);\n\n % === METHOD 2: USE NUMBER OF CONNECTIONS =====\n % === METHOD 3: AVERAGE METHOD 1+2 ===\n case {'path', 'average'}\n % Initialize loop variables\n VertConnGrow = speye(nv);\n VertIter = sparse(nv,nv);\n vall = [];\n\n % Grow and keep track of the layers\n for iter = 1:nIter\n disp(sprintf('SMOOTH> Iteration %d/%d', iter, nIter));\n % Grow selection of vertices\n VertConnPrev = VertConnGrow;\n VertConnGrow = double(VertConnGrow * VertConn > 0);\n % Find all the new connections\n vind = find(VertConnGrow - VertConnPrev > 0);\n [vi,vj] = ind2sub([nv,nv], vind);\n VertIter = VertIter + iter * sparse(vi, vj, ones(size(vi)), nv, nv);\n end\n\n % Use distance in number of connections\n Dist = VertIter * meanDist;\n Dist(1:nv+1:nv*nv) = 0;\n \n % == AVERAGE WITH METHOD 1 ==\n if strcmpi(Method, 'average')\n % Calculate Euclidean distance \n [vi,vj] = find(VertConnGrow);\n d = sqrt((Vertices(vi,1) - Vertices(vj,1)).^2 + (Vertices(vi,2) - Vertices(vj,2)).^2 + (Vertices(vi,3) - Vertices(vj,3)).^2);\n % Average with results of method #2\n Dist = (0.5 .* Dist + 0.5 .* sparse(vi, vj, d, nv, nv));\n end\n \n % ===== METHOD 4: CALCULATE SURFACE DISTANCE =====\n % WARNING: NOT FINISHED!!!!\n case 'surface'\n % Initialize loop variables\n VertConnGrow = speye(nv);\n Dist = sparse([], [], [], nv, nv, 3*nnz(VertConn));\n vall = [];\n nIter = 2;\n % Grow until we reach an accepteable distance\n for iter = 1:nIter\n disp(sprintf('Iteration %d', iter));\n % Get neighbors\n VertConnGrow = VertConnGrow * VertConn;\n % Get all the existing edges in the surface\n vind = find(VertConnGrow);\n % Remove all the previously processed connections\n vind = setdiff(vind, vall);\n [vi,vj] = ind2sub([nv,nv], vind);\n % Remove diagonal\n iDel = (vi == vj);\n vi(iDel) = [];\n vj(iDel) = [];\n % Calculate the distance to the neighbor nodes\n if (iter == 1)\n % Calculate all the distances for all the pairs of edges\n d = sqrt((Vertices(vi,1) - Vertices(vj,1)).^2 + (Vertices(vi,2) - Vertices(vj,2)).^2 + (Vertices(vi,3) - Vertices(vj,3)).^2);\n else\n % Initialize d matrix\n d = zeros(size(vi));\n % Process each new connection separately\n for i = 1:length(vi)\n % Find nodes that are connected to both nodes\n iMid = find((Dist(vi(i),:) & VertConn(vj(i),:)) | (VertConn(vi(i),:) & Dist(vj(i),:)));\n % Find nodes for which we know one connection at least\n iMid0 = (Dist(vi(i),iMid) & Dist(vj(i),iMid));\n iMid1 = (Dist(vi(i),iMid) & ~iMid0);\n iMid2 = (Dist(vj(i),iMid) & ~iMid0);\n % Compute distances\n dMid = 0*iMid;\n dMid(iMid0) = Dist(vi(i),iMid0) + Dist(vj(i),iMid0);\n dMid(iMid1) = Dist(vi(i),iMid1) + sqrt((Vertices(vj(i),1) - Vertices(iMid1,1)).^2 + (Vertices(vj(i),2) - Vertices(iMid1,2)).^2 + (Vertices(vj(i),3) - Vertices(iMid1,3)).^2)';\n dMid(iMid2) = Dist(vj(i),iMid2) + sqrt((Vertices(vi(i),1) - Vertices(iMid2,1)).^2 + (Vertices(vi(i),2) - Vertices(iMid2,2)).^2 + (Vertices(vi(i),3) - Vertices(iMid2,3)).^2)';\n dMid(dMid == 0) = Inf;\n % Find the shortest path\n d(i) = min(dMid);\n if isinf(d(i))\n error('???');\n end\n end\n end\n % Add to processed vertices\n vall = union(vind, vall);\n % Create a sparse distance matrix\n Dist = Dist + sparse(vi, vj, d, nv, nv);\n end\nend\n\n\n% ===== APPLY GAUSSIAN FUNCTION =====\n% Gaussian function\nfun = inline('1 / sqrt(2*pi*sigma2) * exp(-(x.^2/(2*sigma2)))', 'x', 'sigma2');\n% Calculate interpolation as a function of distance\n[vi,vj] = find(Dist>0);\nvind = sub2ind([nv,nv], vi, vj);\nw = fun(Dist(vind), Sigma^2);\n% Build final symmetric matrix\n%W = sparse([vi;vj], [vj;vi], [w;w], nv, nv);\nW = sparse(vi, vj, w, nv, nv);\n% Add the diagonal\nW = W + fun(0,Sigma^2) * speye(nv);\n% Normalize columns\nW = bst_bsxfun(@rdivide, W, sum(W,1));\n% Remove insignificant values\n[vi,vj] = find(W>0.005);\nvind = sub2ind([nv,nv], vi, vj);\nW = sparse(vi, vj, W(vind), nv, nv);\n\n\n% ===== FIX BAD TRIANGLES =====\n% Only for methods including neighbor distance\nif ismember(lower(Method), {'path', 'average'})\n % Configurations to detect: \n % - One face divided in 3 with a point in the middle of the face\n % - Square divided into 4 triangles with one point in the middle\n % Calculate face-vertex connectivity\n VertFacesConn = tess_faceconn(Faces);\n % Find vertices connected to three or four faces\n sumVert = sum(VertConn,2);\n sumFaces = sum(VertFacesConn,2);\n % Three/Four vertices: average the values of their neighbors\n iVert = find(((sumVert == 3) & (sumFaces == 3)) | ((sumVert == 4) & (sumFaces == 4)));\n AvgConn = bst_bsxfun(@rdivide, W * VertConn(:,iVert), sumVert(iVert)');\n W(iVert,:) = AvgConn';\n W(:,iVert) = AvgConn;\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/anatomy/tess_smooth_sources.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6312356438001612}} {"text": "%% mri_sense_demo1.m\n%|\n%| Example illustrating regularized iterative reconstruction for parallel MRI\n%| (sensitivity encoding imaging or SENSE), from nonuniform k-space samples.\n%| (This example does not include field inhomogeneity or relaxation.)\n%|\n%| Copyright 2006-4-18, Jeff Fessler, University of Michigan\n\n%% make coil sensitivity maps\nif ~isvar('smap'), printm 'sense maps'\n\tig = image_geom('nx', 64, 'fov', 250); % 250 mm FOV\n\tig.mask = ig.circ(ig.dx * (ig.nx/2-2), ig.dy * (ig.ny/2-1)) > 0;\n\tf.ncoil = 4;\n\tsmap = mri_sensemap_sim('nx', ig.nx, 'ny', ig.ny, 'dx', ig.dx, ...\n\t\t'rcoil', 120, 'ncoil', f.ncoil, 'chat', 1);\nprompt\nend\n\n\n%% true object (discrete because of discrete sense map)\nif ~isvar('xtrue'), printm 'true object'\n\txtrue = ellipse_im(ig, 'shepplogan-emis', 'oversample', 2);\n\tclim = [0 8];\n\tim plc 2 2\n\tim(1, ig.x, ig.y, xtrue, '\\x true', clim), cbar\n\tim(4, ig.mask, 'mask')\nprompt\nend\n\n\n%% trajectory and system matrix\nif ~isvar('Am'), printm 'system matrix A'\n\tf.traj = 'spiral1';\n\tf.dens = 'voronoi';\n\n\tN = [ig.nx ig.ny];\n\t[kspace, omega, wi_traj] = mri_trajectory(f.traj, {}, ...\n\t\tN, ig.fov, {f.dens});\n\n\t% create Gnufft class object\n\tJ = [6 6];\n\tnufft_args = {N, J, 2*N, N/2, 'table', 2^10, 'minmax:kb'};\n\tAm = Gmri(kspace, ig.mask, ...\n\t\t'fov', ig.fov, 'basis', {'rect'}, 'nufft', nufft_args);\n\n\tif im\n\t\tim subplot 2\n\t\tplot(omega(1:5:end,1), omega(1:5:end,2), '.')\n\t\taxis_pipi, axis square\n\t\ttitlef('%s: %d', f.traj, size(omega,1))\n\tend\nprompt\nend\n\nwi_basis = wi_traj ./ Am.arg.basis.transform;\n\n\n%% SENSE system object\nif ~isvar('Ab'), printm 'Ab object with sense maps within'\n\tfor ic=1:f.ncoil\n\t\ttmp = smap(:,:,ic);\n\t\ttmp = Gdiag(tmp(ig.mask), 'mask', ig.mask);\n\t\tAc{ic} = Am * tmp; % cascade\n\tend\n\tAb = block_fatrix(Ac, 'type', 'col'); % [A1; A2; ... ]\nend\n\n\n%% noisy data\nif ~isvar('yi'), printm 'data yi'\n\tytrue = Ab * xtrue(ig.mask);\n\n\t% add noise\n\trng(0)\n\tyi = ytrue + 0 * randn(size(ytrue));\n\t% todo: visualize data...\nend\n\n\n%% CP recon\nif ~isvar('xcp'), printm 'conj. phase reconstruction'\n\txcp = zeros(ig.nx, ig.ny, f.ncoil, 'single');\n\ty4 = reshape(yi, [], f.ncoil);\n\tfor ic=1:f.ncoil\n\t\ttmp = Am' * (wi_basis .* y4(:,ic));\n\t\txcp(:,:,ic) = ig.embed(tmp);\n\tend\n\n\tim(2, abs(xcp), 'Conj. Phase Recon for each coil'), cbar\nprompt\nend\n\n\n%% SSoS\nif ~isvar('xssos'), printm 'sqrt sum-of-squares reconstruction'\n\txssos = sqrt(sum(abs(xcp).^2, 3));\n\txssos = ir_wls_init_scale(1, xtrue, xssos); % cheat trick for scaling\n\tim(3, abs(xssos), 'sum-of-squares recon'), cbar\n\txlabelf('NRMSE %.1f%%', 100*nrms(xssos(:), xtrue(:)))\nprompt\nend\n\n\n%% regularizer\nif ~isvar('R'), printm 'regularizer'\n\tf.beta = 2^11;\n\tR = Reg1(ig.mask, 'beta', f.beta, 'type_penal', 'mat'); % complex\n\tif 1\n\t\tpsf = qpwls_psf(Ab, R, 1, ig.mask, 1, 'offset', [0 0]);\n\t\tim(4, psf)\n\tend\nprompt\nend\n\n\n%% PCG\nif ~isvar('xpcg'), printm 'PCG with quadratic penalty'\n\tf.niter = 10;\n\txpcg = qpwls_pcg(xssos(ig.mask), Ab, 1, yi(:), 0, R.C, 1, f.niter);\n\txpcg = ig.embed(xpcg(:,end)); % convert last vector to image for display\n\n\tim(4, abs(xpcg), '|\\x| PCG quad', clim), cbar\n\txlabelf('NRMSE %.1f%%', 100*nrms(xpcg(:), xtrue(:)))\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/mri_sense_demo1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6312356362623288}} {"text": "function [IX,IX1,IX2] = FindLinearIdx(x,y,lon,lat)\n% given points in vectors x,y (np x 1) find their linear indices IX (np x 1)\n% from a matrix of x-locations X and y-locations Y of both size nx columns and ny rows.\n% lon and lat must be matrices created by ndgrid. \n% kjr, 20171210 chl, und.\n% wjp, 20201120 making sure dx and dy can be different\n% 20200325 implementing method for irregular grid, cleaning up\nny = size(lon,1);\nnx = size(lon,2);\nnp = numel(x);\n\nif nx == 1 && ny == 1\n IX = 1; IX1 = 1; IX2 = 1;\n return\nend\n\n% make sure entry points are column vectors\nx = x(:);\ny = y(:);\n\n% Get the grid spacing in x and y directions \n% (trying both directions so could be meshgrid or ndgrid format)\ndx = diff(lon(:,1));\ndy = diff(lat(1,:));\ndx_cutoff = 0.1/111e3; % approx 10 cm \nif (max(dx) - min(dx)) > dx_cutoff || (max(dy) - min(dy)) > dx_cutoff\n % % IRREGULAR GRID (SLOWER)\n \n % convert ndgrid to vector\n lonV = reshape(lon(:,1),1,[]); \n % repeat the vector along the length of x\n LON = repmat(lonV,np,1);\n % find the closest lon to each point of x\n [~,IX1] = min(abs(x - LON),[],2);\n \n % convert ndgrid to vector\n latV = lat(1,:); \n % repeat the vector along the length of y\n LAT = repmat(latV,np,1);\n % find the closest lon to each point of y\n [~,IX2] = min(abs(y - LAT),[],2);\n\nelse\n % % REGULAR GRID (FASTER)\n dx = dx(1); dy = dy(1);\n\n IX1 = (x-lon(1,1))/dx + 1;\n IX2 = (y-lat(1,1))/dy + 1;\n\n IX1 = round(IX1);\n IX2 = round(IX2);\n\n IX1 = max([IX1,ones(np,1)],[],2);\n IX1 = min([IX1,ny*ones(np,1)],[],2);\n\n IX2 = max([IX2,ones(np,1)],[],2);\n IX2 = min([IX2,nx*ones(np,1)],[],2);\n\nend\n\nIX = sub2ind([ny,nx],IX1,IX2);\n\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/FindLinearIdx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6311906489066574}} {"text": "function x = r8row_to_r8vec ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8ROW_TO_R8VEC converts an R8ROW into an R8VEC.\n%\n% Example:\n%\n% M = 3, N = 4\n%\n% A =\n% 11 12 13 14\n% 21 22 23 24\n% 31 32 33 34\n%\n% X = ( 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, real A(M,N), the R8ROW.\n%\n% Output, real X(M*N), a vector containing the M rows of A.\n%\n j = 1;\n for i = 1 : m\n x(j:j+n-1) = a(i,1:n);\n j = j + n;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8row_to_r8vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.6311906258866539}} {"text": "function [x, infos] = svrmu_nmf(V, rank, in_options)\n% Stochastic variance reduced multiplicative update for non-negative matrix factorization (SVRMU-NMF) algorithm.\n%\n% Inputs:\n% matrix V\n% rank rank\n% options options\n% Output:\n% w solution of w\n% infos information\n%\n%\n% Reference:\n% H. Kasai, \n% \"Stochastic variance reduced multiplicative update for nonnegative matrix factorization,\" \n% IEEE ICASSP, 2018.\n%\n% \n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai on Mar. 22, 2017\n%\n% Change log: \n%\n% Mar. 15, 2018 (Hiroyuki Kasai): Fixed algorithm. \n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = [];\n local_options.repeat_inneriter = 1;\n local_options.W_sub_mode = 'STD'; \n local_options.H_sub_mode = 'STD';\n local_options.accel = false;\n local_options.ls = false;\n local_options.precon = false; \n local_options.h_repeat = 1;\n local_options.rep_mode = 'fix';\n local_options.stepsize_ratio = 1; % stepsize ratio\n local_options.robust = false;\n local_options.lambda = 1;\n local_options.tol_optgap = 1e-2;\n local_options.x_init_robust = false;\n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options); \n \n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n Wt = init_factors.W;\n H = init_factors.H; \n R = init_factors.R; \n\n % determine sub_mode\n if options.accel\n options.H_sub_mode = 'ACC';\n else\n if options.ls\n options.H_sub_mode = 'LS';\n else\n options.H_sub_mode = 'STD'; \n end\n options.h_repeat = 1;\n end\n \n if options.precon\n options.W_sub_mode = 'Precon';\n fprintf('Unfortunately, Precon variant does not work well.\\n');\n else\n options.W_sub_mode = 'STD';\n end\n \n if options.robust\n mode = 'R-SVRMU-NMF';\n else\n mode = 'SVRMU-NMF'; \n R = zeros(m, n);\n end \n \n if strcmp(options.rep_mode, 'adaptive')\n rhoh = 1+(m+m*rank)/(1*(rank+1));\n alpha = 2;\n delta = 0.01; \n end \n \n % initialize\n method_name = sprintf('%s (%s,%s)', mode, options.W_sub_mode, options.H_sub_mode); \n epoch = 0; \n grad_calc_count = 0;\n l = zeros(m, options.batch_size) + options.lambda; \n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n \n % permute samples\n if options.permute_on\n perm_idx = randperm(n);\n else\n perm_idx = 1:n;\n end \n V = V(:, perm_idx);\n H = H(:, perm_idx); \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, Wt, H, R, options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1 \n fprintf('%s (%s,%s): Epoch = 0000, cost = %.16e, optgap = %.4e\\n', mode, options.W_sub_mode, options.H_sub_mode, f_val, optgap); \n end\n \n % set start time\n start_time = tic(); \n \n % main outer loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end\n \n % store W and H, and calculate full grad\n W_0 = Wt;\n H_0 = H;\n if ~options.robust\n W0_H0_H0T = W_0 * (H_0 * H_0')/n;\n else\n R_0 = R;\n W0_H0_H0T = (W_0 * H_0 + R_0 ) * H_0'/n; \n end\n V_H0T = V * H_0'/n;\n \n if strcmp(options.W_sub_mode, 'Precon') \n invH0H0t = inv(H_0 * H_0');\n invH0H0t = max(invH0H0t,0); \n end\n \n grad_calc_count = grad_calc_count + m * n;\n \n\n % main inner loop\n for s = 1 : options.repeat_inneriter\n for t = 1 : options.batch_size : n - 1\n\n % Retrieve vt and ht\n start_idx = t;\n end_idx = t+options.batch_size-1;\n vt = V(:, start_idx:end_idx);\n ht = H(:, start_idx:end_idx);\n\n ht_0 = H_0(:, start_idx:end_idx);\n\n if ~options.robust\n\n % uddate ht\n Wtv = Wt' * vt;\n WtW = Wt' * Wt;\n if strcmp(options.H_sub_mode, 'ACC')\n if strcmp(options.rep_mode, 'adaptive')\n gamma = 1; \n eps0 = 1; \n j = 1;\n rhoh_alpha = rhoh*alpha;\n %while j <= floor(1+rhoh*alpha) && gamma >= delta*eps0\n ht0 = ht; \n while j <= rhoh_alpha && gamma >= delta*eps0\n ht = ht .* (Wtv) ./ (WtW * ht); \n ht = ht + (ht= delta*eps0\n ht0 = ht; \n while j <= rhoh_alpha && gamma >= delta*eps0\n Wh_r = Wt * ht + rt;\n ht = ht .* (Wtv) ./ (Wt' * Wh_r); \n ht = ht + (ht0\n tPs=cell(N,1);\n pUs=cell(N,1);\n %%%%%%%%%%%%%Determine Rn, the dimension of projected space%%%%\n for n=1:N\n cum=cums{n};\n idxs=find(cum>=Qs(n)/100);\n Ps(n)=idxs(1);\n tUn=tUs{n};\n tPn=tUn(1:Ps(n),:);\n tPs{n}=tPn;\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n for iK=1:maxK\n for n=1:N\n In=Is(n);\n Phi=double(zeros(In,In));\n for m=1:numSpl\n switch N\n case 2\n Xm=TX(:,:,m);\n case 3\n Xm=TX(:,:,:,m);\n case 4\n Xm=TX(:,:,:,:,m);\n otherwise\n error('Order N not supported. Please modify the code here or email hplu@ieee.org for help.')\n end\n tX=ttm(tensor(Xm),tPs,-n);\n tXn=tenmat(tX,n);\n Xn=tXn.data;\n Phi=Phi+Xn*Xn';\n end\n Pn=Ps(n);\n Phi=double(Phi);\n if Pn.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [areas, count] = calc_triangle_areas(verts, faces, space, focus)\n\nif strcmp(space, 'object')\n tri_areas = cal_obj_area(verts, faces);\nelseif strcmp(space, 'parameter')\n tri_areas = cal_par_area(verts, faces);\nend\n\nif strcmp(focus, 'vertex')\n areas = zeros(length(verts),1);\n count = zeros(length(verts),1);\n\n% find all incident triangles upon each vertex and accumulate the areas of the triangles \n for i=1:size(faces,2)\n [u1, m1, n1] = unique(faces(:,i));\n areas(u1) = areas(u1) + accumarray(n1, tri_areas);\n count(u1) = count(u1) + accumarray(n1, ones(length(n1),1));\n end\n \nelseif strcmp(focus, 'triangle')\n areas = tri_areas;\n count = ones(length(tri_areas),1);\nend\n\nreturn;\n\n\n%\n% calculate relative areas of triangles on object surface net\n%\n\nfunction obj_area = cal_obj_area(vertices,faces)\n\nA = faces(:,1); B = faces(:,2); C = faces(:,3);\na = sqrt(sum(((vertices(A,:)-vertices(B,:)).^(2))'))';\nb = sqrt(sum(((vertices(B,:)-vertices(C,:)).^(2))'))';\nc = sqrt(sum(((vertices(C,:)-vertices(A,:)).^(2))'))';\ns = (a+b+c)/2;\nobj_area = sqrt(s.*(s-a).*(s-b).*(s-c));\nobj_area = obj_area/sum(obj_area);\n\nreturn;\n\n\n%\n% calculate relative areas of spherical triangles in parameter space\n%\n\nfunction par_area = cal_par_area(vs,faces)\n\nangles = [];\nfor j = 1:3\n % note that the order of A B C is clockwise (see 08-22-02.htm notes)\n A = vs(faces(:,j),:);\n B = vs(faces(:,mod(j,3)+1),:);\n C = vs(faces(:,mod(j-2,3)+1),:);\n y = A(:,1).*B(:,2).*C(:,3) - A(:,1).*B(:,3).*C(:,2) + ...\n A(:,2).*B(:,3).*C(:,1) - A(:,2).*B(:,1).*C(:,3) + ...\n A(:,3).*B(:,1).*C(:,2) - A(:,3).*B(:,2).*C(:,1);\n x = B(:,1).*C(:,1) + B(:,2).*C(:,2) + B(:,3).*C(:,3) - ...\n (A(:,1).*C(:,1) + A(:,2).*C(:,2) + A(:,3).*C(:,3)).* ...\n (A(:,1).*B(:,1) + A(:,2).*B(:,2) + A(:,3).*B(:,3));\n angles(:,j) = atan2(y,x); \nend\nind = find(angles<0);\nangles(ind) = angles(ind) + 2*pi;\npar_area = sum(angles')' - pi;\npar_area = par_area/(4*pi);\n\nreturn;\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/SpharmToolbox/code/calc_triangle_areas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6310700775225118}} {"text": "function [cl_ext_spm, fwhm] = cl_ext_spm_grf(corrected_p, prim_p, residual_images, mask, varargin) \n% This function is designed to estimate a cluster extent size for \n% the correction for multiple comparisons based on a Gaussian Random Field \n% Theory using SPM toolboxes. \n%\n% :Usage:\n% ::\n%\n% [cl_ext, fwhm] = cl_ext_spm_grf(corrected_p, prim_p, residual_images, mask, varargin) \n%\n% :Inputs:\n%\n% **corrected_p:**\n% corrected p value\n%\n% e.g.) cluster-extent corrected p < .05: corrected_p = .05\n%\n% **prim_p:**\n% primary threshold for height (i.e., cluster-defining threshold)\n%\n% e.g.) prim_p = [0.01 0.005 0.001];\n%\n% **residual_images:**\n% residual image names; if you used\n%\n% cl_ext_make_resid.m, this should be 'Res4d.nii'\n%\n% **mask:**\n% mask image name\n%\n% :Optional Inputs:\n%\n% **'doplot':**\n%\n% **'twotail':**\n% default is one-tail - with this option, primary_p/2 will be used \n% for all clsuter extent estimations. \n%\n% Output:\n%\n% **cl_ext_spm:**\n% cl_ext_spm is the cluster size that makes a corrected p value under \n% corrected_p (e.g., 0.05). \n%\n% **fwhm (x, y, z in voxels):**\n% intrinsic smoothness level estimated by SPM (spm_est_smoothness.m)\n% If you want to convert this into mm, you need to multiply these\n% values by voxel sizes in mm. \n%\n% ..\n% Choong-Wan (Wani) Woo, 08/13/2012\n% modified by Wani, 05/18/2013\n% ..\n \ndoplot = false;\nisTwoTailed = false;\n\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n case 'doplot', doplot = true;\n case 'twotail', isTwoTailed = true;\n end\n end\nend\n\ncon_num = size(expand_4d_filenames(residual_images),1);\nndf = [1 con_num-1];\n\n[fwhm, dummy, r] = spm_est_smoothness(residual_images, mask, [con_num con_num-1]);\n\nV2R = 1/prod(fwhm);\n\ncl_ext = zeros(length(prim_p),2);\n\nif doplot\n scrsz = get(0, 'ScreenSize');\n create_figure('cluster_extent_spm');\n set(gcf, 'Position', [1 scrsz(4)/2 scrsz(3)/1.5 scrsz(4)/2]);\nend\n\nfor i = 1:length(prim_p)\n if isTwoTailed\n u(i) = spm_u(prim_p(i)/2, ndf, 'T');\n else\n u(i) = spm_u(prim_p(i), ndf, 'T');\n end\nend\n\nfor i = 1:length(prim_p) % cluster-extent threshold (k) based on RF in SPM\n\n P = [];\n \n for j = 1:100000\n k = j*V2R; % convert the number of voxels into the number of resels\n \n P(end+1,1) = spm_P_RF(1,k,u(i),ndf,'T',r,1);\n P(end,2) = j;\n\n if P(end,1) <= corrected_p\n cl_ext(i,1) = j;\n cl_ext(i,2) = P(end,1);\n break\n end \n end\n\n if doplot\n hh(i) = subplot(1,length(prim_p),i);\n plot(P(:,2), P(:,1), '-b', 'LineWidth', 1.5);\n xlabel('cluster extent size', 'FontSize', 16);\n ylabel('corrected P value', 'FontSize', 16);\n eval(['title(hh(i), ''Primary P:' num2str(prim_p(i)), ''', ''fontsize'', 16);']);\n set(gca, 'FontSize', 15);\n hold on;\n plot(cl_ext(i,1), cl_ext(i,2), 'r+', 'MarkerSize', 15);\n eval(['text(cl_ext(i,1)/2, cl_ext(i,2), ''+ cl size:' num2str(cl_ext(i,1)) ''', ''FontSize'', 14);']);\n end\n\nend\n\ncl_ext_spm = cl_ext(:,1);\n\nreturn\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Image_thresholding/cl_ext_spm_grf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6310700772154957}} {"text": " function [kp,gz,kz,kf,t] = compute_gz_spsp(kp)\n%function [kp,gz,kz,kf,t] = compute_gz_spsp(kp)\n%Function that computes z gradient waveform accompanying the SPSP pulse,\n%using parameters specified in structure kp, generated by kparameterSPSP.m.\n%In units of g/cm. Currently can only generate waveforms made of trapezoids.\n%Outputs: \n%kp: updated trajectory parameter structure\n%gz: z gradient waveform in g/cm\n%kz,kf: together they specify the trajectory in SPSP k-space (kf-kz space)\n%\n%Chun-yu Yip, 4/1/2009\n\n%Physical parameters\ngam = 26751; %rad/sec/g; gyromagnetic ratio\ngambar = gam/2/pi; %Hz/g\n\n%Trapezoid area calculation\nif (kp.dgdtmax*(kp.T/2)/2 <=kp.gmax) %the lobe is triangular.\n gzarea = kp.T/2 * kp.dgdtmax*(kp.T/2)/2 /2; %g s /cm\nelse %this lobe is a trapezoid.\n r = kp.gmax/kp.dgdtmax; %s; rise time of gradient \n %to plateau \n gzarea = kp.gmax*r + kp.gmax*(kp.T/2 - 2*r); %g s /cm\nend\n\n%Trapezoid generation\ngztrap_whole = dotrap(gzarea,kp.gmax,kp.dgdtmax,kp.pointtime);\ngztrap_half = dotrap(gzarea/2,kp.gmax,kp.dgdtmax,kp.pointtime);\n\nsignz = +1;\ngz = [];\nfor ii = 1:1:kp.Ntraps\n\n if (ii==kp.Ntraps)\n factor = 1;\n else\n factor = 1;\n end\n\n signz = -signz;\n gz = [gz factor*signz*gztrap_whole]; %Concatenate trapezoids\n %with alternating signs.\nend\n\nsignz = -signz;\ngz = [gz signz*gztrap_half]; %Add refocusing lobe \ngz = gz.';\n\nt = kp.pointtime*[0:1:length(gz)-1].'; %s; time vector\n\n%Do \"backward integral\" to obtain excitation k-space trajectory\nintgz = cumtrapz(gz);\nkz = -gambar * kp.pointtime * (ones(length(gz),1)*intgz(end) - intgz); %/cm\nkf = t-t(end);\nkp.npnts = length(gz); %pulse length (number of samples)\nkp.pw = kp.pointtime * kp.npnts; %s; pulse length (actual duration)\n\nif 0 % Display gradient waveform\n\tfigure\n\tplot(t,gz)\n\txlabel('time (sec)')\n\tylabel('g/cm')\n\ttitle('Gz waveform')\n\tgrid\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri-rf/yip-spsp/compute_gz_spsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6310700747817727}} {"text": "function value = normal_01_moment ( order )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_MOMENT evaluates moments of the Normal 01 PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the moment.\n% 0 <= ORDER.\n%\n% Output, real VALUE, the value of the moment.\n%\n if ( mod ( order, 2 ) == 0 )\n value = r8_factorial2 ( order - 1 );\n else\n value = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/truncated_normal/normal_01_moment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6310411743639248}} {"text": "function npower3 = fac_lcm ( nprime, npower1, npower2 )\n\n%*****************************************************************************80\n%\n%% FAC_LCM finds the LCM of two products of prime factors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NPRIME, the index of the highest prime number\n% used in the representations.\n%\n% Input, integer NPOWER1(NPRIME), the powers of primes\n% in the representation of the first quantity.\n%\n% Input, integer NPOWER2(NPRIME), the powers of primes\n% in the representation of the second quantity.\n%\n% Output, integer NPOWER3(NPRIME), the powers of primes\n% in the representation of the LCM.\n%\n for i = 1 : nprime\n\n if ( npower1(i) < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FAC_LCM - Fatal error!\\n' );\n fprintf ( 1, ' One of the powers is negative!\\n' );\n error ( 'FAC_LCM - Fatal error!' );\n end\n\n if ( npower2(i) < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FAC_LCM - Fatal error!\\n' );\n fprintf ( 1, ' One of the powers is negative!\\n' );\n error ( 'FAC_LCM - Fatal error!' );\n end\n\n npower3(i) = max ( npower1(i), npower2(i) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/subpak/fac_lcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6310411685034995}} {"text": "function[varargout]=blurspec(varargin)\n%BLURSPEC Returns the blurred and aliased spectrum given the autocovariance.\n%\n% BLURSPEC is used to rapidly compute blurred, aliased, and other \n% modified versions of a spectrum from a known autocovariance.\n%\n% Performing these calculations in the time domain, making use of \n% Fourier relationships between modified versions of the autocovariance\n% and spectrum, is much faster than working in the frequency domain.\n% __________________________________________________________________\n%\n% Blurred and aliased spectra\n%\n% [F,S]=BLURSPEC(R) inverse Fourier transforms a given *one-sided*\n% autocovariance R to obtain a spectrum S that incorporates the effects\n% of aliasing, as well as blurring by the default taper, the 'boxcar'.\n%\n% Here F is an array of frequencies and S is the one-sided Fourier \n% spectrum. If R is length N, the output arrays will be length (N/2+1) \n% if N is even and (N+1)/2 if N is odd.\n%\n% [F,SPP,SNN]=BLURSPEC(R) for complex-valued R returns SPP and SNN, the \n% positive and negative rotary spectra, respectively. \n%\n% BLURSPEC(DT,R) optionally uses the sample interval DT in computing the \n% frequency array F, and in setting the spectral levels.\n% __________________________________________________________________\n%\n% Tapered and aliased spectra\n%\n% BLURSPEC(R,'tapered',TAPER) incorporates the spectral smoothing due to \n% the use of data TAPER, rather than the boxcar taper, in addition to the\n% effects of aliasing. TAPER must be the same length as R.\n%\n% Note that BLURSPEC(R,'tapered',[]) simply returns the blurred spectrum,\n% as an empty taper is taken to indicate the periodogram.\n%\n% BLURSPEC(R,'window',WIN) uses the pre-computed window that is to \n% multiply the autocovariance function WIN. This is the half of the \n% sequence obtained by convolving the taper with itself. This version\n% is primarily used for speed in an internal call from MATERNFIT.\n% __________________________________________________________________\n%\n% Aliased-only spectrum\n%\n% BLURSPEC(R,'aliased') computes an approximation to *aliased* spectrum,\n% without blurring. This approximation will be accurate to the extent\n% that R has decayed to zero by the end of its duration.\n%\n% This is much faster than explicitly summing over aliased frequencies.\n% __________________________________________________________________\n%\n% Differenced spectra\n%\n% BLURSPEC(R,'difference') returns the blurred and aliased spectrum of \n% the first forward difference of the process with autocovariance R. In \n% this case the output will be length N-1.\n%\n% BLURSPEC(R,'seconddifference') returns the blurred and aliases spectrum\n% of the second forward difference of the process with autocovariance R. \n% The output will be length N-2.\n%\n% These options can be combined with the 'taper' and 'aliased' options \n% described above. \n% __________________________________________________________________\n%\n% 'blurspec --t' runs some tests.\n%\n% Usage: [f,S]=blurspec(R);\n% [f,Spp,Snn]=blurspec(dt,R); \n% [f,Spp,Snn]=blurspec(dt,R,'tapered',TAPER); \n% [f,Spp,Snn]=blurspec(dt,R,'aliased'); \n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2015--2020 J.M. Lilly and A.M. Sykulski \n% --- type 'help jlab_license' for details\n \nif strcmp(varargin{1}, '--t')\n blurspec_test,return\nend\n\ndt=1;\nif length(varargin{1})==1\n dt=varargin{1};\n varargin=varargin(2:end);\nend\nR=varargin{1};\n\nver='standard';\nstr='blurred';\npsi=[];\n\nvarargin=varargin(2:end);\nfor i=1:2\n if length(varargin)>0\n if ischar(varargin{end})\n if strcmpi(varargin{end}(1:3),'sec')||strcmpi(varargin{end}(1:3),'dif')||strcmpi(varargin{end}(1:3),'sta')\n ver=varargin{end};\n elseif strcmpi(varargin{end}(1:3),'ali')\n str=varargin{end};\n end\n varargin=varargin(1:end-1);\n end\n end\n if length(varargin)>1\n %length(varargin)\n if ischar(varargin{end-1})\n str=lower(varargin{end-1});\n psi=varargin{end};\n varargin=varargin(1:end-2);\n end\n end\nend\n\nif isempty(psi)&&strcmpi(str(1:3),'tap')\n str='blurred';\nend\n\nif strcmpi(ver(1:3),'dif')\n R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);\nelseif strcmpi(ver(1:3),'sec')\n R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);\n R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);\nend\n\nN=size(R,1);\nif strcmpi(str(1:3),'win')\n R=R.*vrep(psi,size(R,2),2);\nelseif strcmpi(str(1:3),'tap')\n if length(psi)~=size(R,1)\n error('Sizes of R and taper PSI do not match.')\n end\n win=conv(psi,psi);\n win=win(end-N+1:end);\n R=R.*vrep(win,size(R,2),2);\nelseif strcmpi(str(1:3),'blu')\n tri=[N:-1:1]'./N;\n if size(R,2)==1\n R=R.*tri;\n else\n R=R.*vrep(tri,size(R,2),2);\n end\nend %If str='aliased', do nothing\n%figure,plot(tri)\n\nR(1,:)=R(1,:)./2; %Don't forget to divide first element by two\nS=dt*2*real(fft(R));\nS=abs(S); %Sometimes there are small negative parts after blurring\n\n%Note, this is always correct for both even and odd length time series\nomega=fourier(N);\nSpp=S(1:length(omega),:);\nSnn=[S(1,:);S(end:-1:end-length(omega)+2,:)];\n%Snn=flipud([S(end-length(omega)+2:end,:);S(1,:)]); %Same but slower\n\nvarargout{1}=omega./dt;\nvarargout{2}=Spp;\nvarargout{3}=Snn;\n\nfunction[]=blurspec_test\n \nN=1000;\nalpha=1.5;\nh=1;\nA=1;\n\n[tau,R]=materncov(1,N,A,alpha,h);\n[f,Spp,Snn]=maternspec(1,N,A,alpha,h);\ntic;[f,Spp2,Snn2]=blurspec(R,'aliased');etime1=toc;\n\nmaternspec_spec=@(omega,A,omegao,H,alpha)(frac(H.^(2*alpha-1),materncfun(alpha))*frac(A.^2,((omega-omegao).^2+H.^2).^alpha));\ntic;\nM=100;\n[Sppa,Snna]=vzeros(length(fourier(N)),2*M+1);\nfor m=-M:M\n Sppa(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,0,h,alpha);\nend\nSnna=Sppa;\netime2=toc;\n\nvsum(Sppa,Snna,2);\n%figure,plot(f,[Spp2 Spp2],'k','linewidth',2),hold on,plot(f,[Sppa Snna],'r')\n%figure,plot(f,Spp2-Sppa,'k','linewidth',2),hold,plot(f,Snn2-Snna,'r','linewidth',2)\n\nb1=aresame(Spp2,Sppa,2e-6);\nb2=aresame(Snn2,Snna,2e-6);\n\nreporttest('BLURSPEC aliasing with covariance inversion matches direct calculation to 2e-6, even N',b1&&b2)\ndisp(['BLURSPEC aliasing with covariance inversion was ' num2str(etime2/etime1) ' times faster than direct calculation.'])\n\n\nN=999;\nomegao=1/4;\n[tau,R]=materncov(1,N,A,alpha,h,omegao);\n[f,Spp,Snn]=maternspec(1,N,A,alpha,h,omegao);\ntic;[f,Spp2,Snn2]=blurspec(R,'aliased');etime1=toc;\n\ntic;\nM=200;\n[Sppa,Snna]=vzeros(length(fourier(N)),2*M+1);\nfor m=-M:M\n Sppa(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,omegao,h,alpha);\n Snna(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,-omegao,h,alpha);\nend\netime2=toc;\n\nvsum(Sppa,Snna,2);\nb1=aresame(Spp2,Sppa,1e-6);\nb2=aresame(Snn2,Snna,1e-6);\n \nreporttest('BLURSPEC aliasing with covariance inversion matches direct calculation to 1e-6, odd N, frequency shift',b1&&b2)\ndisp(['BLURSPEC aliasing with covariance inversion was ' num2str(etime2/etime1) ' times faster than direct calculation.'])\n\nx=[10 1.1 0.1];\n[tau,acv]=materncov(1,N,x(1),x(2),x(3)); % autocovariance sequence\nS=abs(real(2*fft(acv.*(1-([0:N-1]')/N))-acv(1))); % blurred spectrum\n\nSpp2=S(1:floor(N/2)+1);\nSnn2=[S(1);S(end:-1:ceil(N/2)+1)]; \n[tau,R]=materncov(1,N,x(1),x(2),x(3));\n[f,Spp,Snn]=blurspec(R);\n\n%[f,Spp,Snn]=maternspec(N,x(1),x(2),x(3),'blurred');\n\nreporttest('BLURSPEC blurring matches alternate version for Matern', aresame(Spp,Spp2,1e-8)&&aresame(Snn,Snn2,1e-8))\n\n% N=1000;\n% alpha=10;\n% h=1/10;\n% sigma=7;\n% z=maternoise(1,[N 10000],sigma,-1/2,h,0,alpha);\n% psi=sleptap(size(z,1),3,1);\n% [f,spp,snn]=mspec(1,z,psi);\n% \n% \n% [tau,R]=materncov(1,N,sigma,-1/2,h,0,alpha);\n% [f,Spp,Snn]=blurspec(R,'taper',psi);\n% figure,plot(f,vmean([spp snn],2)),hold on,plot(f,Spp)\n% \n% N=1001;\n% z=maternoise(1,[N 10000],sigma,-1/2,h,0,alpha);;\n% psi=sleptap(size(z,1),3,1);\n% [f,spp,snn]=mspec(1,z,psi);\n% \n% \n% [tau,R]=materncov(1,N,sigma,-1/2,h,0,alpha);\n% [f,Spp,Snn]=blurspec(R,'taper',psi);\n% %figure,plot(f,vmean([spp snn],2)),hold on,plot(f,Spp)\n% \n% \n% N=1000;\n% alpha=1.5;\n% h=1;\n% A=1;\n% psi=sleptap(size(z,1),3,1);\n% \n% [f,Spp,Snn]=maternspec(dt,N,A,alpha,h/dt);\n% [tau,R]=materncov(dt,N,A,alpha,h);\n% tic;[f,Spp2,Snn2]=blurspec(dt,R,'tapered',psi);\n% tic;[f,Spp3,Snn3]=blurspec(dt,R);\n% figure,plot(f,[Spp Spp2 Spp3])\n% \n% \n% dt=7;\n% z=maternoise(dt,[N 1000],A,alpha,h/dt);\n% psi=sleptap(size(z,1),3,1);\n% [f,spphat,snnhat,spn]=mspec(dt,z,psi);\n% vmean(spphat,snnhat,2);\n% \n% \n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jmatern/blurspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6310395546016143}} {"text": "function xyd_xyn=xydistort_by_xynormalized(xyn, cam)\nk1=cam.kc(1);\nk2=cam.kc(2);\np1=cam.kc(3);\np2=cam.kc(4);\nk3=cam.kc(5);\nxn=xyn(1);\nyn=xyn(2);\nxyd_xyn=zeros(2);\n% xyd to xyn\nxyd_xyn(1,1)=k2*(xn^2 + yn^2)^2 + k3*(xn^2 + yn^2)^3 + 6*p2*xn + 2*p1*yn + xn*(2*k1*xn ...\n+ 4*k2*xn*(xn^2 + yn^2) + 6*k3*xn*(xn^2 + yn^2)^2) + k1*(xn^2 + yn^2) + 1;\n% xd to yn\nxyd_xyn(1,2)=2*p1*xn + 2*p2*yn + xn*(2*k1*yn + 4*k2*yn*(xn^2 + yn^2) + 6*k3*yn*(xn^2 + yn^2)^2); \n% yd to (xn, yn) \nxyd_xyn(2,1)=2*p1*xn + 2*p2*yn + yn*(2*k1*xn + 4*k2*xn*(xn^2 + yn^2) + 6*k3*xn*(xn^2 + yn^2)^2);\nxyd_xyn(2,2)=k2*(xn^2 + yn^2)^2 + k3*(xn^2 + yn^2)^3 + 2*p2*xn + 6*p1*yn + yn*(2*k1*yn ...\n+ 4*k2*yn*(xn^2 + yn^2) + 6*k3*yn*(xn^2 + yn^2)^2) + k1*(xn^2 + yn^2) + 1;\n ", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/imageproc/xydistort_by_xynormalized.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.630994543268421}} {"text": "function line_num = sphere_cubed_line_num ( n )\n\n%*****************************************************************************80\n%\n%% SPHERE_CUBED_LINE_NUM counts lines on a cubed sphere grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sections into which each face of\n% the cube is to be divided.\n%\n% Output, integer LINE_NUM, the number of lines.\n%\n line_num = 0;\n%\n% If N = 1, the corners form 12 lines.\n%\n if ( n == 1 )\n line_num = 12;\n return\n%\n% If 1 < N, each of 8 corners connects to three neighboring edges.\n%\n else\n line_num = line_num + 8 * 3;\n end\n%\n% If 2 < N, then each of the 12 edges includes lines.\n%\n if ( 2 < n )\n line_num = line_num + 12 * ( n - 2 );\n end\n%\n% Lines that belong to one of the six faces.\n%\n if ( 1 < n )\n line_num = line_num + 6 * 2 * n * ( n - 1 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_grid/sphere_cubed_line_num.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.6309908417838198}} {"text": "function [QDu,area,center,QDlambda,stbElem] = graduVEM(node,elem,u)\n%% GRADUVEM the projected gradient of a linear virtual element function.\n%\n% QDu = GRADUVEM(node,elem,u) compute the L2 projection of the gradient of \n% a virtual element function u on a polygonal mesh representing by (node,elem).\n% \n% [QDu,area,center,QDlambda,stbElem] = GRADUVEM(node,elem,u) also outputs areas, centroids, \n% elementwise stabilization, and the L2 projection of Dlambda which is the gradient of P1 \n% conforming VEM basis. QDu{t}(i,1) is the x-component of the i-th vertex's basis in t-th element.\n% stbElem(t,:) is the \\ell^2 norm of (I-P)u_h on each element.\n% \n% Remark: this routine is mostly following Long's vectorization in PoissonVEM,\n% however is ONLY implemented for Matlab version > R2016b\n% see: https://scaomath.github.io/blog/MATLAB-update-on-array-compatibility/\n%\n% See also gradu, gradbasis, PoissonVEM\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n%%\nif ~iscell(elem); elem = num2cell(elem,2); end\n\n%%\nNT = size(elem,1);\nQDu = zeros(NT,2);\narea = zeros(NT,1);\ncenter = zeros(NT,2);\nQDlambda = cell(NT,1);\nstbElem = zeros(NT,1); % || (I- P) u ||_{l^2,K}\n%%\nelemVertexNumber = cellfun('length',elem);% the number of vertices per element\nminNv = min(elemVertexNumber);\nmaxNv = max(elemVertexNumber);\n\n\n%% \nfor nV = minNv:maxNv\n isNv = (elemVertexNumber == nV); % index of elements with Nv vertices\n if ~any(isNv); continue; end\n elemNv = cell2mat(elem(isNv));\n NelemNv = sum(isNv);\n x1 = reshape(node(elemNv,1),[NelemNv,nV]);\n y1 = reshape(node(elemNv,2),[NelemNv,nV]);\n x2 = circshift(x1,[0,-1]);\n y2 = circshift(y1,[0,-1]);\n bdIntegral = x1.*y2 - y1.*x2;\n areaNv = sum(bdIntegral,2)/2; \n xc = sum((x1+x2).*bdIntegral,2)./abs(areaNv)/6;\n yc = sum((y1+y2).*bdIntegral,2)./abs(areaNv)/6;\n center(isNv,:) = [xc, yc];\n normVecx = y2 - y1; % normal vector is a rotation of edge vectors\n normVecy = x1 - x2;\n Bx = (normVecx + circshift(normVecx,[0,1]))./(2*areaNv); % average of normal vectors\n By = (normVecy + circshift(normVecy,[0,1]))./(2*areaNv); % in adjacent edges\n QDlambdaNv = reshape([Bx, By]',[nV,2,NelemNv]);\n QDlambda(isNv) = squeeze(num2cell(QDlambdaNv, [1, 2]));\n uh2elemNv = u(elemNv);\n if NelemNv == 1; uh2elemNv = uh2elemNv'; end % in this case: size(uh2elemNv,2) == 1\n QDudx = sum(uh2elemNv.*Bx, 2);\n QDudy = sum(uh2elemNv.*By, 2);\n QDlambda(isNv) = squeeze(num2cell(QDlambdaNv, [1, 2]));\n %%\n area(isNv,:) = abs(areaNv);\n QDu(isNv,:) = [QDudx, QDudy];\n \n %% compute stablization\n if nargout > 4\n h = sign(areaNv).*sqrt(abs(areaNv)); % h = sqrt(area) not the diameter\n cx = mean(reshape(node(elemNv(:),1),[NelemNv,nV]),2);\n cy = mean(reshape(node(elemNv(:),2),[NelemNv,nV]),2);\n Dx = (x1 - cx)./h; Dy = (y1 - cy)./h; % m = (x - cx)/h\n IminusP = zeros(NelemNv,nV,nV);\n for i = 1:nV\n for j = 1:nV\n IminusP(:,i,j) = - 1/nV - Dx(:,i).*Bx(:,j).*abs(h) - Dy(:,i).*By(:,j).*abs(h);\n end\n IminusP(:,i,i) = ones(NelemNv,1) + IminusP(:,i,i);\n end\n if NelemNv == 1\n IminusP = squeeze(IminusP);\n utIminusPu = uh2elemNv*IminusP*uh2elemNv';\n else\n IminusPu = sum(bsxfun(@times, IminusP, uh2elemNv), 2);\n utIminusPu = sum(uh2elemNv.*squeeze(IminusPu),2);\n end\n \n stbElem(isNv) = sqrt(abs(utIminusPu));\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/graduVEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6308976797073247}} {"text": "function [x, infos] = anls_nmf(V, rank, in_options)\n% Alternative non-negative least squares (ANLS) for non-negative matrix factorization (NMF).\n%\n% The problem of interest is defined as\n%\n% min || V - WH ||_F^2,\n% where \n% {V, W, H} > 0.\n%\n% Given a non-negative matrix V, factorized non-negative matrices {W, H} are calculated.\n%\n%\n% Inputs:\n% V : (m x n) non-negative matrix to factorize\n% rank : rank\n% in_options : options\n%\n%\n% References:\n% Jingu Kim, Yunlong He, and Haesun Park,\n% \"Algorithms for Nonnegative Matrix and Tensor Factorizations: A Unified View \n% Based on Block Coordinate Descent Framework,\"\n% Journal of Global Optimization, 58(2), pp. 285-319, 2014.\n%\n% Jingu Kim and Haesun Park.\n% \"Fast Nonnegative Matrix Factorization: An Active-set-like Method and Comparisons,\"\n% SIAM Journal on Scientific Computing (SISC), 33(6), pp. 3261-3281, 2011.\n%\n%\n% Output:\n% x : non-negative matrix solution, i.e., x.W: (m x rank), x.H: (rank x n)\n% infos : log information\n% epoch : iteration nuber\n% cost : objective function value\n% optgap : optimality gap\n% time : elapsed time\n% grad_calc_count : number of sampled data elements (gradient calculations)\n%\n%\n% This file is part of NMFLibrary\n%\n% This code calls functions {nnls1_asgivens, nnlsm_activeset, nnlsm_blockpivot}\n% written by Jingu Kim. See https://github.com/kimjingu/nonnegfac-matlab.\n%\n% Ported by H.Kasai on Apr. 04, 2017\n%\n% Change log: \n%\n% Oct. 27, 2017 (Hiroyuki Kasai): Fixed algorithm. \n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n% Jun. 24, 2022 (Hiroyuki Kasai): Added momentum acceleration mode and mofified.\n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = [];\n local_options.alg = 'anls_asgroup';\n local_options.sub_mode = 'std'; \n local_options.delta = 0.1;\n local_options.inner_max_epoch = 500;\n local_options.inner_max_epoch_parameter = 0.5; \n local_options.beta0 = 0.5;\n local_options.eta = 1.5; \n local_options.gammabeta = 1.01;\n local_options.gammabetabar = 1.005; \n local_options.momentum_h = 0; \n local_options.momentum_w = 0; \n local_options.scaling = true;\n local_options.warm_restart = false; \n\n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options); \n\n % set paramters\n if ~strcmp(options.alg, 'anls_asgroup') && ~strcmp(options.alg, 'anls_asgivens') ...\n && ~strcmp(options.alg, 'anls_bpp') \n fprintf('Invalid algorithm: %s. Therfore, we use anls_asgroup (i.e., ANLS with Active Set Method and Column Grouping).\\n', options.alg);\n options.alg = 'anls_asgroup';\n end\n \n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n W = init_factors.W;\n H = init_factors.H; \n \n % initialize\n method_name = sprintf('ANLS (%s)', options.alg);\n epoch = 0; \n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name); \n end \n \n if options.scaling\n [W, H] = normalize_WH(V, W, H, rank, 'type1');\n end\n \n % initialize for ANLS\n [options, beta, betamax] = check_momemtum_setting(options); \n \n if options.warm_restart\n nV = norm(V, 'fro');\n rel_error = zeros(1, options.max_epoch);\n rel_error(1) = sqrt(nV^2 - 2*sum(sum(V * H' .* W)) + sum(sum( H * H' .* (W'*W)))) / nV; \n end\n W_prev = W; \n H_prev = H; \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, W, H, [], options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n end \n\n % set start time\n start_time = tic();\n\n % main loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end \n\n \n %% update H \n if strcmp(options.alg, 'anls_asgroup')\n ow = 0;\n \n H = nnlsm_activeset(W'*W, W'*V, ow, 1, H);\n\n elseif strcmp(options.alg, 'anls_asgivens')\n ow = 0;\n \n WtV = W' * V;\n for i=1:size(H,2)\n H(:,i) = nnls1_asgivens(W'*W, WtV(:,i), ow, 1, H(:,i));\n end\n\n elseif strcmp(options.alg, 'anls_bpp')\n \n H = nnlsm_blockpivot(W'*W, W'*V, 1, H);\n \n end\n \n % perform momentum for H\n if strcmp(options.sub_mode, 'momentum')\n [H, H_tmp1, H_tmp2] = do_momentum_h(H, H_prev, beta, epoch, options);\n end\n \n \n \n %% update W\n if strcmp(options.alg, 'anls_asgroup')\n ow = 0;\n \n W = nnlsm_activeset(H*H', H*V', ow, 1, W');\n W = W';\n \n elseif strcmp(options.alg, 'anls_asgivens')\n ow = 0;\n \n HAt = H * V';\n Wt = W';\n for i=1:size(W,1)\n Wt(:,i) = nnls1_asgivens(H*H', HAt(:,i), ow, 1, Wt(:,i));\n end\n W = Wt';\n \n elseif strcmp(options.alg, 'anls_bpp')\n \n W = nnlsm_blockpivot(H*H', H*V', 1, W');\n W = W';\n\n end \n \n % perform momentum for W \n if strcmp(options.sub_mode, 'momentum')\n [W, H, W_tmp1] = do_momentum_w(W, W_prev, H, H_prev, H_tmp1, beta, epoch, options);\n end \n \n % perform warm_restart\n if options.warm_restart\n [W, H, W_prev, H_prev, rel_error, beta, betamax, options] = ...\n warm_restart(V, W, H, rank, W_prev, H_prev, W_tmp1, H_tmp1, H_tmp2, rel_error, beta, betamax, epoch, options);\n end \n \n % measure elapsed time\n elapsed_time = toc(start_time); \n \n % measure gradient calc count\n grad_calc_count = grad_calc_count + m*n;\n\n % update epoch\n epoch = epoch + 1; \n \n % store info\n infos = store_nmf_info(V, W, H, [], options, infos, epoch, grad_calc_count, elapsed_time); \n \n % display info\n display_info(method_name, epoch, infos, options); \n \n end\n\n x.W = W;\n x.H = H;\n\nend", "meta": {"author": "hiroyuki-kasai", "repo": "NMFLibrary", "sha": "ed44132dfe1b5495df685006b42259f0bd16bea3", "save_path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-NMFLibrary/NMFLibrary-ed44132dfe1b5495df685006b42259f0bd16bea3/solver/frobenius_norm/anls_nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6308976671129893}} {"text": "function Agal=step_mg_diff_setup(x,y)\n%mg_diff_setup_step GMG diffusion problem on step domain\n% Agal=mg_diff_setup_step(x,y)\n% input\n% x x coordinate vector for coarse grid\n% y y coordinate vector for coarse grid\n% output\n% Agal discrete diffusion operator\n%\n% IFISS function: AR; 20 January, 2003.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\nn=length(y)-1; np=n/2; nq=n/4;\nnvtx= np*(np*1) + (5*np+1)*(n+1);\n% negative x-values\nxneg=x(1:n/2);yneg=y(1:n/2);\nxpos=x(n/2+1:end);ypos=y(n/2+1:end);\n[Xneg,Ypos]=meshgrid(xneg,ypos);\nxx=reshape(Xneg',np*(np+1),1);\nyy=reshape(Ypos',np*(np+1),1);\nxyleft=[xx(:),yy(:)];\n% assembly process\nkx = 1;\nky = 1;\nmel=0;\n% loop over 2x2 macroelements\nfor j=1:nq\n for i=1:nq\n mref=np*(ky-1)+kx;\n pref=nq*(j-1)+i;\n mel=mel+1;\n nvv(1) = mref;\n nvv(2) = mref+2;\n nvv(3) = mref+2*np+2;\n nvv(4) = mref+2*np;\n nvv(5) = mref+1;\n nvv(6) = mref+np+2; \n nvv(7) = mref+2*np+1; \n nvv(8)= mref+np;\n nvv(9)= mref+np+1; \n npp(1) = pref;\n npp(2) = pref+1;\n npp(3) = pref+nq+1;\n npp(4) = pref+nq;\n mv(mel,1:9)=nvv(1:9);\n mp(mel,1:4)=npp(1:4);\n kx = kx + 2;\n end\n ky = ky + 2;\n kx = 1;\nend\n%\n% correction along the internal boundary\nmref=2*np*(3*np+1)+1;\npref=2*nq*(3*nq+1)+1;\nfor mel=nq:nq:nq*nq;\n nvv=mv(mel,:);\n npp=mp(mel,:);\n nvv(2) = mref;\n nvv(3) = mref+10*np+2;\n nvv(6) = mref+5*np+1; \n npp(2) = pref;\n npp(3) = pref+5*nq+1;\n mv(mel,1:9)=nvv(1:9);\n mp(mel,1:4)=npp(1:4);\n mref=mref+10*np+2;\n pref=pref+5*nq+1;\nend\t\n%\n% positive x_values\n[Xpos,Y]=meshgrid(xpos,y);\nxx=reshape(Xpos',(5*np+1)*(n+1),1);\nyy=reshape(Y',(5*np+1)*(n+1),1);\nxyright=[xx(:),yy(:)];\nxy=[xyleft;xyright]; \n%\nkx = 1;\nky = 1;\nmel=nq*nq;\nfor j=1:np\n for i=1:5*nq\n mref = (5*np+1)*(ky-1)+kx + np*(np+1);\n pref = (5*nq+1)*(j-1)+i + nq*(nq+1);\n mel=mel+1;\n nvv(1) = mref;\n nvv(2) = mref+2;\n nvv(3) = mref+10*np+4;\n nvv(4) = mref+10*np+2;\n nvv(5) = mref+1;\n nvv(6) = mref+5*np+3; \n nvv(7) = mref+10*np+3; \n nvv(8)= mref+5*np+1;\n nvv(9)= mref+5*np+2; \n npp(1) = pref;\n npp(2) = pref+1;\n npp(3) = pref+5*nq+2;\n npp(4) = pref+5*nq+1;\n mv(mel,1:9)=nvv(1:9);\n mp(mel,1:4)=npp(1:4);\n kx = kx + 2;\n end\n ky = ky + 2;\n kx = 1;\nend\n%\n% compute boundary vertices\n% six boundary edges \nk1=find( xy(:,1) <0 & xy(:,2)==0 );\ne1=[]; for k=1:mel, if any(mv(k,5)==k1), e1=[e1,k]; end, end\nef1=ones(size(e1));\n%\nk2=find( xy(:,1)==0 & xy(:,2)<=0 );\ne2=[]; for k=1:mel, if any(mv(k,8)==k2), e2=[e2,k]; end, end\nef2=4*ones(size(e2));\n%\nk3=find( xy(:,1) >0 & xy(:,2)==-1);\ne3=[]; for k=1:mel, if any(mv(k,5)==k3), e3=[e3,k]; end, end\nef3=ones(size(e3));\n%\nk5=find( xy(:,2)==1 );\ne5=[]; for k=1:mel, if any(mv(k,7)==k5), e5=[e5,k]; end, end\nef5=3*ones(size(e5));\n%\nk6=find( xy(:,1)==-1 & xy(:,2)<1 & xy(:,2) >0 );\ne6=[]; for k=1:mel, if any(mv(k,8)==k6), e6=[e6,k]; end, end\nef6=4*ones(size(e6));\n%\nbound=sort([k1;k2;k3;k5;k6]);\nmbound=[e1',ef1';e2',ef2';e3',ef3';;e5',ef5';e6',ef6'];\n%\n%% set up matrices for Q1 approximation\n[ev,ebound]=mg_q1grid(x,y,xy,mv,bound,mbound);\n[A,M,fdummy] = mg_q1diff(xy,ev);\n%\n% impose zero boundary conditions\n[Agal] = mg_zerobc(A,xy,bound);\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/solvers/mg_diff_setup_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6308976621709803}} {"text": "function [ozf] = dyn2ozf(dyn)\n% Convert force from dyne to ounces (force). \n% Chad A. Greene 2012\nozf = dyn*0.000035969431019;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/dyn2ozf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6308976540400273}} {"text": "function poly2 = clipPolygon(polygon, w)\n%CLIPPOLYGON Clip a polygon with a rectangular box\n%\n% POLY2 = clipPolygon(POLY, BOX);\n% POLY is [Nx2] array of points\n% BOX has the form: [XMIN XMAX YMIN YMAX].\n% Returns the polygon created by the itnersection of the polygon POLY and\n% the bounding box BOX.\n%\n% Note: Works only for convex polygons at the moment.\n%\n% See also:\n% polygons2d, boxes2d, clipPolygonHP\n%\n\n% ---------\n% author : David Legland \n% created the 14/05/2005.\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2007/09/14 fix doc\n\n% check case of polygons stored in cell array\nif iscell(polygon)\n poly2 = cell(1, length(polygon));\n for i=1:length(polygon)\n poly2{i} = clipPolygon(polygon{i}, w);\n end\n return;\nend\n\n% check case of empty polygon\nN = size(polygon, 1);\nif N==0\n poly2 = zeros(0, 2);\n return\nend\n\n% create edges array of polygon\nedges = [polygon polygon([2:N 1], :)];\n\n% clip edges\nedges = clipEdge(edges, w);\n\n% select non empty edges, and get their vertices\nind = sum(abs(edges), 2)>1e-14;\npts = unique([edges(ind, 1:2); edges(ind, 3:4)], 'rows');\n\n% add vertices of window corner\ncorners = [w(1) w(3); w(1) w(4);w(2) w(3);w(2) w(4)];\nind = inpolygon(corners(:,1), corners(:,2), polygon(:,1), polygon(:,2));\npts = [pts; corners(ind, :)];\n\n% polygon totally outside the window\nif size(pts, 1)==0\n poly2 = pts;\n return;\nend\n\n% compute centroid of visible polygon\npc = centroid(pts);\n\n% sort vertices around polygon\nangle = edgeAngle([repmat(pc, [size(pts, 1) 1]) pts]);\n[dummy, I] = sort(angle); %#ok\n\n% create resulting polygon\npoly2 = pts(I, :);\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/polygons2d/clipPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6308902070330252}} {"text": "classdef MOEADDE_F2 < PROBLEM\n% \n% Benchmark MOP for testing MOEA/D-DE\n\n%------------------------------- Reference --------------------------------\n% H. Li and Q. Zhang, Multiobjective optimization problems with complicated\n% Pareto sets, MOEA/D and NSGA-II, IEEE Transactions on Evolutionary\n% Computation, 2009, 13(2): 284-302.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = [0,-ones(1,obj.D-1)];\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n J1 = 3 : 2 : obj.D;\n J2 = 2 : 2 : obj.D;\n PopObj(:,1) = X(:,1) + 2*mean((X(:,J1)-sin(repmat(6*pi*X(:,1),1,length(J1))+repmat(J1*pi/obj.D,size(X,1),1))).^2,2);\n PopObj(:,2) = 1-sqrt(X(:,1)) + 2*mean((X(:,J2)-sin(repmat(6*pi*X(:,1),1,length(J2))+repmat(J2*pi/obj.D,size(X,1),1))).^2,2);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - R(:,1).^0.5;\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/MOEADDE_F2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919973399709, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.6308901968248063}} {"text": "function [dist,PP0] = pointTriangleDistance(TRI,P)\n% POINTTRIANGLEDISTANCE Calculate distance between a point and a triangle\n% in 3D\n%\n% SYNTAX\n% dist = pointTriangleDistance(TRI,P)\n% [dist,PP0] = pointTriangleDistance(TRI,P)\n%\n% DESCRIPTION\n% Calculate the distance of a given point P from a triangle TRI.\n% Point P is a row vector of the form 1x3. The triangle is a matrix\n% formed by three rows of points TRI = [P1;P2;P3] each of size 1x3.\n% dist = pointTriangleDistance(TRI,P) returns the distance of the point P\n% to the triangle TRI.\n% [dist,PP0] = pointTriangleDistance(TRI,P) additionally returns the\n% closest point PP0 to P on the triangle TRI.\n\n% Author: Gwendolyn Fischer\n% Release: 1.0\n% Release date: 09/02/02\n% Release: 1.1 Fixed Bug because of normalization\n% Release: 1.2 Fixed Bug because of typo in region 5 20101013\n% Release: 1.3 Fixed Bug because of typo in region 2 20101014\n\n% Minor modifications by Ramon Casero for the Gerardus\n% Project.\n% Version: 0.1.0\n\n% Possible extention could be a version tailored not to return the distance\n% and additionally the closest point, but instead return only the closest\n% point. Could lead to a small speed gain.\n\n% Example:\n% %% The Problem\n% P0 = [0.5 -0.3 0.5];\n% \n% P1 = [0 -1 0];\n% P2 = [1 0 0];\n% P3 = [0 0 0];\n% \n% vertices = [P1; P2; P3];\n% faces = [1 2 3];\n% \n% %% The Engine\n% [dist,PP0] = pointTriangleDistance([P1;P2;P3],P0);\n%\n% %% Visualization\n% [x,y,z] = sphere(20);\n% x = dist*x+P0(1);\n% y = dist*y+P0(2);\n% z = dist*z+P0(3);\n% \n% figure\n% hold all\n% patch('Vertices',vertices,'Faces',faces,'FaceColor','r','FaceAlpha',0.8);\n% plot3(P0(1),P0(2),P0(3),'b*');\n% plot3(PP0(1),PP0(2),PP0(3),'*g')\n% surf(x,y,z,'FaceColor','b','FaceAlpha',0.3)\n% view(3)\n\n% The algorithm is based on \n% \"David Eberly, 'Distance Between Point and Triangle in 3D',\n% Geometric Tools, LLC, (1999)\"\n% http:\\\\www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf\n%\n% ^t\n% \\ |\n% \\reg2|\n% \\ |\n% \\ |\n% \\ |\n% \\|\n% *P2\n% |\\\n% | \\\n% reg3 | \\ reg1\n% | \\\n% |reg0\\ \n% | \\ \n% | \\ P1\n% -------*-------*------->s\n% |P0 \\ \n% reg4 | reg5 \\ reg6\n\n\n%% Do some error checking\nif nargin<2\n error('pointTriangleDistance: too few arguments see help.');\nend\nP = P(:)';\nif size(P,2)~=3\n error('pointTriangleDistance: P needs to be of length 3.');\nend\n\nif size(TRI)~=[3 3]\n error('pointTriangleDistance: TRI needs to be of size 3x3.');\nend\n\n% ToDo: check for colinearity and/or too small triangles.\n\n\n% rewrite triangle in normal form\nB = TRI(1,:);\nE0 = TRI(2,:)-B;\n%E0 = E0/sqrt(sum(E0.^2)); %normalize vector\nE1 = TRI(3,:)-B;\n%E1 = E1/sqrt(sum(E1.^2)); %normalize vector\n\n\nD = B - P;\na = dot(E0,E0);\nb = dot(E0,E1);\nc = dot(E1,E1);\nd = dot(E0,D);\ne = dot(E1,D);\nf = dot(D,D);\n\ndet = a*c - b*b; % do we have to use abs here?\ns = b*e - c*d;\nt = b*d - a*e;\n\n% Terible tree of conditionals to determine in which region of the diagram\n% shown above the projection of the point into the triangle-plane lies.\nif (s+t) <= det\n if s < 0\n if t < 0\n %region4\n if (d < 0)\n t = 0;\n if (-d >= a)\n s = 1;\n sqrDistance = a + 2*d + f;\n else\n s = -d/a;\n sqrDistance = d*s + f;\n end\n else\n s = 0;\n if (e >= 0)\n t = 0;\n sqrDistance = f;\n else\n if (-e >= c)\n t = 1;\n sqrDistance = c + 2*e + f;\n else\n t = -e/c;\n sqrDistance = e*t + f;\n end\n end\n end %of region 4\n else\n % region 3\n s = 0;\n if e >= 0\n t = 0;\n sqrDistance = f;\n else\n if -e >= c\n t = 1;\n sqrDistance = c + 2*e +f;\n else\n t = -e/c;\n sqrDistance = e*t + f;\n end\n end\n end %of region 3 \n else\n if t < 0\n % region 5\n t = 0;\n if d >= 0\n s = 0;\n sqrDistance = f;\n else\n if -d >= a\n s = 1;\n sqrDistance = a + 2*d + f;% GF 20101013 fixed typo d*s ->2*d\n else\n s = -d/a;\n sqrDistance = d*s + f;\n end\n end\n else\n % region 0\n invDet = 1/det;\n s = s*invDet;\n t = t*invDet;\n sqrDistance = s*(a*s + b*t + 2*d) ...\n + t*(b*s + c*t + 2*e) + f;\n end\n end\nelse\n if s < 0\n % region 2\n tmp0 = b + d;\n tmp1 = c + e;\n if tmp1 > tmp0 % minimum on edge s+t=1\n numer = tmp1 - tmp0;\n denom = a - 2*b + c;\n if numer >= denom\n s = 1;\n t = 0;\n sqrDistance = a + 2*d + f; % GF 20101014 fixed typo 2*b -> 2*d\n else\n s = numer/denom;\n t = 1-s;\n sqrDistance = s*(a*s + b*t + 2*d) ...\n + t*(b*s + c*t + 2*e) + f;\n end\n else % minimum on edge s=0\n s = 0;\n if tmp1 <= 0\n t = 1;\n sqrDistance = c + 2*e + f;\n else\n if e >= 0\n t = 0;\n sqrDistance = f;\n else\n t = -e/c;\n sqrDistance = e*t + f;\n end\n end\n end %of region 2\n else\n if t < 0\n %region6 \n tmp0 = b + e;\n tmp1 = a + d;\n if (tmp1 > tmp0)\n numer = tmp1 - tmp0;\n denom = a-2*b+c;\n if (numer >= denom)\n t = 1;\n s = 0;\n sqrDistance = c + 2*e + f;\n else\n t = numer/denom;\n s = 1 - t;\n sqrDistance = s*(a*s + b*t + 2*d) ...\n + t*(b*s + c*t + 2*e) + f;\n end\n else \n t = 0;\n if (tmp1 <= 0)\n s = 1;\n sqrDistance = a + 2*d + f;\n else\n if (d >= 0)\n s = 0;\n sqrDistance = f;\n else\n s = -d/a;\n sqrDistance = d*s + f;\n end\n end\n end\n %end region 6\n else\n % region 1\n numer = c + e - b - d;\n if numer <= 0\n s = 0;\n t = 1;\n sqrDistance = c + 2*e + f;\n else\n denom = a - 2*b + c;\n if numer >= denom\n s = 1;\n t = 0;\n sqrDistance = a + 2*d + f;\n else\n s = numer/denom;\n t = 1-s;\n sqrDistance = s*(a*s + b*t + 2*d) ...\n + t*(b*s + c*t + 2*e) + f;\n end\n end %of region 1\n end\n end\nend\n\n% account for numerical round-off error\nif (sqrDistance < 0)\n sqrDistance = 0;\nend\n\ndist = sqrt(sqrDistance);\n\nif nargout>1\n PP0 = B + s*E0 + t*E1;\nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/pointTriangleDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6308592967896985}} {"text": "function UNew = fluidPeriodic3D(varargin)\n% fluidPeriodic3D: solve fluid registraion in 3D with Periodic\n% boundary conditions\n%\n%\n% author: Nathan D. Cahill\n% email: nathan.cahill@rit.edu\n% affiliation: Rochester Institute of Technology\n% date: January 2014\n% licence: GNU GPL v3\n%\n% Copyright Nathan D. Cahill\n% Code available from https://github.com/tomdoel/npReg\n%\n%\n\n% parse input arguments\n[DU,F,mu,lambda,PixSize,M,N,P,RegularizerFactor,HX,HY,HZ] = parse_inputs(varargin{:});\n\n% multiply F by adjoint of Navier-Lame equations\nFNew = adjointNL(F/RegularizerFactor,mu,lambda,0,M,N,P);\n\n% compute Fourier transform of new force field\nFS = discreteFourierTransform(FNew,M,N,P);\n\n% construct images of coordinates scaled by pi/(N or M or P)\n[a,b,c] = ndgrid(pi*(0:(M-1))/(M-1),pi*(0:(N-1))/(N-1),pi*(0:(P-1))/(P-1));\n\n% construct LHS factor\nLHSfactor = mu.*(lambda+2*mu).*(2*cos(a) + 2*cos(b) + 2*cos(c) - 6).^2;\n\n% if gamma is zero, set origin term to 1, as DC term does not matter\nLHSfactor(1,1,1) = 1;\n\n% solve for FFT of U\nVS = cat(4,FS(:,:,:,1)./LHSfactor,FS(:,:,:,2)./LHSfactor,FS(:,:,:,3)./LHSfactor);\n\n% perform inverse FFT\nV = discreteFourierTransformInverse(VS,M,N,P);\n\n% now perform Euler integration to construct new displacements\nUNew = zeros(M,N,P,3);\nUNew(:,:,:,1) = (1 - imfilter(V(:,:,:,1),HX,'replicate','same')).*V(:,:,:,1) - ...\n imfilter(V(:,:,:,2),HY,'replicate','same').*V(:,:,:,2) - ...\n imfilter(V(:,:,:,3),HZ,'replicate','same').*V(:,:,:,3);\nUNew(:,:,:,2) = -imfilter(V(:,:,:,1),HY,'replicate','same').*V(:,:,:,1) + ...\n (1 - imfilter(V(:,:,:,2),HY,'replicate','same')).*V(:,:,:,2) - ...\n imfilter(V(:,:,:,3),HY,'replicate','same').*V(:,:,:,3);\nUNew(:,:,:,3) = -imfilter(V(:,:,:,1),HZ,'replicate','same').*V(:,:,:,1) - ...\n imfilter(V(:,:,:,2),HZ,'replicate','same').*V(:,:,:,2) + ...\n (1 - imfilter(V(:,:,:,3),HZ,'replicate','same')).*V(:,:,:,3);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction FS = discreteFourierTransformInverse(F,M,N,P);\n% compute inverse DFT of 3-D vector field\n\n% initialize resulting array\nFS = F;\n\n% first perform sine transform down columns\nfor p=1:P\n for n=1:N\n FS(:,n,p,:) = ifft(FS(:,n,p,:),M,1,'symmetric');\n end\nend\n\n% next perform sine transform across rows\nfor p=1:P\n for m=1:M\n FS(m,:,p,:) = ifft(FS(m,:,p,:),N,2,'symmetric');\n end\nend\n\n% finally perform sine transform across pages\nfor n=1:N\n for m=1:M\n FS(m,n,:,:) = ifft(FS(m,n,:,:),P,3,'symmetric');\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction FS = discreteFourierTransform(F,M,N,P);\n% compute DFT of 3-D vector field\n\n% initialize resulting array\nFS = complex(F);\n\n% first perform sine transform down columns\nfor p=1:P\n for n=1:N\n FS(:,n,p,:) = fft(FS(:,n,p,:),M,1);\n end\nend\n\n% next perform sine transform across rows\nfor p=1:P\n for m=1:M\n FS(m,:,p,:) = fft(FS(m,:,p,:),N,2);\n end\nend\n\n% finally perform sine transform across pages\nfor n=1:N\n for m=1:M\n FS(m,n,:,:) = fft(FS(m,n,:,:),P,3);\n end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction FNew = adjointNL(F,mu,lambda,gamma,M,N,P);\n% multiply vector field F by adjoint Navier-Lame equations\n\n% initialize FNew\nFNew = zeros(M,N,P,3);\n\n% construct filter that implements 3-D Laplacian\nL = (lambda+2*mu)*cat(3,[0 0 0;0 1 0;0 0 0],[0 1 0;1 -6 1;0 1 0],[0 0 0;0 1 0;0 0 0]);\n\n% we will need to use L to form two different filters\n% L1 = -(lambda+2*mu)*L; L1(2,2,2) = gamma + L1(2,2,2);\n% L2 = -mu*L; L2(2,2,2) = gamma + L2(2,2,2);\n\n% construct grad div filters\nGD11 = (lambda+mu)*cat(3,zeros(3,3),[0 1 0;0 -2 0;0 1 0],zeros(3,3));\nGD22 = ipermute(GD11,[2 1 3]);\nGD33 = ipermute(GD11,[3 2 1]);\nGD23 = zeros(3,3,3);\nGD23(2,1,1) = 1; GD23(2,3,3) = 1; GD23(2,1,3) = -1; GD23(2,3,1) = -1;\nGD23 = GD23*(lambda+mu)/4;\nGD12 = ipermute(GD23,[3 1 2]);\nGD13 = ipermute(GD23,[2 3 1]);\n\n% perform filtering\nFNew(:,:,:,1) = imfilter(F(:,:,:,1),L-GD11,'replicate') + ...\n imfilter(F(:,:,:,2),-GD12,'replicate') + ...\n imfilter(F(:,:,:,3),-GD13,'replicate');\nFNew(:,:,:,2) = imfilter(F(:,:,:,1),-GD12,'replicate') + ...\n imfilter(F(:,:,:,2),L-GD22,'replicate') + ...\n imfilter(F(:,:,:,3),-GD23,'replicate');\nFNew(:,:,:,3) = imfilter(F(:,:,:,1),-GD13,'replicate') + ...\n imfilter(F(:,:,:,2),-GD23,'replicate') + ...\n imfilter(F(:,:,:,3),L-GD33,'replicate');\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [DU,F,mu,lambda,PixSize,M,N,P,RegularizerFactor,HX,HY,HZ] = parse_inputs(varargin);\n\n% get displacement field and check size\nF = varargin{2};\nPixSize = varargin{4}(1:3);\nM = varargin{5};\nN = varargin{6};\nP = varargin{7};\nmu = varargin{8};\nlambda = varargin{9};\nRegularizerFactor = varargin{10};\nDU = varargin{11};\nHX = varargin{12};\nHY = varargin{13};\nHZ = varargin{14};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/npReg/npRegLib/fluidPeriodic3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6308592915581726}} {"text": "%% This function will generate the simulation data of an ODE function.\n%You could determine the noise level by input variable \"Noise\". If you do\n%not want any noise, set noise to zero. Please indicate whether your ODE\n%function have control input, if the answer is yes, please set the\n%\"Control\" as 1.\n\n% Last Update: 2019/04/21\n% Coded By: K\n\nfunction [d_Data,Data]=Get_Sim_Data(ODE,state0,u,tspan,Noise,Control,Shuffle)\n%% Get the size of the state and control\n[N1,M1]=size(state0);\n[N2,M2]=size(u);\n\n%% Get simulation data by simulating the system using ODE113\n\n% Determine the left hand side derivative\nif Control==1\n y_list(1,:)=state0;\n d_y_list(1,:)=ODE(0,y_list(1,:),u(1,:));\n for i=2:length(u)\n [t_1,y_1] = ode113(@(t_1,y_1)ODE(t_1,y_1,u(i-1,:)),tspan(1,i-1:i),state0);\n y_list(i,:)=y_1(end,:);\n d_y_list(i,:)=ODE(0,y_list(i,:),u(i,:));\n state0=y_list(i,:)';\n end\nelse\n %Simulate the system ODE\n [t,y]=ode45(@(t,y)ODE(t,y),tspan,state0);\n y_list=y;\n % Get the derivative data\n d_y_list=ODE(0,y_list')';\nend\n\n%% Add some noise to the system\nfor i=1:N1\n Data(:,i)=y_list(:,i)+Noise*randn(size(y_list(:,i)));\nend\n%\nfor i=1:N1\n d_Data(:,i)=d_y_list(:,i)+Noise*randn(size(d_y_list(:,i)));\nend\n\n%% Shuffle the data\nif Shuffle==1\n Sequence=randperm(size(Data,1));\n Data=Data(Sequence,:);\n d_Data=d_Data(Sequence,:);\nend\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/DoublePendulum/Functions/Get_Sim_Data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6307392735516285}} {"text": "function [ r, s, area ] = node_reference ( code )\n\n%*****************************************************************************80\n%\n%% NODE_REFERENCE returns the basis nodes for any available element.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character CODE(*), identifies the element desired.\n% Legal values include 'Q4', 'Q8', 'Q9', 'Q12', 'Q16', 'QL',\n% 'T3', 'T4', 'T6' and 'T10'.\n%\n% Output, real R(N), S(N), the coordinates of the basis nodes.\n%\n% Output, real AREA, the area of the element.\n%\n if ( s_eqi ( code, 'Q4' ) )\n [ r, s, area ] = node_reference_q4 ( );\n elseif ( s_eqi ( code, 'Q8' ) )\n [ r, s, area ] = node_reference_q8 ( );\n elseif ( s_eqi ( code, 'Q9' ) )\n [ r, s, area ] = node_reference_q9 ( );\n elseif ( s_eqi ( code, 'Q12' ) )\n [ r, s, area ] = node_reference_q12 ( );\n elseif ( s_eqi ( code, 'Q16' ) )\n [ r, s, area ] = node_reference_q16 ( );\n elseif ( s_eqi ( code, 'QL' ) )\n [ r, s, area ] = node_reference_ql ( );\n elseif ( s_eqi ( code, 'T3' ) )\n [ r, s, area ] = node_reference_t3 ( );\n elseif ( s_eqi ( code, 'T4' ) )\n [ r, s, area ] = node_reference_t4 ( );\n elseif ( s_eqi ( code, 'T6' ) )\n [ r, s, area ] = node_reference_t6 ( );\n elseif ( s_eqi ( code, 'T10' ) )\n [ r, s, area ] = node_reference_t10 ( );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NODE_REFERENCE - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of CODE = \"%s\"\\n', code );\n error ( 'NODE_REFERENCE - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/node_reference.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6307392624521099}} {"text": "% Fixed-budget kernel least mean squares (FB-KLMS) algorithm.\n%\n% D. Rzepka, \"Fixed-budget kernel least mean squares,\" 2012 IEEE 17th\n% Conference on Emerging Technologies & Factory Automation (ETFA), Krakow,\n% Poland, Sept. 2012, http://dx.doi.org/10.1109/ETFA.2012.6489767\n%\n% Remark: code contributed by Dominik Rzepka\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef fbklms < kernel_adaptive_filter\n \n properties (GetAccess = 'public', SetAccess = 'private') % parameters\n nu = .05; % growth criterion threshold\n M = 500; % dictionary size\n eta = .5; % learning rate\n kerneltype = 'gauss'; % kernel type\n kernelpar = 1; % kernel parameter\n end\n \n properties (GetAccess = 'private', SetAccess = 'private') % variables\n dict = []; % dictionary\n diagkdict = []; % diagonal of kernel matrix for dictionary\n alpha = []; % expansion coefficients\n end\n \n methods \n function kaf = fbklms(parameters) % constructor\n if (nargin > 0) % copy valid parameters\n for fn = fieldnames(parameters)'\n if ismember(fn,fieldnames(kaf))\n kaf.(fn{1}) = parameters.(fn{1});\n end\n end\n end\n end\n \n function y_est = evaluate(kaf,x) % evaluate the algorithm\n if size(kaf.dict,1)>0\n k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);\n y_est = k'*kaf.alpha;\n else\n y_est = zeros(size(x,1),1);\n end\n end\n \n function train(kaf,x,y) % train the algorithm\n if size(kaf.dict,2)==0 % initialize\n kaf.dict = x;\n k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);\n kaf.diagkdict(1) = k;\n kaf.alpha = kaf.eta*y*k/(k'*k);\n else\n \n kt = kernel([kaf.dict;x],x,kaf.kerneltype,kaf.kernelpar);\n k = kt(1:end-1);\n y_est = k'*kaf.alpha;\n e = y - y_est;\n \n kaf.alpha = kaf.alpha + kaf.eta*e*k/(k'*k);\n \n % growth criterion\n kx = kt(end);\n dependency = kx - k./kaf.diagkdict;\n if min(dependency) >= kaf.nu % expand dictionary\n kaf.dict = [kaf.dict; x];\n kaf.diagkdict = [kaf.diagkdict; kx];\n kaf.alpha = [kaf.alpha; kaf.eta*e/(k'*k)];\n \n if length(kaf.alpha) > kaf.M % prune dictionary\n [~, id] = min(abs(kaf.alpha));\n kaf.dict(id,:) = [];\n kaf.diagkdict(id) = [];\n kaf.alpha(id) = [];\n end\n end\n end\n end\n end\nend\n", "meta": {"author": "steven2358", "repo": "kafbox", "sha": "694cf94df02a9728a90d7bacda1a8520b425f86f", "save_path": "github-repos/MATLAB/steven2358-kafbox", "path": "github-repos/MATLAB/steven2358-kafbox/kafbox-694cf94df02a9728a90d7bacda1a8520b425f86f/lib/fbklms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6306720148549264}} {"text": "function [qrs_amp_raw,qrs_i_raw,delay]=pan_tompkin(ecg,fs,gr)\n\n%% function [qrs_amp_raw,qrs_i_raw,delay]=pan_tompkin(ecg,fs)\n% Complete implementation of Pan-Tompkins algorithm\n\n%% Inputs\n% ecg : raw ecg vector signal 1d signal\n% fs : sampling frequency e.g. 200Hz, 400Hz and etc\n% gr : flag to plot or not plot (set it 1 to have a plot or set it zero not\n% to see any plots\n%% Outputs\n% qrs_amp_raw : amplitude of R waves amplitudes\n% qrs_i_raw : index of R waves\n% delay : number of samples which the signal is delayed due to the\n% filtering\n%% Method :\n\n%% PreProcessing\n% 1) Signal is preprocessed , if the sampling frequency is higher then it is downsampled\n% and if it is lower upsampled to make the sampling frequency 200 Hz\n% with the same filtering setups introduced in Pan\n% tompkins paper (a combination of low pass and high pass filter 5-15 Hz)\n% to get rid of the baseline wander and muscle noise. \n\n% 2) The filtered signal\n% is derivated using a derivating filter to high light the QRS complex.\n\n% 3) Signal is squared.4)Signal is averaged with a moving window to get rid\n% of noise (0.150 seconds length).\n\n% 5) depending on the sampling frequency of your signal the filtering\n% options are changed to best match the characteristics of your ecg signal\n\n% 6) Unlike the other implementations in this implementation the desicion\n% rule of the Pan tompkins is implemented completely.\n\n%% Decision Rule \n% At this point in the algorithm, the preceding stages have produced a roughly pulse-shaped\n% waveform at the output of the MWI . The determination as to whether this pulse\n% corresponds to a QRS complex (as opposed to a high-sloped T-wave or a noise artefact) is\n% performed with an adaptive thresholding operation and other decision\n% rules outlined below;\n\n% a) FIDUCIAL MARK - The waveform is first processed to produce a set of weighted unit\n% samples at the location of the MWI maxima. This is done in order to localize the QRS\n% complex to a single instant of time. The w[k] weighting is the maxima value.\n\n% b) THRESHOLDING - When analyzing the amplitude of the MWI output, the algorithm uses\n% two threshold values (THR_SIG and THR_NOISE, appropriately initialized during a brief\n% 2 second training phase) that continuously adapt to changing ECG signal quality. The\n% first pass through y[n] uses these thresholds to classify the each non-zero sample\n% (CURRENTPEAK) as either signal or noise:\n% If CURRENTPEAK > THR_SIG, that location is identified as a QRS complex\n% candidate?and the signal level (SIG_LEV) is updated:\n% SIG _ LEV = 0.125 CURRENTPEAK + 0.875?SIG _ LEV\n\n% If THR_NOISE < CURRENTPEAK < THR_SIG, then that location is identified as a\n% Noise peak?and the noise level (NOISE_LEV) is updated:\n% NOISE _ LEV = 0.125CURRENTPEAK + 0.875?NOISE _ LEV\n% Based on new estimates of the signal and noise levels (SIG_LEV and NOISE_LEV,\n% respectively) at that point in the ECG, the thresholds are adjusted as follows:\n% THR _ SIG = NOISE _ LEV + 0.25 ?(SIG _ LEV-NOISE _ LEV )\n% THR _ NOISE = 0.5?(THR _ SIG)\n% These adjustments lower the threshold gradually in signal segments that are deemed to\n% be of poorer quality.\n\n\n% c) SEARCHBACK FOR MISSED QRS COMPLEXES - In the thresholding step above, if\n% CURRENTPEAK < THR_SIG, the peak is deemed not to have resulted from a QRS\n% complex. If however, an unreasonably long period has expired without an abovethreshold\n% peak, the algorithm will assume a QRS has been missed and perform a\n% searchback. This limits the number of false negatives. The minimum time used to trigger\n% a searchback is 1.66 times the current R peak to R peak time period (called the RR\n% interval). This value has a physiological origin - the time value between adjacent\n% heartbeats cannot change more quickly than this. The missed QRS complex is assumed\n% to occur at the location of the highest peak in the interval that lies between THR_SIG and\n% THR_NOISE. In this algorithm, two average RR intervals are stored,the first RR interval is \n% calculated as an average of the last eight QRS locations in order to adapt to changing heart \n% rate and the second RR interval mean is the mean \n% of the most regular RR intervals . The threshold is lowered if the heart rate is not regular \n% to improve detection.\n\n% d) ELIMINATION OF MULTIPLE DETECTIONS WITHIN REFRACTORY PERIOD - It is\n% impossible for a legitimate QRS complex to occur if it lies within 200ms after a previously\n% detected one. This constraint is a physiological one ?due to the refractory period during\n% which ventricular depolarization cannot occur despite a stimulus[1]. As QRS complex\n% candidates are generated, the algorithm eliminates such physically impossible events,\n% thereby reducing false positives.\n\n% e) T WAVE DISCRIMINATION - Finally, if a QRS candidate occurs after the 200ms\n% refractory period but within 360ms of the previous QRS, the algorithm determines\n% whether this is a genuine QRS complex of the next heartbeat or an abnormally prominent\n% T wave. This decision is based on the mean slope of the waveform at that position. A slope of\n% less than one half that of the previous QRS complex is consistent with the slower\n% changing behaviour of a T wave ?otherwise, it becomes a QRS detection.\n% Extra concept : beside the points mentioned in the paper, this code also\n% checks if the occured peak which is less than 360 msec latency has also a\n% latency less than 0,5*mean_RR if yes this is counted as noise\n\n% f) In the final stage , the output of R waves detected in smoothed signal is analyzed and double\n% checked with the help of the output of the bandpass signal to improve\n% detection and find the original index of the real R waves on the raw ecg\n% signal\n\n%% References :\n\n%[1]PAN.J, TOMPKINS. W.J,\"A Real-Time QRS Detection Algorithm\" IEEE\n%TRANSACTIONS ON BIOMEDICAL ENGINEERING, VOL. BME-32, NO. 3, MARCH 1985.\n\n%% Author : Hooman Sedghamiz\n% Linkoping university \n% email : hoose792@student.liu.se\n% hooman.sedghamiz@medel.com\n\n% Any direct or indirect use of this code should be referenced \n% Copyright march 2014\n%%\nif ~isvector(ecg)\n error('ecg must be a row or column vector');\nend\n\n\nif nargin < 3\n gr = 1; % on default the function always plots\nend\necg = ecg(:); % vectorize\n\n%% Initialize\nqrs_c =[]; %amplitude of R\nqrs_i =[]; %index\nSIG_LEV = 0; \nnois_c =[];\nnois_i =[];\ndelay = 0;\nskip = 0; % becomes one when a T wave is detected\nnot_nois = 0; % it is not noise when not_nois = 1\nselected_RR =[]; % Selected RR intervals\nm_selected_RR = 0;\nmean_RR = 0;\nqrs_i_raw =[];\nqrs_amp_raw=[];\nser_back = 0; \ntest_m = 0;\nSIGL_buf = [];\nNOISL_buf = [];\nTHRS_buf = [];\nSIGL_buf1 = [];\nNOISL_buf1 = [];\nTHRS_buf1 = [];\n\n\n%% Plot differently based on filtering settings\nif gr\n if fs == 200\n figure, ax(1)=subplot(321);plot(ecg);axis tight;title('Raw ECG Signal');\n else\n figure, ax(1)=subplot(3,2,[1 2]);plot(ecg);axis tight;title('Raw ECG Signal');\n end\nend \n%% Noise cancelation(Filtering) % Filters (Filter in between 5-15 Hz)\nif fs == 200\n%% Low Pass Filter H(z) = ((1 - z^(-6))^2)/(1 - z^(-1))^2\nb = [1 0 0 0 0 0 -2 0 0 0 0 0 1];\na = [1 -2 1];\nh_l = filter(b,a,[1 zeros(1,12)]); \necg_l = conv (ecg ,h_l);\necg_l = ecg_l/ max( abs(ecg_l));\ndelay = 6; %based on the paper\nif gr\nax(2)=subplot(322);plot(ecg_l);axis tight;title('Low pass filtered');\nend\n%% High Pass filter H(z) = (-1+32z^(-16)+z^(-32))/(1+z^(-1))\nb = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 -32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1];\na = [1 -1];\nh_h = filter(b,a,[1 zeros(1,32)]); \necg_h = conv (ecg_l ,h_h);\necg_h = ecg_h/ max( abs(ecg_h));\ndelay = delay + 16; % 16 samples for highpass filtering\nif gr\nax(3)=subplot(323);plot(ecg_h);axis tight;title('High Pass Filtered');\nend\nelse\n%% bandpass filter for Noise cancelation of other sampling frequencies(Filtering)\nf1=5; %cuttoff low frequency to get rid of baseline wander\nf2=15; %cuttoff frequency to discard high frequency noise\nWn=[f1 f2]*2/fs; % cutt off based on fs\nN = 3; % order of 3 less processing\n[a,b] = butter(N,Wn); %bandpass filtering\necg_h = filtfilt(a,b,ecg);\necg_h = ecg_h/ max( abs(ecg_h));\nif gr\nax(3)=subplot(323);plot(ecg_h);axis tight;title('Band Pass Filtered');\nend\nend\n%% derivative filter H(z) = (1/8T)(-z^(-2) - 2z^(-1) + 2z + z^(2))\nh_d = [-1 -2 0 2 1]*(1/8);%1/8*fs\necg_d = conv (ecg_h ,h_d);\necg_d = ecg_d/max(ecg_d);\ndelay = delay + 2; % delay of derivative filter 2 samples\nif gr\nax(4)=subplot(324);plot(ecg_d);axis tight;title('Filtered with the derivative filter');\nend\n%% Squaring nonlinearly enhance the dominant peaks\necg_s = ecg_d.^2;\nif gr\nax(5)=subplot(325);plot(ecg_s);axis tight;title('Squared');\nend\n\n\n\n%% Moving average Y(nt) = (1/N)[x(nT-(N - 1)T)+ x(nT - (N - 2)T)+...+x(nT)]\necg_m = conv(ecg_s ,ones(1 ,round(0.150*fs))/round(0.150*fs));\ndelay = delay + 15;\n\nif gr\nax(6)=subplot(326);plot(ecg_m);axis tight;title('Averaged with 30 samples length,Black noise,Green Adaptive Threshold,RED Sig Level,Red circles QRS adaptive threshold');\naxis tight;\nend\n\n%% Fiducial Mark \n% Note : a minimum distance of 40 samples is considered between each R wave\n% since in physiological point of view no RR wave can occur in less than\n% 200 msec distance\n[pks,locs] = findpeaks(ecg_m,'MINPEAKDISTANCE',round(0.2*fs));\n\n\n\n\n%% initialize the training phase (2 seconds of the signal) to determine the THR_SIG and THR_NOISE\nTHR_SIG = max(ecg_m(1:2*fs))*1/3; % 0.25 of the max amplitude \nTHR_NOISE = mean(ecg_m(1:2*fs))*1/2; % 0.5 of the mean signal is considered to be noise\nSIG_LEV= THR_SIG;\nNOISE_LEV = THR_NOISE;\n\n\n%% Initialize bandpath filter threshold(2 seconds of the bandpass signal)\nTHR_SIG1 = max(ecg_h(1:2*fs))*1/3; % 0.25 of the max amplitude \nTHR_NOISE1 = mean(ecg_h(1:2*fs))*1/2; %\nSIG_LEV1 = THR_SIG1; % Signal level in Bandpassed filter\nNOISE_LEV1 = THR_NOISE1; % Noise level in Bandpassed filter\n%% Thresholding and online desicion rule\n\nfor i = 1 : length(pks)\n \n %% locate the corresponding peak in the filtered signal \n if locs(i)-round(0.150*fs)>= 1 && locs(i)<= length(ecg_h)\n [y_i x_i] = max(ecg_h(locs(i)-round(0.150*fs):locs(i)));\n else\n if i == 1\n [y_i x_i] = max(ecg_h(1:locs(i)));\n ser_back = 1;\n elseif locs(i)>= length(ecg_h)\n [y_i x_i] = max(ecg_h(locs(i)-round(0.150*fs):end));\n end\n \n end\n \n \n %% update the heart_rate (Two heart rate means one the moste recent and the other selected)\n if length(qrs_c) >= 9 \n \n diffRR = diff(qrs_i(end-8:end)); %calculate RR interval\n mean_RR = mean(diffRR); % calculate the mean of 8 previous R waves interval\n comp =qrs_i(end)-qrs_i(end-1); %latest RR\n if comp <= 0.92*mean_RR || comp >= 1.16*mean_RR\n % lower down thresholds to detect better in MVI\n THR_SIG = 0.5*(THR_SIG);\n %THR_NOISE = 0.5*(THR_SIG); \n % lower down thresholds to detect better in Bandpass filtered \n THR_SIG1 = 0.5*(THR_SIG1);\n %THR_NOISE1 = 0.5*(THR_SIG1); \n \n else\n m_selected_RR = mean_RR; %the latest regular beats mean\n end \n \n end\n \n %% calculate the mean of the last 8 R waves to make sure that QRS is not\n % missing(If no R detected , trigger a search back) 1.66*mean\n \n if m_selected_RR\n test_m = m_selected_RR; %if the regular RR availabe use it \n elseif mean_RR && m_selected_RR == 0\n test_m = mean_RR; \n else\n test_m = 0;\n end\n \n if test_m\n if (locs(i) - qrs_i(end)) >= round(1.66*test_m)% it shows a QRS is missed \n [pks_temp,locs_temp] = max(ecg_m(qrs_i(end)+ round(0.200*fs):locs(i)-round(0.200*fs))); % search back and locate the max in this interval\n locs_temp = qrs_i(end)+ round(0.200*fs) + locs_temp -1; %location \n \n if pks_temp > THR_NOISE\n qrs_c = [qrs_c pks_temp];\n qrs_i = [qrs_i locs_temp];\n \n % find the location in filtered sig\n if locs_temp <= length(ecg_h)\n [y_i_t x_i_t] = max(ecg_h(locs_temp-round(0.150*fs):locs_temp));\n else\n [y_i_t x_i_t] = max(ecg_h(locs_temp-round(0.150*fs):end));\n end\n % take care of bandpass signal threshold\n if y_i_t > THR_NOISE1 \n \n qrs_i_raw = [qrs_i_raw locs_temp-round(0.150*fs)+ (x_i_t - 1)];% save index of bandpass \n qrs_amp_raw =[qrs_amp_raw y_i_t]; %save amplitude of bandpass \n SIG_LEV1 = 0.25*y_i_t + 0.75*SIG_LEV1; %when found with the second thres \n end\n \n not_nois = 1;\n SIG_LEV = 0.25*pks_temp + 0.75*SIG_LEV ; %when found with the second threshold \n end \n \n else\n not_nois = 0;\n \n end\n end\n \n \n \n \n %% find noise and QRS peaks\n if pks(i) >= THR_SIG\n \n % if a QRS candidate occurs within 360ms of the previous QRS\n % ,the algorithm determines if its T wave or QRS\n if length(qrs_c) >= 3\n if (locs(i)-qrs_i(end)) <= round(0.3600*fs)\n Slope1 = mean(diff(ecg_m(locs(i)-round(0.075*fs):locs(i)))); %mean slope of the waveform at that position\n Slope2 = mean(diff(ecg_m(qrs_i(end)-round(0.075*fs):qrs_i(end)))); %mean slope of previous R wave\n if abs(Slope1) <= abs(0.5*(Slope2)) % slope less then 0.5 of previous R\n nois_c = [nois_c pks(i)];\n nois_i = [nois_i locs(i)];\n skip = 1; % T wave identification\n % adjust noise level in both filtered and\n % MVI\n NOISE_LEV1 = 0.125*y_i + 0.875*NOISE_LEV1;\n NOISE_LEV = 0.125*pks(i) + 0.875*NOISE_LEV; \n else\n skip = 0;\n end\n \n end\n end\n \n if skip == 0 % skip is 1 when a T wave is detected \n qrs_c = [qrs_c pks(i)];\n qrs_i = [qrs_i locs(i)];\n \n % bandpass filter check threshold\n if y_i >= THR_SIG1\n if ser_back \n qrs_i_raw = [qrs_i_raw x_i]; % save index of bandpass \n else\n qrs_i_raw = [qrs_i_raw locs(i)-round(0.150*fs)+ (x_i - 1)];% save index of bandpass \n end\n qrs_amp_raw =[qrs_amp_raw y_i];% save amplitude of bandpass \n SIG_LEV1 = 0.125*y_i + 0.875*SIG_LEV1;% adjust threshold for bandpass filtered sig\n end\n \n % adjust Signal level\n SIG_LEV = 0.125*pks(i) + 0.875*SIG_LEV ;\n end\n \n \n elseif THR_NOISE <= pks(i) && pks(i)-100000];\nsig_func = @(s) sigma_dc(1)*[s>-100000];\n[Q, y_1, c_index_1] = Q_Matrix(m_0, mu_func,sig_func,Ls_dc(1),Rs_dc(1),gridMethod,center, GridMultParam);\nP1 = expm(Q*dt);\n\n% Form CTMC 2\ncenter = Y_0s(2);\nmu_func = @(s) drift_dc(2)*[s>-100000];\nsig_func = @(s) sigma_dc(2)*[s>-100000];\n[Q, y_2, c_index_2] = Q_Matrix(m_0, mu_func,sig_func,Ls_dc(2),Rs_dc(2),gridMethod,center, GridMultParam);\nP2 = expm(Q*dt);\n\nG = get_payoff_G_matrix_from_ygrid_2d( y_1, y_2, S_0s, sigmas, rho, contractParams);\n\nif contract == 1 % European, Price by single step\n vals = exp(-r*T)*P1*G*P2.';\n \nelseif contract == 2 % European, Price By Multi Step\n vals = G;\n for m=M-1:-1:0\n vals = exp(-r*dt)*P1*vals*P2.';\n end \n \nelseif contract == 3 % Bermudan\n vals = G;\n for m=M-1:-1:0\n vals = max(exp(-r*dt)*P1*vals*P2.', G);\n end\n \nelseif contract == 4 % Barrier\n b1 = contractParams.barriers_1; L1 = b1(1); U1 = b1(2);\n b2 = contractParams.barriers_2; L2 = b2(1); U2 = b2(2);\n B = ones(m_0, m_0);\n for i = 1:m_0\n y1 = y_1(i);\n S1 = S_0s(1)*exp(sigmas(1)*y1);\n if S1 < L1 || S1 > U1\n B(i,:) = 0;\n else\n for j = 1:m_0\n y2 = y_2(j);\n S2 = S_0s(2)*exp(sigmas(2)*(y2 + rho*y1));\n if S2 < L2 || S2 > U2\n B(i,j) = 0;\n end\n end\n end\n end\n vals = G.*B;\n for m=M-1:-1:0\n vals = exp(-r*dt)*(B.*P1*vals*P2.');\n end \nend\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/CTMC/Diffusion_2D/price_2d_ctmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6306463564413737}} {"text": "function [ value, ifault ] = ppchi2 ( p, v, g )\n\n%*****************************************************************************80\n%\n%% PPCHI2 evaluates the percentage points of the Chi-squared PDF.\n%\n% Discussion\n%\n% Incorporates the suggested changes in AS R85 (vol.40(1),\n% pages 233-5, 1991) which should eliminate the need for the limited\n% range for P, though these limits have not been removed\n% from the routine.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Donald Best, DE Roberts.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Donald Best, DE Roberts,\n% Algorithm AS 91:\n% The Percentage Points of the Chi-Squared Distribution,\n% Applied Statistics,\n% Volume 24, Number 3, 1975, pages 385-390.\n%\n% Parameters:\n%\n% Input, real P, value of the chi-squared cumulative\n% probability density function.\n% 0.000002 <= P <= 0.999998.\n%\n% Input, real V, the parameter of the chi-squared probability\n% density function.\n% 0 < V.\n%\n% Input, real G, the value of log ( Gamma ( V / 2 ) ).\n%\n% Output, real VALUE, the value of the chi-squared random\n% deviate with the property that the probability that a chi-squared random\n% deviate with parameter V is less than or equal to PPCHI2 is P.\n%\n% Output, integer IFAULT, is nonzero if an error occurred.\n% 0, no error.\n% 1, P is outside the legal range.\n% 2, V is not positive.\n% 3, an error occurred in GAMMAD.\n% 4, the result is probably as accurate as the machine will allow.\n%\n aa = 0.6931471806;\n c1 = 0.01;\n c2 = 0.222222;\n c3 = 0.32;\n c4 = 0.4;\n c5 = 1.24;\n c6 = 2.2;\n c7 = 4.67;\n c8 = 6.66;\n c9 = 6.73;\n c10 = 13.32;\n c11 = 60.0;\n c12 = 70.0;\n c13 = 84.0;\n c14 = 105.0;\n c15 = 120.0;\n c16 = 127.0;\n c17 = 140.0;\n c18 = 175.0;\n c19 = 210.0;\n c20 = 252.0;\n c21 = 264.0;\n c22 = 294.0;\n c23 = 346.0;\n c24 = 420.0;\n c25 = 462.0;\n c26 = 606.0;\n c27 = 672.0;\n c28 = 707.0;\n c29 = 735.0;\n c30 = 889.0;\n c31 = 932.0;\n c32 = 966.0;\n c33 = 1141.0;\n c34 = 1182.0;\n c35 = 1278.0;\n c36 = 1740.0;\n c37 = 2520.0;\n c38 = 5040.0;\n e = 0.5E-06;\n maxit = 20;\n pmax = 0.999998;\n pmin = 0.000002;\n%\n% Test arguments and initialize.\n%\n value = - 1.0;\n\n if ( p < pmin || pmax < p )\n ifault = 1;\n return\n end\n\n if ( v <= 0.0 )\n ifault = 2;\n return\n end\n\n ifault = 0;\n xx = 0.5 * v;\n c = xx - 1.0;\n%\n% Starting approximation for small chi-squared\n%\n if ( v < - c5 * log ( p ) )\n\n ch = ( p * xx * exp ( g + xx * aa ) )^( 1.0 / xx );\n\n if ( ch < e )\n value = ch;\n return\n end\n%\n% Starting approximation for V less than or equal to 0.32\n%\n elseif ( v <= c3 )\n\n ch = c4;\n a = log ( 1.0 - p );\n\n while ( 1 )\n\n q = ch;\n p1 = 1.0 + ch * ( c7 + ch );\n p2 = ch * ( c9 + ch * ( c8 + ch ) );\n\n t = - 0.5 + (c7 + 2.0 * ch ) / p1 ...\n - ( c9 + ch * ( c10 + 3.0 * ch ) ) / p2\n\n ch = ch - ( 1.0 - exp ( a + g + 0.5 * ch + c * aa ) * p2 / p1) / t;\n\n if ( abs ( q / ch - 1.0 ) <= c1 )\n break\n end\n\n end\n\n else\n%\n% Call to algorithm AS 111 - note that P has been tested above.\n% AS 241 could be used as an alternative.\n%\n [ x, ifault ] = ppnd ( p );\n%\n% Starting approximation using Wilson and Hilferty estimate\n%\n p1 = c2 / v;\n ch = v * ( x * sqrt ( p1 ) + 1.0 - p1)^3;\n%\n% Starting approximation for P tending to 1.\n%\n if ( c6 * v + 6.0 < ch )\n ch = - 2.0 * ( log ( 1.0 - p ) - c * log ( 0.5 * ch ) + g );\n end\n\n end\n%\n% Call to algorithm AS 239 and calculation of seven term\n% Taylor series\n%\n for i = 1 : maxit\n\n q = ch;\n p1 = 0.5 * ch;\n [ temp, if1 ] = gammad ( p1, xx );\n p2 = p - temp;\n\n if ( if1 ~= 0 )\n ifault = 3;\n return\n end\n\n t = p2 * exp ( xx * aa + g + p1 - c * log ( ch ) );\n b = t / ch;\n a = 0.5 * t - b * c;\n s1 = ( c19 + a * ( c17 + a * ( c14 + a * ( c13 + a * ( c12 + ...\n c11 * a ))))) / c24;\n s2 = ( c24 + a * ( c29 + a * ( c32 + a * ( c33 + c35 * a )))) / c37;\n s3 = ( c19 + a * ( c25 + a * ( c28 + c31 * a ))) / c37;\n s4 = ( c20 + a * ( c27 + c34 * a) + c * ( c22 + a * ( c30 + c36 * a ))) ...\n / c38;\n s5 = ( c13 + c21 * a + c * ( c18 + c26 * a )) / c37;\n s6 = ( c15 + c * ( c23 + c16 * c )) / c38;\n ch = ch + t * ( 1.0 + 0.5 * t * s1 - b * c * ( s1 - b * ...\n ( s2 - b * ( s3 - b * ( s4 - b * ( s5 - b * s6 ))))));\n\n if ( e < abs ( q / ch - 1.0 ) )\n value = ch;\n return\n end\n\n end\n\n ifault = 4;\n value = ch;\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/asa091/ppchi2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6305936272487943}} {"text": "function imf = bwtfilter(im,f)\n% function imf = bwtfilter(im,f)\n%\n% BWT decimated filtering\n% Version 1.2\n%\n% This is faster than doing the complete filtering operation with conv2 and\n% then decimating the result\n% \n% Arguments:\n% im: A square image, with side length a multiple of 3\n% f: A 3x3 filter\n%\n% Result:\n% imf: im is filtered with f, and the result is decimated, taking every \n% 3rd value in x and y. This code is equivalent to:\n% imf = conv2(im, rot90(rot90(f)),'same');\n% imf = imf(2:3:end,2:3:end);\n%\n% Citation:\n% Willmore B, Prenger RJ, Wu MC and Gallant JL (2008). The Berkeley \n% Wavelet Transform: A biologically-inspired orthogonal wavelet transform.\n% Neural Computation 20:6, 1537-1564 \n%\n% The article is available at:\n% \n%\n% Copyright (c) 2008 Ben Willmore\n%\n% Permission is hereby granted, free of charge, to any person\n% obtaining a copy of this software and associated documentation\n% files (the \"Software\"), to deal in the Software without\n% restriction, including without limitation the rights to use,\n% copy, modify, merge, publish, distribute, sublicense, and/or sell\n% copies of the Software, and to permit persons to whom the\n% Software is furnished to do so, subject to the following\n% conditions:\n% \n% The above copyright notice and this permission notice shall be\n% included in all copies or substantial portions of the Software.\n% \n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n% OTHER DEALINGS IN THE SOFTWARE.\n\nsz = size(im);\n\nif (length(sz) ~= 2) || (sz(1) ~= sz(2))\n disp('Input must be square');\n decomp = nan;\n return;\nend\n\nsz = sz(1);\nssz = sz/3;\n\nif ( (ssz-floor(ssz)) > abs(ssz)*eps )\n fprintf('Side length must be a multiple of 3');\n decomp = nan;\n return;\nend\n\nf_rep = repmat(f,ssz,ssz);\n\nimdot = im .* f_rep;\n\nimf = zeros(ssz);\n\nfor yy = 1:3\n for xx = 1:3\n imf = imf + imdot(yy:3:end,xx:3:end);\n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/19860-berkeley-wavelet-transform/bwt/bwtfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6305936168013032}} {"text": "function M = stiefelfactory(n, p, k, gpuflag)\n% Returns a manifold structure to optimize over orthonormal matrices.\n%\n% function M = stiefelfactory(n, p)\n% function M = stiefelfactory(n, p, k)\n% function M = stiefelfactory(n, p, k, gpuflag)\n%\n% The Stiefel manifold is the set of orthonormal nxp matrices. If k\n% is larger than 1, this is the Cartesian product of the Stiefel manifold\n% taken k times. The metric is such that the manifold is a Riemannian\n% submanifold of R^nxp equipped with the usual trace inner product, that\n% is, it is the usual metric.\n%\n% Points are represented as matrices X of size n x p x k (or n x p if k=1,\n% which is the default) such that each n x p matrix is orthonormal,\n% i.e., X'*X = eye(p) if k = 1, or X(:, :, i)' * X(:, :, i) = eye(p) for\n% i = 1 : k if k > 1. Tangent vectors are represented as matrices the same\n% size as points.\n%\n% The default retraction is QR-based: it is only a first-order retraction.\n% To use the polar retraction (which is second order), run\n% M.retr = M.retr_polar;\n% after creating M with this factory. This can be reverted with\n% M.retr = M.retr_qr;\n% If used, you may also want to update M.invretr similarly.\n%\n% Set gpuflag = true to have points, tangent vectors and ambient vectors\n% stored on the GPU. If so, computations can be done on the GPU directly.\n%\n% By default, k = 1 and gpuflag = false.\n%\n% See also: grassmannfactory rotationsfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n% July 5, 2013 (NB) : Added ehess2rhess.\n% Jan. 27, 2014 (BM) : Bug in ehess2rhess corrected.\n% June 24, 2014 (NB) : Added true exponential map and changed the randvec\n% function so that it now returns a globally\n% normalized vector, not a vector where each\n% component is normalized (this only matters if k>1).\n% July 17, 2018 (NB) : Now both QR (default) and polar retractions are\n% directly accessible, and their inverses are also\n% implemented.\n% Aug. 2, 2018 (NB) : Added GPU support: just set gpuflag = true.\n% June 18, 2019 (NB) : Using qr_unique for retr and rand.\n% July 9, 2019 (NB) : Added a comment about QR retraction being first\n% order only.\n% Jan. 8, 2021 (NB) : Added tangent2ambient+tangent2ambient_is_identity.\n\n assert(n >= p, 'The dimension n must be larger than the dimension p.');\n \n if ~exist('k', 'var') || isempty(k)\n k = 1;\n end\n if ~exist('gpuflag', 'var') || isempty(gpuflag)\n gpuflag = false;\n end\n \n % If gpuflag is active, new arrays (e.g., via rand, randn, zeros, ones)\n % are created directly on the GPU; otherwise, they are created in the\n % usual way (in double precision).\n if gpuflag\n array_type = 'gpuArray';\n else\n array_type = 'double';\n end\n \n if k == 1\n M.name = @() sprintf('Stiefel manifold St(%d, %d)', n, p);\n elseif k > 1\n M.name = @() sprintf('Product Stiefel manifold St(%d, %d)^%d', n, p, k);\n else\n error('k must be an integer no less than 1.');\n end\n \n M.dim = @() k*(n*p - .5*p*(p+1));\n \n M.inner = @(x, d1, d2) d1(:).'*d2(:);\n \n M.norm = @(x, d) norm(d(:));\n \n M.dist = @(x, y) error('stiefel.dist not implemented yet.');\n \n M.typicaldist = @() sqrt(p*k);\n \n M.proj = @projection;\n function Up = projection(X, U)\n \n XtU = multiprod(multitransp(X), U);\n symXtU = multisym(XtU);\n Up = U - multiprod(X, symXtU);\n \n% The code above is equivalent to, but faster than, the code below.\n% \n% Up = zeros(size(U));\n% function A = sym(A), A = .5*(A+A'); end\n% for i = 1 : k\n% Xi = X(:, :, i);\n% Ui = U(:, :, i);\n% Up(:, :, i) = Ui - Xi*sym(Xi'*Ui);\n% end\n\n end\n \n M.tangent = M.proj;\n \n M.tangent2ambient_is_identity = true;\n M.tangent2ambient = @(X, U) U;\n \n % For Riemannian submanifolds, converting a Euclidean gradient into a\n % Riemannian gradient amounts to an orthogonal projection.\n M.egrad2rgrad = M.proj;\n \n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, H)\n XtG = multiprod(multitransp(X), egrad);\n symXtG = multisym(XtG);\n HsymXtG = multiprod(H, symXtG);\n rhess = projection(X, ehess - HsymXtG);\n end\n \n M.retr_qr = @retraction_qr;\n function Y = retraction_qr(X, U, t)\n % It is necessary to call qr_unique rather than simply qr to ensure\n % this is a retraction, to avoid spurious column sign flips.\n if nargin < 3\n Y = qr_unique(X + U);\n else\n Y = qr_unique(X + t*U);\n end\n end\n\n M.invretr_qr = @invretr_qr;\n function U = invretr_qr(X, Y)\n XtY = multiprod(multitransp(X), Y);\n R = zeros(p, p, k, array_type);\n H = 2*eye(p, array_type);\n for kk = 1 : k\n % For each slice, assuming the inverse retraction is well\n % defined for the given inputs, we have:\n % X + U = YR\n % Left multiply with X' to get\n % I + X'U = X'Y R\n % Since X'U is skew symmetric for a tangent vector U at X, add\n % up this equation with its transpose to get:\n % 2I = (X'Y) R + R' (X'Y)'\n % Contrary to the polar factorization, here R is not symmetric\n % but it is upper triangular. As a result, this is not a\n % Sylvester equation and we must solve it differently.\n R(:, :, kk) = solve_for_triu(XtY(:, :, kk), H);\n % Then,\n % U = YR - X\n % which is what we compute below.\n end\n U = multiprod(Y, R) - X;\n end\n \n M.retr_polar = @retraction_polar;\n function Y = retraction_polar(X, U, t)\n if nargin < 3\n Y = X + U;\n else\n Y = X + t*U;\n end\n for kk = 1 : k\n [u, s, v] = svd(Y(:, :, kk), 'econ'); %#ok\n Y(:, :, kk) = u*v';\n end\n end\n \n M.invretr_polar = @invretr_polar;\n function U = invretr_polar(X, Y)\n XtY = multiprod(multitransp(X), Y);\n MM = zeros(p, p, k, array_type);\n H = 2*eye(p, array_type);\n for kk = 1 : k\n % For each slice, assuming the inverse retraction is well\n % defined for the given inputs, we have:\n % X + U = YM\n % Left multiply with X' to get\n % I + X'U = X'Y M\n % Since X'U is skew symmetric for a tangent vector U at X, add\n % up this equation with its transpose to get:\n % 2I = (X'Y) M + M' (X'Y)'\n % = (X'Y) M + M (X'Y)' since M is symmetric.\n % Solve for M symmetric with a call to sylvester:\n MM(:, :, kk) = sylvester_nochecks(XtY(:, :, kk), XtY(:, :, kk)', H);\n % Note that the above is really a Lyapunov equation: it could\n % be solved faster by exploiting the fact the same matrix\n % appears twice on the left, with one the transpose of the\n % other. Then,\n % U = YM - X\n % which is what we compute below.\n end\n U = multiprod(Y, MM) - X;\n end\n \n % By default, we use the QR retraction\n M.retr = M.retr_qr;\n M.invretr = M.invretr_qr;\n\n M.exp = @exponential;\n function Y = exponential(X, U, t)\n if nargin == 2\n tU = U;\n else\n tU = t*U;\n end\n Y = zeros(size(X), array_type);\n I = eye(p, array_type);\n Z = zeros(p, array_type);\n for kk = 1 : k\n % From a formula by Ross Lippert, Example 5.4.2 in AMS08.\n Xkk = X(:, :, kk);\n Ukk = tU(:, :, kk);\n Y(:, :, kk) = [Xkk Ukk] * ...\n expm([Xkk'*Ukk , -Ukk'*Ukk ; I , Xkk'*Ukk]) * ...\n [ expm(-Xkk'*Ukk) ; Z ];\n end\n \n end\n\n M.hash = @(X) ['z' hashmd5(X(:))];\n \n M.rand = @() qr_unique(randn(n, p, k, array_type));\n \n M.randvec = @randomvec;\n function U = randomvec(X)\n U = projection(X, randn(n, p, k, array_type));\n U = U / norm(U(:));\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(n, p, k, array_type);\n \n M.transp = @(x1, x2, d) projection(x2, d);\n \n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [n, p, k]);\n M.vecmatareisometries = @() true;\n\n \n % Automatically convert a number of tools to support GPU.\n if gpuflag\n M = factorygpuhelper(M);\n end\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/stiefel/stiefelfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6305380975413737}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n\n% even or odd \n t1=0:4\n t2=0:-1:-4\n \n %even\n x1=t1.^2\n x2=t2.^2\n \n% odd\n y1=t1.^3\n y2=t2.^3\n\n \n %analysis in even and odd parts\n n=-5:5;\n u=(n>=0); \n stem(n,u);\n\n figure\n u_n=(n<=0)\n ue=1/2*(u+ u_n);\n stem(n,ue);\n\n figure\n uo=1/2*(u- u_n);\n stem(n,uo);\n\n figure\n stem(n,ue+uo)", "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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c243.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6305380820682529}} {"text": "%% meshDistMarch\n% Below is a demonstration of the features of the |meshDistMarch| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[d,seedIndex]=meshDistMarch(F,V,indStart,optionStruct);|\n\n%% Description\n% The meshDistMarch function can be used to compute distances on meshes.\n% The distances can be used for points sampling on the mesh or for\n% remeshing. \n% The function can operate on edge descriptions or face descriptions.\n% Therefore for volumetric meshes (e.g. consisting of tetrahedra or\n% hexahedra) appropriate face or edge data should be computed first to\n% formulate the input. \n%\n% Input:\n% E: the edges or faces for the mesh. E.g. an nx2 edge matrix or an nxm\n% face matrix (n faces, m corners per face)\n% V: the vertices for the mesh\n% indStart: indices for one or more points to compute distances from\n% optionStruct.toleranceLevel : The tolerance level for convergence. 0 is\n% the default. \n% optionStruct.numSeeds: Defines the number of seeds to generate on the mesh. Default is equal to startInd.\n% optionStruct.waitBarOn=0; %Turn on/off waitbar\n% optionStruct.unitEdgeOn=1; %Turn on/off the use of unit edge lengths\n% \n% Output: \n% d: distances (from the start/seed points) on the mesh vertices \n% seedIndex: nearest seed (or start) point indices for each vertex, forming\n% a quasi-Voronoi tesselation.\n% If the second output is not requested the performance is enhanced. \n\n%% Examples\n\n%%\n% Plot settings\ncMapDist=flipud(igviridis(250));\n[cMapIndices,scrambleIndices]=scramble(viridis(250),1); %Colormap\n\nfaceAlpha1=1;\nfaceAlpha2=0.65;\nfontSize=25; \nmarkerSize=50;\n\n%% Example: Edge or graph data \n\n%%\n% Create branching example. E defines edges and V is a vertex array\n\nn=75;\nx=linspace(0,0.9*pi,n);\ny=sin(x);\nV=[x(:) y(:) zeros(size(x(:)))];\nV=evenlySampleCurve(V,n,'pchip',0);\nx=V(:,1);\ny=V(:,2);\ndV=vecnormalize(diff(V,1,1));\nVdV=V(1:1:end-1,:);\nplacePoints=1:3:n-1;\nE=[(1:1:n-1)' (2:1:n)'];\nnumSteps=numel(placePoints);\nl=linspace(0.75,0.25,numSteps);\na=linspace(0.25*pi,0.25*pi,numSteps);\nfor q=1:1:numSteps \n R=euler2DCM([0 0 a(q)]);\n vr1=dV(placePoints(q),:)*R.*l(q);\n vr2=dV(placePoints(q),:)*R'.*l(q); \n Vb=linspacen([x(placePoints(q)) y(placePoints(q)) 0],vr1+[x(placePoints(q)) y(placePoints(q)) 0],n)';\n Eb=[(1:1:n-1)' (2:1:n)']; \n E=[E; Eb+size(V,1)];\n V=[V; Vb]; \n Vb=linspacen([x(placePoints(q)) y(placePoints(q)) 0],vr2+[x(placePoints(q)) y(placePoints(q)) 0],n)';\n Eb=[(1:1:n-1)' (2:1:n)'];\n E=[E; Eb+size(V,1)];\n V=[V; Vb];\nend\nE=[E;E+size(V,1);];\nV2=V;\nV2(:,2)=-V2(:,2);\nV2(:,1)=-V2(:,1);\nV=[V;V2];\nE=[E;E+size(V,1);];\nV2=V;\nV2(:,2)=-V2(:,2);\nV=[V;V2];\n[E,V]=mergeVertices(E,V);\n\n%%\n% Compute distances on mesh\n\n%Option set\nindStart=1; %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\nd=meshDistMarch(E,V,indStart,optionStruct);\n\n%%\n% Visualization\n\ncFigure; hold on;\ntitle('Distances on an edge / graph model','fontSize',fontSize);\nhp(1)=gpatch(E,V,'none',d,1,4);\nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\nview(2);\ncolorbar;\ndrawnow; \n\n%% Example: Triangulated data \n\n%%\n% Get example triangulated mesh data\n[F,V]=stanford_bunny;%graphicsModels(1);\n\n%%\n% Compute distances on mesh\n\n%Option set\n[~,indStart]=min(V(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\nd=meshDistMarch(F,V,indStart,optionStruct);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,2,1);hold on;\ntitle('Distances on a triangulated surface model','fontSize',fontSize);\ngpatch(F,V,'kw',d,1);\nhp(1)=gpatch(F,V,'none',d,1,2);\nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncolorbar;\ncamlight headlight;\n\nsubplot(1,2,2);hold on;\ntitle('Distances on a triangulated surface model','fontSize',fontSize);\nhp(1)=gpatch(F,V,d,'none',1);\nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolorbar;\ndrawnow; \n\n%% Example: Quadrangulated data \n\n%%\n% Get example quadrangulated mesh data\nn=4;\nr=1;\n[F,V]=quadSphere(n,r);\n\n%%\n% Compute distances on mesh\n\n%Option set\n[~,indStart]=min(V(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\nd=meshDistMarch(F,V,indStart,optionStruct);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,2,1);hold on;\ntitle('Distances on a quad surface model','fontSize',fontSize);\ngpatch(F,V,'kw',d,1);\nhp(1)=gpatch(F,V,'none',d,1,2);\nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncolorbar;\ncamlight headlight;\n\nsubplot(1,2,2);hold on;\ntitle('Distances on a quad surface model','fontSize',fontSize);\nhp(1)=gpatch(F,V,d,'none',1);\nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolorbar;\ndrawnow; \n\n%% Example: Hexahedral mesh data \n\n%%\n% Get example hexahedral mesh data\ncubeDimensions=[1 1 1];\ncubeElementNumbers=[10 10 10];\noutputStructType=2; %A structure compatible with mesh view\n[meshStruct]=hexMeshBox(cubeDimensions,cubeElementNumbers,outputStructType);\n\n%Access elements, nodes, and faces from the structure\nHEX=meshStruct.elements; %The elements\nF=meshStruct.faces; %The faces\nV=meshStruct.nodes; %The nodes (vertices)\n\n%Get edges for mesh marching\nE=patchEdges(F); %Mesh edges\n\n%%\n% Compute distances on mesh\n\n%Option set\n[~,indStart]=min(V(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\nd=meshDistMarch(E,V,indStart,optionStruct);\n\n%% \n% Plotting model boundary surfaces and a cut view\n\ncFigure; hold on\ntitle('Distances on a hexahedral mesh','FontSize',fontSize);\nhp(1)=gpatch(E,V,'none',d,1,3); \nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\ncolorbar;\naxisGeom(gca,fontSize);\ndrawnow;\n\n%% Example: Tetrahedral mesh data \n\n%%\n% Get example tetrahedral mesh data\n[TET,V]=hex2tet(HEX,V,[],2);\nF=element2patch(TET,V); %Element faces\n\n%Get edges for mesh marching\nE=patchEdges(F); %Mesh edges\n\n%%\n% Compute distances on mesh\n\n%Option set\n[~,indStart]=min(abs(V(:,1)-min(V(:,1)))+abs(V(:,2)-max(V(:,2)))+abs(V(:,3)-min(V(:,3)))); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\nd=meshDistMarch(E,V,indStart,optionStruct);\n\n%% \n% Plotting model boundary surfaces and a cut view\n\ncFigure; hold on\ntitle('Distances on a tetrahedral mesh','FontSize',fontSize);\nhp(1)=gpatch(E,V,'none',d,1,3); \nhp(2)=plotV(V(indStart,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\ncolorbar;\naxisGeom(gca,fontSize);\ndrawnow;\n\n%% Example: Mesh types effecting marching based distance computation\n% In this example 3 mesh variations for a sphere are created. For each the\n% start point is the point with the minimum x coordinate, i.e. a point on\n% the far left of the plot. For each the true distance should be a smooth\n% gradient with a maximum which equals pi. \n% The marching algorithm uses the mesh to march and compute distances. One\n% can imaging that straight paths (geodesically speaking) yeild the\n% shortest distances. Hence zig-zag pattern (geodesically speaking) create\n% false increased distances. This is not compensated for in this algorithm.\n% Therefore the distance map depends on the mesh type and mesh\n% connectivity. In the below example the regular quadrilateral mesh\n% contains a straight path to the farthest point allong the equator. With\n% mesh refinement the maximum distance would therefore converge on pi.\n% However, other directions for the quadrilateral mesh produce zig-zag\n% patterns causing distance to be altered. Hence the distance map departs\n% from the smooth gradient allong the x-direction, one would expect. The\n% triangulated mesh converted from the quadrilateral mesh contains both a\n% straight path at the equator and also improved connectivity for other\n% directions. The uniform geodesic triangulation contains the most smooth\n% distance map. \n\n%%\n% Getting 3 different mesh types for a sphere. \n\nn=3;\nr=1;\n[F1,V1]=quadSphere(n,r);\n[F2,V2]=quad2tri(F1,V1);\n[F3,V3]=geoSphere(n,r);\n\n%%\n% Compute distances on mesh\n\n% -> Surface 1\n%Option set\n[~,indStart1]=min(V1(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\n[d1,i1]=meshDistMarch(F1,V1,indStart1,optionStruct);\n\n% -> Surface 2\n%Option set\n[~,indStart2]=min(V2(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\n[d2,i2]=meshDistMarch(F2,V2,indStart2,optionStruct);\n\n% -> Surface 3\n%Option set\n[~,indStart3]=min(V3(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1; %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\n\n%Compute distances on mesh description\n[d3,i3]=meshDistMarch(F3,V3,indStart3,optionStruct);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,3,1);hold on;\ntitle('Regular quad mesh','fontSize',fontSize);\nhp(1)=gpatch(F1,V1,d1,d1);\nhp(2)=plotV(V1(indStart1,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncolorbar; caxis([0 pi]);\ncamlight headlight;\nview(2); \n\nsubplot(1,3,2);hold on;\ntitle('Irregular quad mesh','fontSize',fontSize);\nhp(1)=gpatch(F2,V2,d2,d2);\nhp(2)=plotV(V2(indStart2,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncolorbar; caxis([0 pi]);\ncamlight headlight;\nview(2); \n\nsubplot(1,3,3);hold on;\ntitle('Geodesic triangulated mesh','fontSize',fontSize);\nhp(1)=gpatch(F3,V3,d3,d3);\nhp(2)=plotV(V3(indStart3,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Start point(s)'},'Location','SouthOutSide');\naxisGeom;\ncolorbar; caxis([0 pi]);\ncamlight headlight;\nview(2); \n\ndrawnow; \n\n%% Example: Using |meshDistMarch| for geodesic point sampling\n\n%%\n% Get example triangulated mesh data\n[F,V]=graphicsModels(7);\n\n%%\n% Compute distances on mesh\n\nnumSeeds=250;\n\n%Option set\n[~,indStart]=min(V(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=numSeeds; %Number of seeds\noptionStruct.waitBarOn=1; %Turn on/off waitbar\n\n%Use weigths based on z-direction\n% W=V(:,3);\n% W=W-min(W);\n% W=W./max(W);\n% W=(W*9)+1;\n% optionStruct.W=W;\n\n%Compute distances on mesh description\n[d,seedIndex]=meshDistMarch(F,V,indStart,optionStruct);\n[indSeeds,~,ind2]=unique(seedIndex);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Distances on a triangulated surface model','fontSize',fontSize);\nhp(1)=gpatch(F,V,d,'none',1); hp(1).FaceColor='Interp';\nhp(2)=plotV(V(indSeeds,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Seed point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolormap(gca,cMapDist); colorbar;\n\nsubplot(1,2,2); hold on;\ntitle('Seed indices','fontSize',fontSize);\nhp(1)=gpatch(F,V,'kw',ind2,1); \nhp(2)=plotV(V(indSeeds,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Seed point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolormap(gca,cMapIndices); %icolorbar;\ndrawnow; \n\n%% Example: Using |meshDistMarch| for geodesic surface resampling\n% See also: |remeshTriSurfDistMap|\n\n[Fd,Vd,indSeed]=seedIndex2triangulation(F,V,seedIndex);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Distances on a triangulated surface model','fontSize',fontSize);\nhp(1)=gpatch(F,V,d,'none',1); hp(1).FaceColor='Interp';\nhp(2)=plotV(V(indSeeds,:),'k.','MarkerSize',markerSize);\nlegend(hp,{'Mesh distances','Seed point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolormap(gca,cMapDist); colorbar;\n\nsubplot(1,2,2); hold on;\ntitle('Resampled surface model','fontSize',fontSize);\nplotV(V(indSeed,:),'k.','MarkerSize',50);\nhp(1)=gpatch(F,V,'kw','none',0.5);\nhp(2)=gpatch(Fd,Vd,'gw','k',1,2);\nlegend(hp,{'Original mesh','Resampled mesh'},'Location','SouthOutSide');\n\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n%% Example: Using unit edge lengths\n% Forcing unit edge lenghts means each edge is considered equally long i.e.\n% a length of 1. Hence when used in combination with resampling, this\n% causes the algorithm to resample dense regions in a dense fashion and\n% coarse regions in a coarse fashion. Therefore using\n% optionStruct.unitEdgeOn=1; one can force the resampling to have similar\n% degrees of relative density differences. In the example below a dinosaur\n% mesh with a fine mesh at the limbs and a coarse mesh on the main body is\n% resampled using unit edge lengths. The output can be seen to remain\n% refined at the limbs. \n\n%%\n% Get example triangulated mesh data\n[F,V]=graphicsModels(4);\n[F,V]=subtri(F,V,2);\n\n%%\n% Compute distances on mesh\n\n%Option set\n[~,indStart]=min(V(:,1)); %Index of the start point\noptionStruct.toleranceLevel=0; %Tolerance for convergence\noptionStruct.numSeeds=1000; %Number of seeds\noptionStruct.waitBarOn=1; %Turn on/off waitbar\noptionStruct.unitEdgeOn=1;\n\n%Compute distances on mesh description\n[d,seedIndex]=meshDistMarch(F,V,indStart,optionStruct);\n[indSeeds,~,ind2]=unique(seedIndex);\n\n%Compute resampled surface\n[Fd,Vd,indSeed]=seedIndex2triangulation(F,V,seedIndex);\n\n%%\n% Visualization\n\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Distances on a triangulated surface model','fontSize',fontSize);\nhp(1)=gpatch(F,V,d,'none',1); hp(1).FaceColor='Interp';\nhp(2)=plotV(V(indSeeds,:),'k.','MarkerSize',25);\nlegend(hp,{'Mesh distances','Seed point(s)'},'Location','SouthOutSide');\naxisGeom;\ncamlight headlight;\ncolormap(gca,cMapDist); colorbar;\n\nsubplot(1,2,2); hold on;\ntitle('Resampled surface model','fontSize',fontSize);\nplotV(V(indSeed,:),'k.','MarkerSize',25);\nhp(1)=gpatch(F,V,'kw','none',0.5);\nhp(2)=gpatch(Fd,Vd,'gw','k',1,2);\nlegend(hp,{'Original mesh','Resampled mesh'},'Location','SouthOutSide');\n\naxisGeom;\ncamlight headlight;\ndrawnow;\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_meshDistMarch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6305328436479748}} {"text": "function filtered_image = gaussianbpf(I,d0,d1)\n\t% Butterworth Bandpass Filter\n\t% This simple function was written for my Digital Image Processing course\n\t% at Eastern Mediterranean University taught by\n\t% Assoc. Prof. Dr. Hasan Demirel\n\t% for the 2010-2011 Spring Semester\n\t% for the complete report:\n\t% http://www.scribd.com/doc/51981950/HW4-Frequency-Domain-Bandpass-Filtering\n\t%\n\t% Written By:\n\t% Leonardo O. Iheme (leonardo.iheme@cc.emu.edu.tr)\n\t% 24th of March 2011\n\t%\n\t% I = The input grey scale image\n\t% d0 = Lower cut off frequency\n\t% d1 = Higher cut off frequency\n\t%\n\t% The function makes use of the simple principle that a bandpass filter\n\t% can be obtained by multiplying a lowpass filter with a highpass filter\n\t% where the lowpass filter has a higher cut off frquency than the high pass filter.\n\t%\n\t% Usage GAUSSIANBPF(I,DO,D1)\n\t% Example\n\t% ima = imread('grass.jpg');\n\t% ima = rgb2gray(ima);\n\t% filtered_image = gaussianbpf(ima,30,120);\n\t% Gaussian Bandpass Filter\n\t%\n\t% biafra ahanonu\n\t% updated: 2013.11.09 [13:20:43]\n\t% changelog\n\t\t% 2013.11.09 [13:21:06] updated function so it no longer converts to uint8 as this causes problems. Also, changed filtered_image = fftI + filter3.*fftI; to filtered_image = filter3.*fftI;\n\t\t% 2014.06.03 - updated to do binary fft\n\n\n\tf = double(I);\n\t[nx ny] = size(f);\n\t% f = uint8(f);\n\tfftI = fft2(f,2*nx-1,2*ny-1);\n\tfftI = fftshift(fftI);\n\n\t% subplot(2,2,1)\n\t% imshow(f,[]);\n\t% title('Original Image')\n\n\t% subplot(2,2,2)\n\t% fftshow(fftI,'log')\n\t% title('Fourier Spectrum of Image')\n\t% Initialize filter.\n\t% filter1 = ones(2*nx-1,2*ny-1);\n\t% filter2 = ones(2*nx-1,2*ny-1);\n\t% filter3 = ones(2*nx-1,2*ny-1);\n\t% % ======\n\t% % Gaussian\n\t% for i = 1:2*nx-1\n\t% for j =1:2*ny-1\n\t% dist = ((i-(nx+1))^2 + (j-(ny+1))^2)^.5;\n\t% % Use Gaussian filter.\n\t% filter1(i,j) = exp(-dist^2/(2*d1^2));\n\t% filter2(i,j) = exp(-dist^2/(2*d0^2));\n\t% filter3(i,j) = 1.0 - filter2(i,j);\n\t% filter3(i,j) = filter1(i,j).*filter3(i,j);\n\t% end\n\t% end\n\t% ======\n\t% binary\n\timageSize = size(fftI);\n\tci = [round(imageSize(1)/2), round(imageSize(2)/2), 10]; % center and radius of circle ([c_row, c_col, r])\n\t[xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));\n\tfilter3 = logical((xx.^2 + yy.^2)<(ci(3)^2));\n\t% imagesc(mask)\n\t% ======\n\t% Update image with passed frequencies\n\tfftI_filtered = filter3.*fftI;\n\t% subplot(2,2,3)\n\t% fftshow(filter3,'log')\n\t% title('Frequency Domain Filter Function Image')\n\tfiltered_image = ifftshift(fftI_filtered);\n\tfiltered_image = ifft2(filtered_image,2*nx-1,2*ny-1);\n\tfiltered_image = real(filtered_image(1:nx,1:ny));\n\tfiltered_image = double(filtered_image);\n\t% filtered_image = uint8(filtered_image);\n\t% ======\n\t% imagesc(filter3)\n\tsubplot(2,2,1)\n\tfftshow(fftI_filtered,'log')\n\tsubplot(2,2,2)\n\tfftshow(fftI,'log')\n\tsubplot(2,2,3)\n\timagesc(I)\n\tsubplot(2,2,4)\n\timshow(filtered_image,[])\n\ttitle('Bandpass Filtered Image')", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/_external_programs/_file_exchange/gaussianbpf/gaussianbpf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6305328372190353}} {"text": "function [ i_lo, i_hi ] = r8vec_sorted_range ( n, r, r_lo, r_hi )\n\n%*****************************************************************************80\n%\n%% R8VEC_SORTED_RANGE searches a sorted vector for elements in a range.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of items in the vector.\n%\n% Input, real R(N), the sorted vector.\n%\n% Input, real R_LO, R_HI, the limits of the range.\n%\n% Output, integer I_LO, I_HI, the range of indices\n% so that I_LO <= I <= I_HI => R_LO <= R(I) <= R_HI. If no\n% values in R lie in the range, then I_HI < I_LO will be returned.\n%\n\n%\n% Cases we can handle immediately.\n%\n if ( r(n) < r_lo )\n i_lo = 0;\n i_hi = - 1;\n return\n end\n\n if ( r_hi < r(1) )\n i_lo = 0;\n i_hi = - 1;\n return\n end\n%\n% Are there are least two intervals?\n%\n if ( n == 1 )\n if ( r_lo <= r(1) && r(1) <= r_hi )\n i_lo = 1;\n i_hi = 1;\n else\n i_lo = 0;\n i_hi = -1;\n end\n return\n end\n%\n% Bracket R_LO.\n%\n if ( r_lo <= r(1) )\n\n i_lo = 1;\n\n else\n%\n% R_LO is in one of the intervals spanned by R(J1) to R(J2).\n% Examine the intermediate interval [R(I1), R(I1+1)].\n% Does R_LO lie here, or below or above?\n%\n j1 = 1;\n j2 = n;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n\n while ( 1 )\n\n if ( r_lo < r(i1) )\n j2 = i1;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n elseif ( r(i2) < r_lo )\n j1 = i2;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n else\n i_lo = i1;\n break;\n end\n\n end\n\n end\n%\n% Bracket R_HI\n%\n if ( r(n) <= r_hi )\n\n i_hi = n;\n\n else\n\n j1 = i_lo;\n j2 = n;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n\n while ( 1 )\n\n if ( r_hi < r(i1) )\n j2 = i1;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n elseif ( r(i2) < r_hi )\n j1 = i2;\n i1 = floor ( ( j1 + j2 - 1 ) / 2 );\n i2 = i1 + 1;\n else\n i_hi = i2;\n break\n end\n\n end\n\n end\n%\n% We expect to have computed the largest I_LO and smallest I_HI such that\n% R(I_LO) <= R_LO <= R_HI <= R(I_HI)\n% but what we want is actually\n% R_LO <= R(I_LO) <= R(I_HI) <= R_HI\n% which we can usually get simply by incrementing I_LO and decrementing I_HI.\n%\n if ( r(i_lo) < r_lo )\n i_lo = i_lo + 1;\n if ( n < i_lo )\n i_hi = i_lo - 1;\n end\n end\n\n if ( r_hi < r(i_hi) )\n i_hi = i_hi - 1;\n if ( i_hi < 1 )\n i_lo = i_hi + 1;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_sorted_range.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6302866822887406}} {"text": "close all\nclear\n\npos_rob = [-0.5,-0.5;0.5,0.5];\npos_ref = [1.1,1;-1.1,-1];\npos_circ = [-0.5,-0.5;0.5,0.5]/2;\n\n% circular constraint sets\nzbf_circ = @(i,pos_rob) 1-(pos_rob(i,:)-pos_circ(i,:))*(pos_rob(i,:)-pos_circ(i,:))';\n% nominal control\nknom = 1;\nunom_rob = @(i,pos_rob) -knom*(pos_rob(i,:)-pos_ref(i,:));\n% bounded distance costraints\nld = 0.5; ud = 1;\nzbf_lb = @(i,j,pos_rob) (pos_rob(i,:)-pos_rob(j,:))*(pos_rob(i,:)-pos_rob(j,:))'-ld^2;\nzbf_ub = @(i,j,pos_rob) ud^2-(pos_rob(i,:)-pos_rob(j,:))*(pos_rob(i,:)-pos_rob(j,:))';\n% extended K-class function\nakcf = 1;\nekcf = @(h) akcf*h;\n% control barrier function (less or equal)\ncbfa_circ = @(i,pos_rob) pos_rob(i,:)-pos_circ(i,:);\ncbfb_circ = @(i,pos_rob) ekcf(zbf_circ(i,pos_rob));\ncbfa_lb = @(i,j,pos_rob) -(pos_rob(i,:)-pos_rob(j,:));\ncbfb_lb = @(i,j,pos_rob) ekcf(zbf_lb(i,j,pos_rob));\ncbfa_ub = @(i,j,pos_rob) -cbfa_lb(i,j,pos_rob);\ncbfb_ub = @(i,j,pos_rob) ekcf(zbf_ub(i,j,pos_rob));\n\n% simulation\ndt = 0.01;\nT = 10;\nloop = 0;\ncolor_list = ['b','g','m','r','c'];\nfor t=0:dt:T\n loop = loop+1;\n % control barrier function - quadratic program\n for i=1:2\n fqp = -unom_rob(i,pos_rob)';\n aqp = cbfa_circ(i,pos_rob);\n bqp = cbfb_circ(i,pos_rob);\n for j=1:2\n if i~=j\n aqp = [aqp;cbfa_lb(i,j,pos_rob)];\n bqp = [bqp;cbfb_lb(i,j,pos_rob)];\n aqp = [aqp;cbfa_ub(i,j,pos_rob)];\n bqp = [bqp;cbfb_ub(i,j,pos_rob)];\n end\n end\n [uqp,~,is_solved] = quadprog(eye(2),fqp,aqp,bqp);\n uqp_rob(i,:) = uqp';\n end\n % update\n pos_rob = pos_rob+dt*uqp_rob;\n % plot\n for i=1:2\n plot(pos_rob(i,1),pos_rob(i,2),[color_list(i) 'o']); hold on\n circle_(pos_circ(i,:),1,'color',color_list(i));\n plot(pos_ref(i,1),pos_ref(i,2),[color_list(i) 'd']);\n quiver(pos_rob(i,1),pos_rob(i,2),uqp_rob(i,1),uqp_rob(i,2))\n end\n hold off\n drawnow\nend\n\n\n", "meta": {"author": "star2dust", "repo": "paper-simulation", "sha": "2d35e3beeccd2ce41f60c59e347b090f25960706", "save_path": "github-repos/MATLAB/star2dust-paper-simulation", "path": "github-repos/MATLAB/star2dust-paper-simulation/paper-simulation-2d35e3beeccd2ce41f60c59e347b090f25960706/Ibuki2020Optimization/main_cbf_two_agents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6302397849687756}} {"text": "function y = nanmax(x,dim)\n% nanmax - Max ignoring NaNs.\n%\n% Synopsis:\n% y = nanmax(x)\n% y = nanmax(x,dim)\n% \n% Arguments:\n% x: Matrix or vector\n% dim: Dimension along which sum operates. Default: First non-singleton\n% dimension.\n% \n% Returns:\n% y: max along the chosen dimension, treating NaNs as missing values.\n% \n% Description:\n% For vectors, nanmax(X) is the max of the non-NaN elements in\n% X. For matrices, nanmax(X) is a row vector containing the max\n% of the non-NaN elements in each column of X. For N-D arrays,\n% nanmax(X) operates along the first non-singleton dimension.\n%\n% nanmax(X,dim) determaxes the max along the dimension dim. \n% \n% Examples:\n% nanmax([1 2 NaN]) returns 2.\n% nanmax([1 2 NaN], 1) returns [1 2 NaN].\n% nanmax([1 2 NaN], 2) returns 2.\n% \n% See also: nansum,nanmean,nanstd\n% \n\n% Author(s): Benjamax Blankertz, Anton Schwaighofer, Aug 2005\n\nif nargin<2,\n % Operate along the first non-singleton dimension\n dim = max(find(size(x)~=1));\n if isempty(dim),\n dim = 1; \n end\nend\n% Replace NaNs with zeros.\nnans = isnan(x);\nx(nans) = -inf;\n\n% Protect against an entire column of NaNs\ny = max(x, [], dim);\nallNaNs = all(nans, dim);\ny(allNaNs) = NaN;\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/utils/nanmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6301825257189166}} {"text": "%%*************************************************************************\n%% iterrefine: Iterative refinement. \n%% This step is crucial to ensure that computed solution \n%% is sufficiently accuraete. \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 [x,resnrm,solve_ok] = iterrefine(A,b,L,x0); \n\n tol = 1e-6; \n maxit = 10; \n bnorm = max(1,norm(b)); \n tolb = tol*bnorm;\n x = x0; \n solve_ok = 1; \n resnrm(1) = bnorm;\n%%\n for iter = 1:maxit\n x0 = x; \n if isstruct(A); r = b-matvec(A,x); else; r=b-A*x; end; \n err = norm(r); \n resnrm(iter+1) = err; \n \n if (err < tolb); break; end; \n if (iter > 1) & (resnrm(iter+1)/resnrm(iter) > 0.9)\n x = x0; solve_ok = 0; break; \n end\n\td = linsysolvefun(L,r); \n x = x + d; \n end\n%%*************************************************************************\n%% matvec: matrix-vector multiply.\n%% matrix = [A.mat11 A.mat12; A.mat12' A.mat22]\n%%*************************************************************************\n\n function Ax = matvec(A,x);\n\n m = length(A.mat11); m2 = length(x)-m; \n x1 = x(1:m); \n Ax = A.mat11*x1;\n if (m2 > 0)\n x2 = x(m+[1:m2]);\n Ax = Ax + A.mat12*x2; \n Ax2 = (x1'*A.mat12)' + A.mat22*x2;\n Ax = [Ax; Ax2]; \n end\n return;\n%%*************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/Oldmfiles/iterrefine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6301825237506827}} {"text": "function [ a, ipvt, info ] = dchdc ( a, lda, p, ipvt, job )\n\n%*****************************************************************************80\n%\n%% DCHDC computes the Cholesky decomposition of a positive definite matrix.\n%\n% Discussion:\n%\n% A pivoting option allows the user to estimate the condition of a\n% positive definite matrix or determine the rank of a positive\n% semidefinite matrix.\n%\n% For positive definite matrices, INFO = P is the normal return.\n%\n% For pivoting with positive semidefinite matrices, INFO will\n% in general be less than P. However, INFO may be greater than\n% the rank of A, since rounding error can cause an otherwise zero\n% element to be positive. Indefinite systems will always cause\n% INFO to be less than P.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,P), the matrix whose decomposition is to\n% be computed. Only the upper half of A need be stored.\n% The lower part of the array a is not referenced.\n%\n% Input, integer LDA, the leading dimension of the array A.\n%\n% Input, integer P, the order of the matrix.\n%\n% Input, integer IPVT(P), integers that control the selection\n% of the pivot elements, if pivoting has been requested.\n% Each diagonal element A(K,K) is placed in one of three classes\n% according to the value of IPVT(K).\n%\n% > 0, then X(K) is an initial element.\n% = 0, then X(K) is a free element.\n% < 0, then X(K) is a final element.\n%\n% Before the decomposition is computed, initial elements are moved by\n% symmetric row and column interchanges to the beginning of the array A\n% and final elements to the end. Both initial and final elements are\n% frozen in place during the computation and only free elements are moved.\n% At the K-th stage of the reduction, if A(K,K) is occupied by a free\n% element, it is interchanged with the largest free element A(L,L) with\n% K <= L. IPVT is not referenced if JOB is 0.\n%\n% Input, integer JOB, initiates column pivoting.\n% 0, no pivoting is done.\n% nonzero, pivoting is done.\n%\n% Output, real A(LDA,P), contains in its upper half the Cholesky factor\n% of the input matrix, as it has been permuted by pivoting.\n%\n% Output, integer IPVT(N); IPVT(J) contains the index of the diagonal element\n% of A that was moved into the J-th position, if pivoting was requested.\n%\n% Output, integer INFO, contains the index of the last positive diagonal\n% element of the Cholesky factor.\n%\n pl = 1;\n pu = 0;\n info = p;\n\n if ( job ~= 0 )\n%\n% Pivoting has been requested.\n% Rearrange the the elements according to IPVT.\n%\n for k = 1 : p\n\n swapk = 0 < ipvt(k);\n\n negk = ipvt(k) < 0;\n\n if ( negk )\n ipvt(k) = -k;\n else\n ipvt(k) = k;\n end\n\n if ( swapk )\n\n if ( k ~= pl )\n\n temp(1:pl-1) = a(1:pl-1,k);\n a(1:pl-1,k) = a(1:pl-1,pl);\n a(1:pl-1,pl) = temp(1:pl-1);\n\n temp = a(k,k);\n a(k,k) = a(pl,pl);\n a(pl,pl) = temp;\n\n for j = pl+1 : p\n\n if ( j < k )\n temp = a(pl,j);\n a(pl,j) = a(j,k);\n a(j,k) = temp;\n elseif ( k < j )\n temp = a(k,j);\n a(k,j) = a(pl,j);\n a(pl,j) = temp;\n end\n\n end\n\n ipvt(k) = ipvt(pl);\n ipvt(pl) = k;\n\n end\n\n pl = pl + 1;\n\n end\n\n end\n\n pu = p;\n\n for k = p : -1 : pl\n\n if ( ipvt(k) < 0 )\n\n ipvt(k) = -ipvt(k);\n\n if ( pu ~= k )\n\n temp(1:k-1) = a(1:k-1,k);\n a(1:k-1,k) = a(1:k-1,pu);\n a(1:k-1,pu) = temp(1:k-1);\n\n temp = a(k,k);\n a(k,k) = a(pu,pu);\n a(pu,pu) = temp;\n\n for j = k+1 : p\n\n if ( j < pu )\n temp = a(k,j);\n a(k,j) = a(j,pu);\n a(j,pu) = temp;\n elseif ( pu < j )\n temp = a(k,j);\n a(k,j) = a(pu,j);\n a(pu,j) = temp;\n end\n\n end\n\n jt = ipvt(k);\n ipvt(k) = ipvt(pu);\n ipvt(pu) = jt;\n\n end\n\n pu = pu - 1;\n\n end\n\n end\n\n end\n\n for k = 1 : p\n%\n% Reduction loop.\n%\n maxdia = a(k,k);\n maxl = k;\n%\n% Determine the pivot element.\n%\n if ( pl <= k & k < pu )\n\n for l = k+1 : pu\n if ( maxdia < a(l,l) )\n maxdia = a(l,l);\n maxl = l;\n end\n end\n\n end\n%\n% Quit if the pivot element is not positive.\n%\n if ( maxdia <= 0.0 )\n info = k - 1;\n return\n end\n%\n% Start the pivoting and update IPVT.\n%\n if ( k ~= maxl )\n\n temp(1:k-1) = a(1:k-1,k);\n a(1:k-1,k) = a(1:k-1,maxl);\n a(1:k-1,maxl) = temp(1:k-1);\n\n a(maxl,maxl) = a(k,k);\n a(k,k) = maxdia;\n jp = ipvt(maxl);\n ipvt(maxl) = ipvt(k);\n ipvt(k) = jp;\n\n end\n%\n% Reduction step.\n% Pivoting is contained across the rows.\n%\n work(k) = sqrt ( a(k,k) );\n a(k,k) = work(k);\n\n for j = k+1 : p\n\n if ( k ~= maxl )\n\n if ( j < maxl )\n temp = a(k,j);\n a(k,j) = a(j,maxl);\n a(j,maxl) = temp;\n elseif ( maxl < j )\n temp = a(k,j);\n a(k,j) = a(maxl,j);\n a(maxl,j) = temp;\n end\n\n end\n\n a(k,j) = a(k,j) / work(k);\n work(j) = a(k,j);\n temp = -a(k,j);\n a(k+1:k+j-k,j) = a(k+1:k+j-k,j) + temp * work(k+1:k+j-k)';\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dchdc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6301825208953802}} {"text": "function[varargout]=windtrans(varargin)\n%WINDTRANS Ekman-like transfer-functions for the wind-driven response.\n%\n% G=WINDTRANS(OMEGA,Z,FC,DELTA,MU,H) returns the no-slip transfer \n% function for the wind-driven currents evaluated at frequencies OMEGA\n% and at depths Z. G will have LENGTH(OMEGA) rows and LENGTH(Z) columns.\n%\n% Here FC is the local Coriolis frequency, DELTA is the Ekman depth.\n% MU is the Madsen depth, and H is the boundary layer depth.\n%\n% The units of these quantitites are important. For consistency with \n% other routines, OMEGA and FC are in radians per day, while Z, DELTA,\n% MU, and H are all in meters. The units of G are then m^2 s / kg.\n%\n% WINDTRANS(...,'free') instead returns the free slip transfer function.\n%\n% For details on the expressions implemented by this function, see\n%\n% Lilly, J. M. and S. Elipot (2021). A unifying perspective on \n% transfer function solutions to the unsteady Ekman problem. \n% Fluids, 6 (2): 85, 1--36. \n% __________________________________________________________________\n%\n% Special forms\n%\n% By default WINDTRANS uses the general transfer function. WINDTRANS \n% will also employ limiting expressions for special cases, as follows.\n%\n% H = Inf -- Mixed Ekman / Madsen solution\n% H = Inf, MU = 0 -- Ekman solution\n% H = Inf, DELTA = 0 -- Madsen solution\n% MU = 0 -- Finite-layer Ekman solution\n% DELTA = 0 -- Finite-layer Madsen solution\n%\n% These have to be coded separately because the full solution is singular\n% in these cases.\n% __________________________________________________________________\n%\n% Computational options\n%\n% When computed over a wide range of parameter space, the transfer\n% function tends to be encounter numerical overflow when the arguments to\n% Bessel functions become large, causing its computation to fail.\n%\n% To avoid this problems, by default WINDTRANS switches to using a highly\n% accurate thirty-term expansion about the large-argument exponential \n% behavior of the Bessel functions when their arguments exceed 10^2.9. \n%\n% Two other options are available, primarily for testing purposes. Both\n% of these other algorithms lead to artifacts and are not recommended.\n%\n% WINDTRANS(...'far',...) switches instead to use the (inferior) one-term \n% expansion, also known as the far-inertial limit.\n%\n% WINDTRANS(...,'general',...) uses the general formula with no switch.\n%\n% Note that these options only apply to no-slip solution. The free-slip\n% solution, which is not deemed to be physically relevant, is only\n% computed with the general formula.\n%\n% For details on these algorithms, see Lilly and Elipot (2021).\n% __________________________________________________________________\n%\n% 'windtrans --t' runs a some tests.\n%\n% Usage: G=windtrans(omega,z,fc,delta,mu,h);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2019--2021 J.M. Lilly --- type 'help jlab_license' for details\n \n\n% WINDTRANS(OMEGA,Z,FC,DELTA,MU,A,'AMP') alternately parameterizes the\n% transfer function in terms of the magntide of the near-inertial peak A\n% in 1/m, together with the Ekman and Madsen depths DELTA and MU.\n\n% Gradient output\n%\n% [G,DDELTA,DH]=WINDTRANS(OMEGA,Z,FC,DELTA,0,H) for the Ekman-like model\n% also returns the partial derivatives with respect to DELTA and H.\n\nif strcmp(varargin{1}, '--t')\n windtrans_test,return\nend\n \nomega=varargin{1}(:)/24/3600;%convert to rad/second\nz=varargin{2};\nfc=varargin{3}/24/3600;%convert to rad/second\ndelta=varargin{4};\nmu=varargin{5};\nh=varargin{6};\n\ntol=100;\nrho=1027;\nstr='expansion';%use the 30-term tilde expansion by default\n%str='two';%use the two-term tilde expansion by default\nslipstr='noslip';\n\nbool=false(2,1);\nfor i=7:nargin\n istr=varargin{i}(1:3);\n if strcmpi(istr,'gen')||strcmpi(istr,'eli')||strcmpi(istr,'far')||strcmpi(istr,'ada')||strcmpi(istr,'exp')||strcmpi(istr,'two')\n str=varargin{i};\n if strcmpi(str(1:3),'exp')\n bool(1)=true;\n end\n elseif strcmpi(istr,'fre')||strcmpi(istr,'nos')\n slipstr=varargin{i};\n if strcmpi(slipstr(1:3),'fre')\n bool(2)=true;\n end\n end\nend\n\n%this is just to keep track of an unsuitable combination of input arguments\nif all(bool)\n disp('Sorry, the tilde expansion algorithm is not implemented for the free-slip transfer function.') \nend\n%these may have been either input, or reflecting the default behavior\nif strcmpi(str(1:3),'exp')&&strcmpi(slipstr(1:3),'fre')\n str='gen';\nend\n\nomega1=omega;\nif length(z)~=1\n [z,omega]=meshgrid(z,omega);\nend\n\n%if isinf(h)||delta==0||mu==0\n% str='lilly';%use the lilly version of expressions for special cases\n%end\n\n%str,slipstr\nG=zeros(size(omega));\nif strcmpi(slipstr(1:3),'nos')\n %----------------------------------------------------------------------\n %The noslip forms\n %[G,xiz,xih,xi0]=windtrans_general_noslip(delta,fc,rho,z,mu,omega,h,str);\n % G=windtrans_general_noslip(delta,fc,rho,z,mu,omega,h,str);\n if strcmpi(str(1:3),'gen')|| strcmpi(str(1:3),'far')||strcmpi(str(1:3),'exp')||strcmpi(str(1:3),'two')\n [G,varargout{2},varargout{3}]=windtrans_lilly_noslip(delta,fc,rho,z,mu,omega,h,str);\n elseif strcmpi(str(1:3),'eli')%asymptotic forms, elipot edition\n G=windtrans_elipot_noslip(delta,fc,rho,z,mu,omega,h);\n end\nelseif strcmpi(slipstr(1:3),'fre')\n %----------------------------------------------------------------------\n %The freeslip forms\n\n K0=frac(1,2)*delta.^2.*abs(fc);\n K1=frac(1,2)*mu*abs(fc);\n\n s=sign(fc).*sign(1+omega./fc);\n zo=delta.^2./mu;\n [xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h);\n\n coeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*rho.*abs(fc).*sqrt(abs(1+omega./fc)));\n [k0z,i0z,k1h,i1h,k10,i10]=bessels_freeslip(xiz,xih,xi0);\n \n if strcmpi(str(1:3),'gen')||(strcmpi(str(1:3),'lil')&&((K0~=0)&&(K1~=0)))\n numer=i0z.*k1h+i1h.*k0z;\n denom=i1h.*k10-i10.*k1h;\n G=coeff.*frac(numer,denom);\n elseif strcmpi(str(1:3),'lil')\n % [h,K0,K1]\n if mu==0\n coeff=frac(sqrt(2).*rot(-s*pi/4),delta.*abs(fc).*rho.*sqrt(abs((1+omega./fc))));\n cosharg=sqrt(2).*rot(s*pi/4).*frac(h-z,delta).*sqrt(abs((1+omega./fc)));\n sinharg=sqrt(2).*rot(s*pi/4).*frac(h,delta).*sqrt(abs((1+omega./fc)));\n G=coeff.*frac(cosh(cosharg),sinh(sinharg));\n elseif delta==0\n coeff=frac(2,rho*K1);\n k0z=besselk(0,2*rot(s*pi/4).*sqrt(frac(z,K1./abs(fc)).*abs(1+omega./fc)));\n k1h=besselk(1,2*rot(s*pi/4).*sqrt(frac(h,K1./abs(fc)).*abs(1+omega./fc)));\n i0z=besseli(0,2*rot(s*pi/4).*sqrt(frac(z,K1./abs(fc)).*abs(1+omega./fc)));\n i1h=besseli(1,2*rot(s*pi/4).*sqrt(frac(h,K1./abs(fc)).*abs(1+omega./fc)));\n G=coeff.*(k0z+frac(k1h.*i0z,i1h));\n end\n elseif strcmpi(str(1:3),'eli')\n \n delta1=sqrt(2.*K0./(omega+fc));\n delta2=K1./(omega+fc);\n xize=2*sqrt(1i*(zo+z)./delta2);\n xi0e=2*sqrt(1i*zo./delta2);\n xihe=2*sqrt(1i*(zo+h)./delta2);\n \n if mu==0\n coeff=frac(1,rho.*sqrt(1i*(omega+fc).*K0));\n numer=cosh((1+1i).*(h-z)./delta1);\n denom=sinh((1+1i).*h./delta1);\n G=coeff.*numer./denom;\n elseif delta==0\n coeff=(2./rho./K1);\n k0z=besselk(0,2.*sqrt(1i.*z./delta2));\n k1h=besselk(1,2*sqrt(1i.*h./delta2));\n i0z=besseli(0,2*sqrt(1i.*z./delta2));\n i1h=besseli(1,2*sqrt(1i.*h./delta2));\n G=coeff.*(k0z+frac(k1h.*i0z,i1h));\n else\n coeff=frac(1,rho.*sqrt(1i.*(omega+fc).*K0));\n k0z=besselk(0,xize);\n k10=besselk(1,xi0e);\n i10=besseli(1,xi0e);\n i0z=besseli(0,xize);\n k1h=besselk(1,xihe);\n i1h=besseli(1,xihe);\n numer=i0z.*k1h+i1h.*k0z;\n denom=i1h.*k10-i10.*k1h;\n G=coeff.*frac(numer,denom);\n end\n end\nend\nG(z>h)=nan;\n\nvarargout{1}=G;\n%varargout{2}=xih;\n%varargout{3}=xiz;\n%varargout{4}=xi0;\n\nfunction[xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h)\n\nxiz=2*sqrt(2).*rot(s.*pi/4).*(zo./delta).*sqrt((1+z./zo).*abs((1+omega./fc)));\nxih=2*sqrt(2).*rot(s.*pi/4).*(zo./delta).*sqrt((1+h./zo).*abs((1+omega./fc)));\nxi0=2*sqrt(2).*rot(s.*pi/4).*(zo./delta).*sqrt(abs((1+omega./fc)));\n\nfunction[k0z,i0z,k0h,i0h,k10,i10]=bessels_noslip(varargin)\n\nargz=varargin{1};\nargh=varargin{2};\nif length(varargin)==3\n arg0=varargin{3};\nend\n\nk0z=besselk(0,argz);\ni0z=besseli(0,argz);\nk0h=besselk(0,argh);\ni0h=besseli(0,argh);\n\nif nargout>4\n k10=besselk(1,arg0);\n i10=besseli(1,arg0);\nend\n\nfunction[k0z,i0z,k0h,i0h,k10,i10]=besseltildes_noslip(argz,argh,arg0,nterms)\n\nk0z=besselktilde(0,argz,nterms);\ni0z=besselitilde(0,argz,nterms);\nk0h=besselktilde(0,argh,nterms);\ni0h=besselitilde(0,argh,nterms);\n\nk10=besselktilde(1,arg0,nterms);\ni10=besselitilde(1,arg0,nterms);\n\nfunction[k0z,i0z,k1h,i1h,k10,i10]=bessels_freeslip(argz,argh,arg0)\n\nk0z=besselk(0,argz);\ni0z=besseli(0,argz);\nk1h=besselk(1,argh);\ni1h=besseli(1,argh);\n\nif nargout>4\n k10=besselk(1,arg0);\n i10=besseli(1,arg0);\nend\n\nfunction[G]=windtrans_expansion_noslip(delta,fc,rho,z,mu,omega,h,str)\n\nzo=delta.^2./mu;\ns=sign(fc).*sign(1+omega./fc);\n[xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h);\ncoeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*rho.*abs(fc).*sqrt(abs(1+omega./fc)));\n\nif strcmpi(str(1:3),'two')\n [k0z,i0z,k0h,i0h,k10,i10]=besseltildes_noslip(xiz,xih,xi0,2);\nelseif strcmpi(str(1:3),'exp')\n [k0z,i0z,k0h,i0h,k10,i10]=besseltildes_noslip(xiz,xih,xi0,30);\nend\n \nnumer=exp(xi0-xiz).*i0h.*k0z-exp(xi0+xiz-2*xih).*k0h.*i0z;\ndenom=i0h.*k10+exp(2*xi0-2*xih).*k0h.*i10;\nG=coeff.*frac(numer,denom);\n\nbool=(omega==-fc);\nif ~isinf(h)&&~isinf(zo)\n if length(z)==1\n G(bool)=frac(4*zo,rho*abs(fc)*delta.^2).*frac(sqrt(1+h./zo)-sqrt(1+z./zo),(1+z./zo).^(1/4));\n else\n G(bool)=frac(4*zo,rho*abs(fc)*delta.^2).*frac(sqrt(1+h./zo)-sqrt(1+z(bool)./zo),(1+z(bool)./zo).^(1/4));\n end\nelseif isinf(h)\n G(bool)=inf;\nend\n\nfunction[G,xiz,xih,xi0]=windtrans_general_noslip(delta,fc,rho,z,mu,omega,h,str)\n\nzo=delta.^2./mu;\ns=sign(fc).*sign(1+omega./fc);\n[xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h);\ncoeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*rho.*abs(fc).*sqrt(abs(1+omega./fc)));\n\n[k0z,i0z,k0h,i0h,k10,i10]=bessels_noslip(xiz,xih,xi0);\n\n%numerically, better to do it like this to avoid having huge numbers dominate\n%tests shows this removes the large-argument overflow when only h (not z) is large\n\nnumer=k0z./k10-(k0h./k10).*(i0z./i0h);\ndenom=1+(k0h./k10).*(i10./i0h);\nG=coeff.*frac(numer,denom);\n\n\nif strcmpi(str(1:3),'exp')||strcmpi(str(1:3),'two')\n bool=log10(abs(xiz))>2.9;\n if ~isempty(find(bool,1)) \n if length(z)==1\n G(bool)=windtrans_expansion_noslip(delta,fc,rho,z,mu,omega(bool),h,str);\n else\n G(bool)=windtrans_expansion_noslip(delta,fc,rho,z(bool),mu,omega(bool),h,str);\n end\n end\nelseif strcmpi(str(1:3),'far')\n bool=log10(abs(xiz))>2.9;\n if ~isempty(find(bool,1)) \n if length(z)==1\n G(bool)=windtrans_farinertial_noslip(delta,fc,rho,z,mu,omega(bool),h);\n else\n G(bool)=windtrans_farinertial_noslip(delta,fc,rho,z(bool),mu,omega(bool),h);\n end\n end\nend\nG=windtrans_inertiallimit(G,delta,fc,rho,z,mu,omega,h);\n\n\n\n\nfunction[G]=windtrans_farinertial_noslip(delta,fc,rho,z,mu,omega,h)\n\nzo=delta.^2./mu;\ns=sign(fc).*sign(1+omega./fc);\n[xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h);\ncoeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*abs(fc).*rho);\n\nnumer=exp(-xiz+xi0)-exp(xiz+xi0-2*xih);\ndenom=1+exp(2*xi0-2*xih);\nG=coeff.*frac(1,sqrt(abs(1+omega./fc)).*(1+z./zo).^(1/4)).*frac(numer,denom);\n%Don't apply the inertial limit!\n\nfunction[G]=windtrans_inertiallimit(G,delta,fc,rho,z,mu,omega,h)\n\nzo=delta.^2./mu;\nbool=(omega==-fc);\n\nif ~isempty(find(bool,1))\n if ~isinf(h)&&~isinf(zo)\n if length(z)==1\n %G(bool)=frac(2*zo,rho*abs(fc)*delta.^2).*log(frac(1+h./zo,1+z./zo));\n G(bool)=frac(2,rho*abs(fc)*mu).*log(frac(1+h./zo,1+z./zo));\n else\n %G(bool)=frac(2*zo,rho*abs(fc)*delta.^2).*log(frac(1+h./zo,1+z./zo));\n G(bool)=frac(2,rho*abs(fc)*mu).*log(frac(1+h./zo,1+z(bool)./zo));\n end\n elseif ~isinf(h)&&isinf(zo)\n if length(z)==1\n G(bool)=frac(2,rho*abs(fc)*delta.^2).*(h-z);\n else\n G(bool)=frac(2,rho*abs(fc)*delta.^2).*(h-z(bool));\n end\n else\n G(bool)=inf;\n end\nend\n\nfunction[G,ddelta,dh]=windtrans_lilly_noslip(delta,fc,rho,z,mu,omega,h,str)\n\nzo=delta.^2./mu;\ns=sign(fc).*sign(1+omega./fc);\n[xiz,xih,xi0]=xis(s,zo,delta,z,omega,fc,h);\n%[delta,zo,K0,K1]\n\nif h==inf\n if mu==0\n %Ekman solution\n coeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*abs(fc).*rho);\n G=coeff.*frac(exp(-(1+s.*1i).*(z./delta).*sqrt(abs((1+omega./fc)))),sqrt(abs((1+omega./fc))));\n elseif delta==0\n %Madsen solution\n coeff=frac(4,rho*abs(fc)*mu);\n G=coeff.*besselk(0,2*sqrt(2)*rot(s.*pi/4).*sqrt(frac(z,mu).*abs(1+omega./fc)));\n else\n %Mixed solution\n k0z=besselk(0,xiz);\n k10=besselk(1,xi0);\n coeff=frac(sqrt(2).*rot(-s.*pi/4),delta.*abs(fc).*rho.*sqrt(abs((1+omega./fc))));\n G=coeff.*frac(k0z,k10);\n end\nelse\n if mu==0\n %finite-layer Ekman\n coeff=frac(sqrt(2).*rot(-s*pi/4),delta.*abs(fc).*rho.*sqrt(abs((1+omega./fc))));\n %sinharg=sqrt(2).*rot(s*pi/4).*frac(h-z,delta).*sqrt(abs((1+omega./fc)));\n %cosharg=sqrt(2).*rot(s*pi/4).*frac(h,delta).*sqrt(abs((1+omega./fc)));\n %G=coeff.*frac(sinh(sinharg),cosh(cosharg)); \n %can't do it this way because you divide two huge numbers\n \n argh=sqrt(2).*rot(s*pi/4).*frac(h,delta).*sqrt(abs((1+omega./fc)));\n argz=sqrt(2).*rot(s*pi/4).*frac(z,delta).*sqrt(abs((1+omega./fc)));\n \n numer=exp(-argz)-exp(argz).*exp(-2*argh);\n denom=1+exp(-2*argh);\n G=coeff.*frac(numer,denom);\n \n bool=(omega==-fc);\n if length(z)==1\n G(bool)=frac(2,rho*abs(fc)*delta.^2).*(h-z);\n else\n G(bool)=frac(2,rho*abs(fc)*delta.^2).*(h-z(bool));\n end\n elseif delta==0\n % if z==0\n % coeff=frac(4,rho*abs(fc)*mu);\n % argz=2*sqrt(2)*rot(s*pi/4).*sqrt(frac(z,mu).*abs(1+omega./fc));\n % argh=2*sqrt(2)*rot(s*pi/4).*sqrt(frac(h,mu).*abs(1+omega./fc));\n %\n % [k0z,i0z,k0h,i0h]=bessels_noslip(argz,argh);\n % length(find(isnan(k0z)))\n % length(find(isnan(i0z)))\n % length(find(isnan(k0h)))\n % length(find(isnan(i0h)))\n % length(find(isnan(argh)))\n %\n % %figure,plot(abs(argh))\n %\n % G=-coeff.*(log(xi0)+frac(1,2)*(z./zo)+frac(k0h,i0h));\n % G=-coeff.*(log(xi0./xih)+frac(1,2)*(z./zo));\n % length(find(isnan(xi0./xih)))\n %\n % else\n %finite-layer Madsen\n coeff=frac(4,rho*abs(fc)*mu);\n argz=2*sqrt(2)*rot(s*pi/4).*sqrt(frac(z,mu).*abs(1+omega./fc));\n argh=2*sqrt(2)*rot(s*pi/4).*sqrt(frac(h,mu).*abs(1+omega./fc));\n [k0z,i0z,k0h,i0h]=bessels_noslip(argz,argh);\n G=coeff.*(k0z-i0z.*frac(k0h,i0h));\n \n bool=(omega==-fc);\n if length(z)==1\n G(bool)=frac(1,2)*coeff.*log(h./z);\n else\n G(bool)=frac(1,2)*coeff.*log(h./z(bool));\n end\n %end\n else\n %General solution\n G=windtrans_general_noslip(delta,fc,rho,z,mu,omega,h,str);\n end\nend\n\nif mu==0\n s=sign(fc).*sign(1+omega./fc);\n Gamma=sqrt(2).*rot(s*pi/4).*sqrt(abs((1+omega./fc)));\n ddelta1=(Gamma.*frac(h,delta).*tanh(Gamma.*frac(h,delta))-1).*G./delta;\n numer=exp(Gamma.*frac(-z,delta))+exp(-Gamma.*frac(2*h-z,delta));\n denom=1+exp(-Gamma.*frac(2*h,delta));\n ddelta2=-frac(2,delta.^2.*abs(fc).*rho).*frac(h-z,delta).*frac(numer,denom);\n ddelta=ddelta1+ddelta2;\n dh1=-Gamma.*frac(1,delta).*tanh(Gamma.*frac(h,delta)).*G;\n dh2=frac(2,delta.^2.*abs(fc).*rho).*frac(numer,denom);\n dh=dh1+dh2;\nelse\n ddelta=[];\n dh=[];\nend\n\n\nfunction[G]=windtrans_elipot_noslip(delta,fc,rho,z,mu,omega,h)\n\nzo=delta.^2./mu;\nK0=frac(1,2)*delta.^2.*abs(fc);\nK1=frac(1,2)*mu*abs(fc);\n\ndelta1=sqrt(2.*K0./(omega+fc));\ndelta2=K1./(omega+fc);\nxiz=2*sqrt(1i*(zo+z)./delta2);\nxi0=2*sqrt(1i*zo./delta2);\nxih=2*sqrt(1i*(zo+h)./delta2);\n\nif h==inf\n if K1==0\n %Ekman solution\n coeff=frac(1,rho.*sqrt(1i*(omega+fc).*K0));\n G=coeff.*exp(-z.*(1+1i)./delta1);\n elseif K0==0\n %Madsen solution\n coeff=(2./rho./K1);\n k0z=besselk(0,2.*sqrt(1i.*z./delta2));\n G=coeff.*k0z;\n else\n %Mixed solution\n coeff=frac(1,rho.*sqrt(1i.*(omega+fc).*K0));\n G=coeff.*besselk(0,xiz)./besselk(1,xi0);\n end\nelse\n if K1==0\n %finite-layer Ekman\n coeff=frac(1,rho.*sqrt(1i*(omega+fc).*K0));\n numer=sinh((1+1i).*(h-z)./delta1);\n denom=cosh((1+1i).*h./delta1);\n G=coeff.*numer./denom;\n elseif K0==0\n %finite-layer Madsen\n coeff=(2./rho./K1);\n k0z=besselk(0,2.*sqrt(1i.*z./delta2));\n k0h=besselk(0,2*sqrt(1i.*h./delta2));\n i0z=besseli(0,2*sqrt(1i.*z./delta2));\n i0h=besseli(0,2*sqrt(1i.*h./delta2));\n G=coeff.*(k0z-frac(k0h.*i0z,i0h));\n else\n %General solution\n coeff=frac(1,rho.*sqrt(1i.*(omega+fc).*K0));\n [k0z,i0z,k0h,i0h,k10,i10]=bessels_noslip(xiz,xih,xi0);\n numer=i0h.*k0z-k0h.*i0z;\n denom=i10.*k0h+k10.*i0h;\n G=coeff.*frac(numer,denom);\n end\nend\n\nfunction[]=windtrans_test\nwindtrans_test_gradient;\nwindtrans_test_limits;\n\nfunction[]=windtrans_test_gradient\n\ndelta=10.^(-1:0.05:3);\nh=10.^(log10(15.15):.05:5);\n[dg,hg]=meshgrid(delta,h);\n\n[G,G1,G2,G3,G4,dg1,dg2]=vzeros(size(dg));\nddelta=1e-6;dh=1e-6;\nomega=-1e-4;\n%omega=-1.5e-4;\n%omega=-5e-4;\nfor j=1:length(delta)\n for i=1:length(h)\n %G=windtrans(omega,z,fc,delta,mu,h);\n [G(i,j),dg1(i,j),dg2(i,j)]=windtrans(omega,15,1e-4,dg(i,j),0,hg(i,j));\n G1(i,j)=windtrans(omega,15,1e-4,dg(i,j)-ddelta/2,0,hg(i,j));\n G2(i,j)=windtrans(omega,15,1e-4,dg(i,j)+ddelta/2,0,hg(i,j));\n G3(i,j)=windtrans(omega,15,1e-4,dg(i,j),0,hg(i,j)-dh/2);\n G4(i,j)=windtrans(omega,15,1e-4,dg(i,j),0,hg(i,j)+dh/2);\n end\nend\n\ndg1hat=frac(G2-G1,ddelta);\ndg2hat=frac(G4-G3,dh);\n\nbool=dg1hat~=0;\neps1=maxmax(log10(frac(abs(dg1hat(bool)-dg1(bool)),sqrt(squared(dg1hat(bool))+squared(dg1(bool))))));\nbool=dg2hat~=0;\neps2=maxmax(log10(frac(abs(dg2hat(bool)-dg2(bool)),sqrt(squared(dg2hat(bool))+squared(dg2(bool))))));\n\n%jpcolor(log10(delta),log10(h),real(dg1))\n%figure,jpcolor(log10(delta),log10(h),log10(frac(abs(dg1hat-dg1),sqrt(squared(dg1hat)+squared(dg1)))))\n%jpcolor(log10(delta),log10(h),log10(frac(abs(dg2hat-dg2),sqrt(squared(dg2hat)+squared(dg2)))))\n\nreporttest(['WINDTRANS analytic and numerical gradients match for Ekman case'],eps1<-4&&eps2<-4)\n\nfunction[]=windtrans_test_limits\n \nN=1000;\nz=[0.1:1:100];\nh=[inf 200];\nK0=[0 1/10 1/10];\nK1=[1 0 1];\nfc=1e-4;\ndelta=sqrt(frac(2*K0,fc));\nmu=frac(2*K1,fc);\n\n[bool1,bool2,bool3,bool4]=vzeros(length(K0),2);\n[Ge,Go,Gl,Ga]=vzeros(N,length(z),length(K0),2);\nslipstr='noslip';\nomega=fourier(1,N,'two');\n \nfor s=[1 -1]\n for i=1:length(K0)\n for j=1:2\n Ge(:,:,i,j)=windtrans(omega,z,s/2,delta(i),mu(i),h(j),'elipot',slipstr);\n Gl(:,:,i,j)=windtrans(omega,z,s/2,delta(i),mu(i),h(j),slipstr);\n Go(:,:,i,j)=windtrans(omega,z,s/2,delta(i)+1e-14,mu(i)+0.5,h(j),slipstr,'general');\n Ga(:,:,i,j)=windtrans(omega,z,s/2,delta(i)+1e-14,mu(i)+0.5,h(j),slipstr,'two');\n Ge(:,:,i,j)=Ge(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n Go(:,:,i,j)=Go(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n Ga(:,:,i,j)=Ga(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n Gl(:,:,i,j)=Gl(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n \n bool1(i,j)=aresame(Ge(:,:,i,j),Gl(:,:,i,j),1e-8);\n bool2(i,j)=aresame(Ge(:,:,i,j),Go(:,:,i,j),1e-1);\n bool3(i,j)=aresame(Gl(:,:,i,j),Go(:,:,i,j),1e-1);\n bool4(i,j)=aresame(Ga(:,:,i,j),Go(:,:,i,j),1e-20);\n end\n end\n \n if s==1\n reporttest(['WINDTRANS Elipot and Lilly forms match for f>0 and ' slipstr ' condition'],allall(bool1))\n reporttest(['WINDTRANS general and special forms match for f>0 and ' slipstr ' condition'],allall(bool2).*allall(bool3))\n reporttest(['WINDTRANS general and expansion forms match for f>0 and ' slipstr ' condition'],allall(bool4).*allall(bool3))\n else\n reporttest(['WINDTRANS Elipot and Lilly forms match for f<0 and ' slipstr ' condition'],allall(bool1))\n reporttest(['WINDTRANS general and special forms match for f<0 and ' slipstr ' condition'],allall(bool2).*allall(bool3))\n reporttest(['WINDTRANS general and expansion forms match for f>0 and ' slipstr ' condition'],allall(bool4).*allall(bool3))\n end\nend\n\n\n% older test for freeslip forms; not currently particularly relevant \n% h=20;\n% z=[0.1:1:20];\n% [bool1,bool2,bool3]=vzeros(length(K0),1);\n% [Ge,Go,Gl]=vzeros(N,length(z),length(K0));\n% slipstr='freeslip';\n% for s=[1 -1]\n% for i=1:length(K0)\n% for j=1:length(h)\n% i,j,s\n% Ge(:,:,i,j)=windtrans(omega,z,s/2,delta(i),mu(i),h(j),'elipot',slipstr);\n% Gl(:,:,i,j)=windtrans(omega,z,s/2,delta(i),mu(i),h(j),'lilly',slipstr);\n% Go(:,:,i,j)=windtrans(omega,z,s/2,delta(i)+1e-10,mu(i)+0.5,h(j),slipstr,'general');\n% Ge(:,:,i,j)=Ge(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n% Go(:,:,i,j)=Go(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n% Gl(:,:,i,j)=Gl(:,:,i,j)./maxmax(abs(Gl(:,:,i,j)));\n% bool1(i,j)=aresame(Ge(:,:,i,j),Gl(:,:,i,j),1e-8);\n% bool2(i,j)=aresame(Ge(:,:,i,j),Go(:,:,i,j),1e-1);\n% bool3(i,j)=aresame(Gl(:,:,i,j),Go(:,:,i,j),1e-1);\n% end\n% end\n% \n% if s==1\n% reporttest(['WINDTRANS Elipot and Lilly forms match for f>0 and ' slipstr ' condition'],allall(bool1))\n% reporttest(['WINDTRANS general and special forms match for f>0 and ' slipstr ' condition'],allall(bool2).*allall(bool3))\n% else\n% reporttest(['WINDTRANS Elipot and Lilly forms match for f<0 and ' slipstr ' condition'],allall(bool1))\n% reporttest(['WINDTRANS general and special forms match for f<0 and ' slipstr ' condition'],allall(bool2).*allall(bool3))\n% end\n% end\n\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jOceans/windtrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6301825055377017}} {"text": " function [deriv, curv] = trl_dercurv(data, li, curvtype, iblock, nblock)\n%function [deriv, curv] = trl_dercurv(data, li, curvtype, iblock, nblock)\n%\n% evaluate derivatives and curvatures for monoenergetic Poisson transmission\n% negative log-likelihoods: f(x) = \\sum_i h_i(l), h_i(l) = mi(l) - yi log mi(l)\n% mi(l) = bi exp(-l) + ri\n%\n% in\n%\tdata\t{yi, bi, ri}\n%\t\t\t\tyi is [nb,na]. bi, ri are same or scalar\n%\t\t\t\tpassed to trl_curvature()\n%\tli\t[nb,#view_in_block]\n%\tcurvtype ''\t\tcurvature type\n%\tiblock, nblock\t\tfor OS type methods\n%\n% out\n%\tderiv\t[nb,#]\t\t\\dot hi(l)\n%\tcurv\t[nb,#]\t\tsurrogate curvature for hi at li\n%\n% Copyright 2004-2-1, Jeff Fessler, The University of Michigan\n\nif nargin < 2, ir_usage, end\nif nargin < 3, curvtype = 'pc'; end\n\nyi = data{1};\nbi = data{2};\nri = data{3};\n\nif nargin == 5\n\tia = iblock:nblock:size(yi,2);\n\tyi = yi(:,ia);\n\tif length(bi) > 1\n\t\tbi = bi(:,ia);\n\tend\n\tif length(ri) > 1\n\t\tri = ri(:,ia);\n\tend\nend\n\n\n% transmission Poisson likelihood function\nei = exp(-li);\nmi = bi .* ei + ri;\nderiv = (1 - yi ./ mi) .* (-bi .* ei);\n\ncurv = trl_curvature(yi, bi, ri, li, curvtype);\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/transmission/trl_dercurv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.6301470091914263}} {"text": "function [out] = area_1(p1,p2,S,Smin,Smax,varargin)\n%area_1 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Auxiliary function that calculates a variable contributing area.\n% Constraints: A <= 1\n% @(Inputs): p1 - linear scaling parameter [-]\n% p2 - exponential scaling parameter [-]\n% S - current storage [mm]\n% Smin - minimum contributing storage [mm]\n% Smax - maximum contributing storage [mm]\n% varargin(1) - smoothing variable r (default 0.01)\n% varargin(2) - smoothing variable e (default 5.00)\n\nif size(varargin,2) == 0\n out = min(1,p1.*(max(0,S-Smin)./(Smax-Smin)).^p2).*...\n (1-smoothThreshold_storage_logistic(S,Smin)); % default smoothing\nelseif size(varargin,2) == 1\n out = min(1,p1.*(max(0,S-Smin)./(Smax-Smin)).^p2).*...\n (1-smoothThreshold_storage_logistic(S,Smin,varargin(1))); % user-specified smoothing\nelseif size(varargin,2) == 2\n out = min(1,p1.*(max(0,S-Smin)./(Smax-Smin)).^p2).*...\n (1-smoothThreshold_storage_logistic(S,Smin,varargin(1),varargin(2))); % user-specified smoothing\nend\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/area_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6301469706203858}} {"text": "function [ Tt ] = updateTransform2(T,w,v,dt)\n% This function takes the input of the \nnormw=norm(w);\nif normw>0\n R1=T(1:3,1:3);\n wCrossR1=zeros(3,3);\n for i=1:3\n wCrossR1(:,i)=cross(w,R1(:,i));\n end\n Rt=R1+wCrossR1*dt;\nelse\n Rt=T(1:3,1:3);\nend\n\ndx=v*dt;\nxt=T(1:3,4)+dx;\n\nTt=[Rt,xt];\nTt=[Tt;\n 0 0 0 1];\nTt=normalizeTransformMatrix(Tt);\nend\n\n\nfunction R=quat2rot(q)\nR=[(1-2*q(3)*q(3)-2*q(4)*q(4)), 2*(q(1)*q(3)-q(1)*q(4)), 2*(q(2)*q(4)+q(1)*q(3));\n2*(q(2)*q(3)+q(1)*q(4)), (1-2*q(2)*q(2)-2*q(4)*q(4)), 2*(q(3)*q(4)-q(1)*q(2));\n2*(q(2)*q(4)-q(1)*q(3)), 2*(q(3)*q(4)+q(1)*q(2)), (1-2*q(2)*q(2)-2*q(3)*q(3))];\nend\n\nfunction T=normalizeTransformMatrix(t)\nT=zeros(4,4);\nT(:,4)=t(:,4);\nfor i=1:3\n T(1:3,i)=t(1:3,i)/norm(t(1:3,i));\nend\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/updateTransform2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6301433596570819}} {"text": "function [A, B] = reflexKronApprox( K, m, n, Rtol )\n%\n% [A, B] = reflexKronApprox( K, m, n, Rtol );\n%\n% computes a kronecker sum approximation to the blurring matrix K\n% that arises from the input PSF under reflexive boundary conditions.\n% This approximation is done a-la Nagy-Ng-Perrone (see paper for details).\n%\n% Input:\n% K - psfMatrix object\n% m - size of matrix A (assumed square)\n% n - size of matrix B (assumed square)\n% Rtol - relative tolerance ( <=1 ); determines number of kron products\n% in the approximation. If si/s1 > Rtol, \n% where si is the ith largest\n% singular value of the weighted PSF,\n% then Ai(x)Bi will be included in the approximation.\n% IF ONLY ONE TERM IN THE SUM IS DESIRED, USE Rtol = 1.\n%\n% Output:\n% Cells A and B such that K \\approx \\sum_i[ A{i} \\otimes B{i} ].\n%\n\n% L. Perrone, 4/28/02\n\n% Modifications: \n% 5/25/02, J. Nagy \n% Cosmetic changes to incorporate into RestoreTools \n%\n% 9/??/02 L. Perrone\n% This code now conforms to the new kronMatrix class,\n% where fields K.a and K.b are cell arrays containing\n% (possibly) more than one matrix, depending on Rtol.\n% 11/22/02 L. Perrone\n% The kronMatrix class should work for image processing\n% problems, where it is common to use lexicographical (row)\n% ordering. However, the kronMatrix class was designed\n% using vec(column) ordering (unlike all other classes\n% in the RestoreTools package). Until now, the inconsistency\n% remained hidden because the PSFs in use\n% had been symmetric or close to symmetric. \n% This discrepancy has now been fixed.\n\n\n\nP1 = K.psf;\nP2 = P1.image;\nPSF = P2{1};\nc1 = P1.center;\ncenter = c1{1};\n\n[mp, np] = size(PSF);\n\nif ( mp ~= np )\n error('For now, we expect PSF to be square')\nend\n\n%\n% Compute weighted PSF.\n%\nc = zeros(mp,1);\nc(1) = mp;\nc(2:2:end) = 1;\nR = chol( toeplitz(c) );\n\nPhat = R*PSF*R';\n\n%\n% Compute SVD of weighted PSF, which is then used to construct\n% the separable approximation.\n%\n[U,S,V] = svd( Phat );\n\n%\n% check to make sure first column looks like\n% a Gaussian, and is not inverted.\n%\nminU = abs(min(min(U(:,1))));\nmaxU = max(max(abs(U(:,1))));\nif minU == maxU\n U = -U;\n V = -V;\nend\n\n%\n% Construct approximation.\n%\nA = cell(1);\nB = cell(1);\ni=1;\nPP = zeros(size(PSF));\nwhile S(i,i)/S(1,1) >= Rtol\n a = R \\ ( U(:,i) * sqrt(S(i,i)) );\n b = R \\ ( V(:,i) * sqrt(S(i,i)) );\n PP = PP + a*b';\n % Comment out the next two statements, replace with the two that\n % follow, in order to fix the 11/22/02 problem.\n %A{i} = build_toep(a, center(1), m) + buildHank(a, center(1), m);\n %B{i} = build_toep(b, center(2), n) + buildHank(b, center(2), n);\n B{i} = build_toep(a, center(1), m) + buildHank(a, center(1), m);\n A{i} = build_toep(b, center(2), n) + buildHank(b, center(2), n);\n i=i+1;\nend\n\n\n%\n% The following scales the approximation so that the\n% corresponding PSF approximation has the property\n% that its sum of values is the same as the sum of the\n% original PSF values.\n%\ncs = sqrt(sum(PSF(:))/sum(PP(:)));\nfor i = 1:length(A)\n A{i} = cs*A{i};\n B{i} = cs*B{i};\n AA = A{i};\n BB = B{i};\nend\n\n\n", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/Extra/prblur_tools/@psfMatrix/private/reflexKronApprox_save.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6301433529412835}} {"text": "function CPD = root_gaussian_CPD(bnet, self, mu, Sigma, mu0, n0, alpha0, beta0)\n% ROOT_GAUSSIAN_CPD Make an unconditional Gaussian distrib.\n%\n% CPD = root_gaussian_CPD(bnet, self, mu, Sigma)\n% This defines the distribution Y ~ N(mu, Sigma),\n% Pass in [] to generate a default random value for a parameter.\n%\n% CPD = root_gaussian_CPD(bnet, self, [], [], mu0, n0, alpha0, beta0)\n% defines a Normal-Wishart prior over the parameters:\n% P(mu | lambda) = N(mu | mu0, n0*lambda)\n% P(lambda) = Wishart(lambda | alpha0, beta0)\n% where lambda = inv(Sigma) is the precision matrix of mu.\n% n0 is a scale factor, beta0 is a precision matrix.\n% Pass in [] to generate a default value for a hyperparameter.\n% mu and Sigma will be set to their prior expected values.\n% See \"Bayesian Theory\", Bernardo and Smith (2000), p441.\n\n\nif nargin==0\n % This occurs if we are trying to load an object from a file.\n CPD = init_fields;\n CPD = class(CPD, 'root_gaussian_CPD', generic_CPD(0));\n return;\nelseif isa(bnet, 'root_gaussian_CPD')\n % This might occur if we are copying an object.\n CPD = bnet;\n return;\nend\nCPD = init_fields;\n\n\nns = bnet.node_sizes;\nd = ns(self);\n\nif nargin < 5,\n prior = [];\n if isempty(mu), mu = randn(d, 1); end\n if isempty(Sigma), Sigma = eye(d); end\nelse\n if isempty(mu0), mu0 = zeros(d, 1); end\n if isempty(n0), n0 = 0.1; end\n if isempty(alpha0), alpha0 = (d-1)/2 + 1; end % Wishart requires 2 alpha > d-1\n if isempty(beta0), beta0 = eye(d); end\n \n prior.mu = mu0;\n prior.n = n0;\n prior.alpha = alpha0;\n prior.beta = beta0;\n \n % set params to their mean\n mu = prior.mu;\n Sigma = prior.beta/prior.alpha; % mean of Wishart is E[lambda] = alpha*inv(beta)\nend\n\nCPD.self = self;\nCPD.mu = mu;\nCPD.Sigma = Sigma;\nCPD.prior = prior;\n\nclamped = 0;\nCPD = class(CPD, 'root_gaussian_CPD', generic_CPD(clamped));\n\n\n%%%%%%%%%%%\n\nfunction CPD = init_fields()\n% This ensures we define the fields in the same order \n% no matter whether we load an object from a file,\n% or create it from scratch. (Matlab requires this.)\n\nCPD.self = [];\nCPD.mu = [];\nCPD.Sigma = [];\nCPD.prior = [];\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/CPDs/Old/@root_gaussian_CPD/root_gaussian_CPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.630143349835621}} {"text": "function varargout = projPointOnPolygon(point, poly, varargin)\n%PROJPOINTONPOLYGON Compute position of a point projected on a polygon\n%\n% POS = projPointOnPolygon(POINT, POLYGON)\n% Compute the position of the orthogonal projection of a point on a\n% polygon.\n% POINT is a 1-by-2 row vector containing point coordinates\n% POLYGON is a N-by-2 array containing coordinates of polygon vertices\n%\n% When POINT is an array of points, returns a column vector with as many\n% rows as the number of points. \n%\n% [POS, DIST] = projPointOnPolygon(...)\n% Also returns the distance between POINT and POLYGON. The distance is\n% negative if the point is located inside of the polygon.\n%\n% Example\n% poly = [10 10; 20 10;20 20;10 20];\n% projPointOnPolygon([15 0], poly)\n% ans =\n% 0.5000\n% projPointOnPolygon([0 16], poly)\n% ans =\n% 3.4000\n%\n% See also\n% points2d, polygons2d, polygonPoint, projPointOnPolyline\n% distancePointpolygon\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2009-04-30, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\n\n% eventually copy first point at the end to ensure closed polygon\nif sum(poly(end, :) == poly(1,:)) ~= 2\n poly = [poly; poly(1,:)];\nend\n\n% compute position wrt outline\n[pos, minDist] = projPointOnPolyline(point, poly);\n\n% process output arguments\nif nargout <= 1\n varargout{1} = pos;\nelseif nargout == 2\n varargout{1} = pos;\n if inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2))\n minDist = -minDist;\n end\n varargout{2} = minDist;\nend", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/polygons2d/projPointOnPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6299851503109813}} {"text": "function point_num = sphere_llq_grid_point_count ( lat_num, long_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLQ_GRID_POINT_COUNT counts points for a SPHERE LLQ grid.\n%\n% Discussion:\n%\n% A SPHERE LLQ grid imposes a grid of quadrilaterals on a sphere,\n% using latitude and longitude lines.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 28 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LAT_NUM, LONG_NUM, the number of latitude \n% and longitude lines to draw. The latitudes do not include the North and \n% South poles, which will be included automatically, so LAT_NUM = 5, for \n% instance, will result in points along 7 lines of latitude.\n%\n% Output, integer POINT_NUM, the number of grid points.\n%\n point_num = 2 + lat_num * long_num;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_llq_grid/sphere_llq_grid_point_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.6299007414105736}} {"text": "%==============================================================================\n% This code is part of the Finite Element Method app for the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR/FAIRFEM \n%==============================================================================\n%\n% classdef TetraMesh1 < handle\n%\n% Finite Element Mesh based on tetrahedral subdivision of rectangular mesh.\n%\n% Each Cell is divided into 24 tetrahedra:\n%\n%\n% To construct an instance of this class type:\n%\n% >> Mesh = TriMesh1(omega,m)\n%\n% Input:\n% \tomega - description of spatial domain\n% m - number of cells\n%\n% Properties:\n% xn - node list\n% tri - triangle list\n% dim - space dimension\n% omega - description of spatial domain\n% m - number of cells\n% type - type of partition\n% vol - volume of triangles\n% nnodes - number of nodes\n% ntri - number of triangles\n% dx1 - partial derivative operator\n% dx2 - partial derivative operator\n% dx3 - partial derivative operator\n% GRAD - gradient operator\n% P1 - projection operator for node 1\n% P2 - projection operator for node 2\n% P3 - projection operator for node 3\n% P4 - projection operator for node 4\n% PC - projection operator for Barycentrum\n% P - prolongation operator\n% Pt - restriction operator\n%\n% Methods:\n% mfPu - matrix free prolongation/restriction\n% mfPi - matrix free edge projector\n% getP - builds prolongation operator\n% tri2cc - averaging\n%\n%\n% see also\n% =========================================================================\nclassdef TetraMesh1 < handle\n \n properties\n % ===================================\n % node list\n % ===================================\n xn\n % ===================================\n % triangle list\n % ===================================\n tri\n % ===================================\n % space dimension\n % ===================================\n dim = 3;\n % ===================================\n % description of computational domain\n % ===================================\n omega\n % ===================================\n % number of cells\n % ===================================\n m\n % ===================================\n % type of partition\n % ===================================\n type = 1;\n % ===================================\n % function handle to myself\n % ===================================\n me = @TetraMesh1;\n % ===================================\n % volume of triangles\n % ===================================\n vol\n % ===================================\n % number of nodes\n % ===================================\n nnodes\n % ===================================\n % number of triangles in mesh\n % ===================================\n ntri\n end\n \n properties (Access = public, Dependent) % These will be created when first callend and stores persistently\n % ===================================\n % dx1 - partial derivative operator\n % ===================================\n dx1\n % ===================================\n % dx2 - Partial derivative operator\n % ===================================\n dx2\n % ===================================\n % dx3 - Partial derivative operator\n % ===================================\n dx3\n % ===================================\n % GRAD - Gradient operator\n %\n % | dx1 |\n % | |\n % GRAD = | dx2 |\n % | |\n % | dx3 |\n %\n % ===================================\n GRAD\n % ===================================\n % B - Vector gradient operator\n %\n % | GRAD 0 0 |\n % | |\n % B = | 0 GRAD 0 |\n % | |\n % | 0 0 GRAD |\n %\n % ===================================\n B\n % ===================================\n % P1 - Projection operator on Node 1\n % ===================================\n P1\n % ===================================\n % P2 - Projection operator on Node 2\n % ===================================\n P2\n % ===================================\n % P3 - Projection operator on Node 3\n % ===================================\n P3\n % ===================================\n % P4 - Projection operator on Node 4\n % ===================================\n P4\n % ===================================\n % PC - Projection operator on Barycenter\n % ===================================\n PC\n % ===================================\n % P - Prolongation operator\n % ===================================\n P\n % ===================================\n % Pt - Restriction operator\n % ===================================\n Pt\n % ===================================\n % Boundary indices\n % ===================================\n boundaryIdx\n % ===================================\n % Boundary projector\n % ===================================\n boundaryProj\n mfdx1\n mfdx2\n mfdx3\n mfGRAD\n end\n \n properties (Access = private)\n % These are where the dependent data is actually stored\n dx1_\n dx2_\n dx3_\n GRAD_\n B_\n P1_\n P2_\n P3_\n P4_\n PC_\n P_\n Pt_\n mfdx1_\n mfdx2_\n mfdx3_\n mfGRAD_\n boundaryIdx_\n boundaryProj_\n end\n \n methods\n function this = TetraMesh1(omega,m)\n if nargin==0,\n help(mfilename);\n this.runMinimalExample;\n return;\n end\n h = (omega(2:2:end)-omega(1:2:end))./m;\n this.omega = omega;\n this.m = m;\n \n % get nodes (combine nodal, stg-1,stg-2,stg-3,cc grids)\n xc = @(i) linspace(omega(2*i-1)+h(i)/2,omega(2*i)-h(i)/2,m(i))'; % cell centers\n xn = @(i) linspace(omega(2*i-1),omega(2*i),m(i)+1)'; % nodes\n % add nodal grid\n nn = reshape(1:prod(m+1),m+1);\n nn = reshape(nn(1:end-1,1:end-1,1:end-1),1,[]); % get indices of bottom left vertices\n this.xn = reshape(getNodalGrid(omega,m),[],3);\n % add stg-1 grid\n ns = prod(ones(length(m),1)*m+eye(length(m)),2); %staggered\n ns1 = reshape(size(this.xn,1)+(1:ns(1)),[m(1)+1 m(2) m(3)]);\n ns1 = reshape(ns1(1:end-1,:,:),1,[]); % get indices of bottom left vertices\n [x1,x2,x3] = ndgrid(xn(1),xc(2),xc(3));\n this.xn = [this.xn; x1(:), x2(:), x3(:)];\n % add stg-2 grid\n ns2 = reshape(size(this.xn,1)+(1:ns(2)),[m(1) m(2)+1 m(3)]);\n ns2 = reshape(ns2(:,1:end-1,:),1,[]); % get indices of bottom left vertices\n [x1,x2,x3] = ndgrid(xc(1),xn(2),xc(3));\n this.xn = [this.xn; x1(:), x2(:), x3(:)];\n % add stg-3 grid\n ns3 = reshape(size(this.xn,1)+(1:ns(3)),[m(1) m(2) m(3)+1]);\n ns3 = reshape(ns3(:,:,1:end-1),1,[]); % get indices of bottom left vertices\n [x1,x2,x3] = ndgrid(xc(1),xc(2),xn(3));\n this.xn = [this.xn; x1(:), x2(:), x3(:)];\n % add cc grid\n nc = reshape(size(this.xn,1)+(1:prod(m)),m);\n nc = reshape(nc,1,[]); % get indices of bottom left vertices\n this.xn = [this.xn; reshape(getCellCenteredGrid(omega,m),[],3)];\n \n % specify triangles\n iyn = m(1)+1; izn = prod(m(1:2)+1); izc = prod(m(1:2));\n this.tri = [\n nn; nn+1; ns2; nc;\n nn+1; nn+izn+1; ns2; nc;\n nn+izn+1; nn+izn; ns2; nc;\n nn+izn; nn; ns2; nc; % 4\n nn+1; nn+iyn+1; ns1+1; nc;\n nn+iyn+1; nn+iyn+1+izn; ns1+1; nc;\n nn+iyn+1+izn; nn+1+izn; ns1+1; nc;\n nn+1+izn; nn+1; ns1+1; nc; % 8\n nn+1; nn; ns3; nc;\n nn; nn+iyn; ns3; nc;\n nn+iyn; nn+1+iyn; ns3; nc;\n nn+1+iyn; nn+1; ns3; nc; % 12 \n \n nn+iyn; nn; ns1; nc;\n nn; nn+izn; ns1; nc;\n nn+izn; nn+iyn+izn; ns1; nc;\n nn+iyn+izn; nn+iyn; ns1; nc; % 16\n \n nn+iyn+1; nn+iyn; ns2+m(1); nc;\n nn+iyn; nn+iyn+izn; ns2+m(1); nc;\n nn+iyn+izn; nn+iyn+1+izn; ns2+m(1); nc;\n nn+iyn+1+izn; nn+iyn+1; ns2+m(1); nc; % 20\n nn+izn; nn+izn+1; ns3+izc; nc;\n nn+izn+1; nn+izn+1+iyn; ns3+izc; nc;\n nn+iyn+1+izn; nn+iyn+izn; ns3+izc; nc;\n nn+iyn+izn; nn+izn; ns3+izc; nc; % 24\n ];\n this.tri = reshape(this.tri,4,[])';\n this.nnodes = size(this.xn,1);\n this.ntri = size(this.tri,1);\n this.vol = prod((omega(2:2:end)-omega(1:2:end))./m)/24*ones(this.ntri,1);\n end\n \n function runMinimalExample(~)\n omega = [0 4 2 6 0 3]; m = [3 4 6];\n Mesh = feval(mfilename,omega,m);\n end\n \n function x = mfPi(this,x,i)\n % =============================================================\n % function x = mfPi(this,x,i)\n %\n % matrix free edge projector\n % =============================================================\n switch i\n case 1\n P = this.P1;\n case 2\n P = this.P2;\n case 3\n P = this.P3;\n case 4\n P = this.P4;\n case 'C'\n P = this.PC;\n end\n if size(x,1) == this.ntri,\n % ajoint\n x = P'*x;\n else\n x = P * x;\n end\n end\n \n function x = tri2cc(this,x)\n % =============================================================\n % function x = tri2cc(x)\n %\n % averaging or adjoint\n % =============================================================\n if numel(x)==this.ntri,\n x = mean(reshape(x,24,[]),1);\n else\n x = reshape(x,1,[]);\n x = (1/24)*repmat(x,[24 1]);\n x = x(:);\n end\n \n end\n \n \n \n function Pu = mfPuNodal(this,yn,m,flag)\n % =============================================================\n % function Pu = mfPuNodal(~,yn,m,flag)\n %\n % matrix free prolongation/restriction for nodal quantities\n % =============================================================\n yn = reshape(yn,[],this.dim);\n v = @(x) x(:);\n switch flag\n case 'Pu' % coarse --> fine\n mf = 2*m;\n \n % indices of coarse grid nodes (split by nodal, stg-i, c)\n ns = prod(ones(length(m),1)*m+eye(length(m)),2); %staggered\n inc = reshape(1:prod(m+1),m+1);\n is1c = reshape(prod(m+1)+(1:ns(1)),[m(1)+1 m(2) m(3)]);\n is2c = reshape(prod(m+1)+ns(1)+ (1:ns(2)),[m(1) m(2)+1 m(3)]);\n is3c = reshape(prod(m+1)+ns(1)+ns(2)+(1:ns(3)),[m(1) m(2) m(3)+1]);\n icc = reshape(prod(m+1)+ns(1)+ns(2)+ns(3)+(1:prod(m)),m);\n % indices of fine grid nodes\n ns = prod(ones(length(mf),1)*mf+eye(length(mf)),2); %staggered\n inf = reshape(1:prod(mf+1),mf+1);\n is1f = reshape(prod(mf+1)+(1:ns(1)),[mf(1)+1 mf(2) mf(3)]);\n is2f = reshape(prod(mf+1)+ns(1)+ (1:ns(2)),[mf(1) mf(2)+1 mf(3)]);\n is3f = reshape(prod(mf+1)+ns(1)+ns(2)+(1:ns(3)),[mf(1) mf(2) mf(3)+1]);\n icf = reshape(prod(mf+1)+ns(1)+ns(2)+ns(3)+(1:prod(mf)),mf);\n \n % allocate space\n Pu = zeros(icf(end),this.dim);\n \n % include existing nodes (nodal-->nodal)\n Pu(v(inf(1:2:end,1:2:end,1:2:end)),:) = yn(inc(:),:);\n % include existing nodes (stg-1-->nodal)\n Pu(v(inf(1:2:end,2:2:end,2:2:end)),:) = yn(is1c(:),:);\n % include existing nodes (stg-2-->nodal)\n Pu(v(inf(2:2:end,1:2:end,2:2:end)),:) = yn(is2c(:),:);\n % include existing nodes (stg-3-->nodal)\n Pu(v(inf(2:2:end,2:2:end,1:2:end)),:) = yn(is3c(:),:);\n % include existing nodes (cc-->nodal)\n Pu(v(inf(2:2:end,2:2:end,2:2:end)),:) = yn(icc(:),:);\n \n % average to get edge-stg-1\n Pu(v(inf(2:2:end,1:2:end,1:2:end)),:) = ...\n .5*(yn(v(inc(1:end-1,:,:)),:) + yn(v(inc(2:end,:,:)),:)) ;\n % average to get edge-stg-2\n Pu(v(inf(1:2:end,2:2:end,1:2:end)),:) = ...\n .5*(yn(v(inc(:,1:end-1,:)),:) + yn(v(inc(:,2:end,:)),:)) ;\n % average to get edge-stg-3\n Pu(v(inf(1:2:end,1:2:end,2:2:end)),:) = ...\n .5*(yn(v(inc(:,:,1:end-1)),:) + yn(v(inc(:,:,2:end)),:)) ;\n % get face-stg-1\n Pu(is1f(:),:) = .25*( Pu(v(inf(1:end,1:end-1,1:end-1)),:) ...\n + Pu(v(inf(1:end,2:end ,1:end-1)),:) ...\n + Pu(v(inf(1:end,2:end ,2:end )),:) ...\n + Pu(v(inf(1:end,1:end-1,2:end )),:));\n \n \n % get face-stg-2\n Pu(is2f(:),:) = .25*( Pu(v(inf(1:end-1,1:end ,1:end-1)),:) ...\n + Pu(v(inf(2:end ,1:end ,1:end-1)),:) ...\n + Pu(v(inf(2:end ,1:end ,2:end )),:) ...\n + Pu(v(inf(1:end-1,1:end ,2:end )),:));\n % get face-stg-3\n Pu(is3f(:),:) = .25*( Pu(v(inf(1:end-1,1:end-1,1:end)),:) ...\n + Pu(v(inf(2:end ,1:end-1,1:end)),:) ...\n + Pu(v(inf(2:end ,2:end ,1:end)),:) ...\n + Pu(v(inf(1:end-1,2:end ,1:end)),:));\n \n \n % get new cell-centers\n Pu(icf(:),:) = .125*( Pu(v(inf(1:end-1,1:end-1,1:end-1)),:) ...\n + Pu(v(inf(2:end ,1:end-1,1:end-1)),:) ...\n + Pu(v(inf(2:end ,2:end ,1:end-1)),:) ...\n + Pu(v(inf(1:end-1,2:end ,1:end-1)),:) ...\n + Pu(v(inf(1:end-1,1:end-1,2:end)),:) ...\n + Pu(v(inf(2:end ,1:end-1,2:end)),:) ...\n + Pu(v(inf(2:end ,2:end ,2:end)),:) ...\n + Pu(v(inf(1:end-1,2:end ,2:end)),:));\n \n \n case 'PTu' % fine --> coarse\n % include parent nodes\n mf = m;\n m = m/2;\n % indices of coarse grid nodes (split by nodal, stg-i, c)\n ns = prod(ones(length(m),1)*m+eye(length(m)),2); %staggered\n inc = reshape(1:prod(m+1),m+1);\n is1c = reshape(prod(m+1)+(1:ns(1)),[m(1)+1 m(2) m(3)]);\n is2c = reshape(prod(m+1)+ns(1)+ (1:ns(2)),[m(1) m(2)+1 m(3)]);\n is3c = reshape(prod(m+1)+ns(1)+ns(2)+(1:ns(3)),[m(1) m(2) m(3)+1]);\n icc = reshape(prod(m+1)+ns(1)+ns(2)+ns(3)+(1:prod(m)),m);\n % indices of fine grid nodes\n ns = prod(ones(length(mf),1)*mf+eye(length(mf)),2); %staggered\n inf = reshape(1:prod(mf+1),mf+1);\n is1f = reshape(prod(mf+1)+(1:ns(1)),[mf(1)+1 mf(2) mf(3)]);\n is2f = reshape(prod(mf+1)+ns(1)+ (1:ns(2)),[mf(1) mf(2)+1 mf(3)]);\n is3f = reshape(prod(mf+1)+ns(1)+ns(2)+(1:ns(3)),[mf(1) mf(2) mf(3)+1]);\n icf = reshape(prod(mf+1)+ns(1)+ns(2)+ns(3)+(1:prod(mf)),mf);\n \n % allocate space\n Pu = zeros(icc(end),this.dim);\n \n % push weights from cell-centers\n yn(v(inf(1:end-1,1:end-1,1:end-1)),:) = yn(v(inf(1:end-1,1:end-1,1:end-1)),:) + .125* yn(icf(:),:);\n yn(v(inf(2:end ,1:end-1,1:end-1)),:) = yn(v(inf(2:end ,1:end-1,1:end-1)),:) + .125* yn(icf(:),:);\n yn(v(inf(2:end ,2:end ,1:end-1)),:) = yn(v(inf(2:end ,2:end ,1:end-1)),:) + .125* yn(icf(:),:);\n yn(v(inf(1:end-1,2:end ,1:end-1)),:) = yn(v(inf(1:end-1,2:end ,1:end-1)),:) + .125* yn(icf(:),:);\n yn(v(inf(1:end-1,1:end-1,2:end)),:) = yn(v(inf(1:end-1,1:end-1,2:end)),:) + .125* yn(icf(:),:);\n yn(v(inf(2:end ,1:end-1,2:end)),:) = yn(v(inf(2:end ,1:end-1,2:end)),:) + .125* yn(icf(:),:);\n yn(v(inf(2:end ,2:end ,2:end)),:) = yn(v(inf(2:end ,2:end ,2:end)),:) + .125* yn(icf(:),:);\n yn(v(inf(1:end-1,2:end ,2:end)),:) = yn(v(inf(1:end-1,2:end ,2:end)),:) + .125* yn(icf(:),:);\n % push weights from face-stg-1\n yn(v(inf(1:end,1:end-1,1:end-1)),:) = yn(v(inf(1:end,1:end-1,1:end-1)),:) + .25 * yn(is1f(:),:);\n yn(v(inf(1:end,2:end ,1:end-1)),:) = yn(v(inf(1:end,2:end ,1:end-1)),:) + .25 * yn(is1f(:),:);\n yn(v(inf(1:end,2:end ,2:end )),:) = yn(v(inf(1:end,2:end ,2:end )),:) + .25 * yn(is1f(:),:);\n yn(v(inf(1:end,1:end-1,2:end )),:) = yn(v(inf(1:end,1:end-1,2:end )),:) + .25 * yn(is1f(:),:);\n % push weights from face-stg-2\n yn(v(inf(1:end-1,1:end ,1:end-1)),:) = yn(v(inf(1:end-1,1:end ,1:end-1)),:) + .25 * yn(is2f(:),:);\n yn(v(inf(2:end ,1:end ,1:end-1)),:) = yn(v(inf(2:end ,1:end ,1:end-1)),:) + .25 * yn(is2f(:),:);\n yn(v(inf(2:end ,1:end ,2:end )),:) = yn(v(inf(2:end ,1:end ,2:end )),:) + .25 * yn(is2f(:),:);\n yn(v(inf(1:end-1,1:end ,2:end )),:) = yn(v(inf(1:end-1,1:end ,2:end )),:) + .25 * yn(is2f(:),:);\n % push weights from face-stg-3\n yn(v(inf(1:end-1,1:end-1,1:end)),:) = yn(v(inf(1:end-1,1:end-1,1:end)),:) + .25 * yn(is3f(:),:);\n yn(v(inf(2:end ,1:end-1,1:end)),:) = yn(v(inf(2:end ,1:end-1,1:end)),:) + .25 * yn(is3f(:),:);\n yn(v(inf(2:end ,2:end ,1:end)),:) = yn(v(inf(2:end ,2:end ,1:end)),:) + .25 * yn(is3f(:),:);\n yn(v(inf(1:end-1,2:end ,1:end)),:) = yn(v(inf(1:end-1,2:end ,1:end)),:) + .25 * yn(is3f(:),:);\n \n % include existing nodes (nodal-->nodal)\n Pu(inc(:),:) = yn(v(inf(1:2:end,1:2:end,1:2:end)),:) ;\n % include existing nodes (stg-1-->nodal)\n Pu(is1c(:),:) = yn(v(inf(1:2:end,2:2:end,2:2:end)),:);\n % include existing nodes (stg-2-->nodal)\n Pu(is2c(:),:) = yn(v(inf(2:2:end,1:2:end,2:2:end)),:);\n % include existing nodes (stg-3-->nodal)\n Pu(is3c(:),:) = yn(v(inf(2:2:end,2:2:end,1:2:end)),:);\n % include existing nodes (cc-->nodal)\n Pu(icc(:),:) = yn(v(inf(2:2:end,2:2:end,2:2:end)),:);\n \n % average to get edge-stg-1\n Pu(v(inc(1:end-1,:,:)),:) = Pu(v(inc(1:end-1,:,:)),:) + .5 * yn(v(inf(2:2:end,1:2:end,1:2:end)),:);\n Pu(v(inc(2:end,:,:)),:) = Pu(v(inc(2:end,:,:)),:) + .5 * yn(v(inf(2:2:end,1:2:end,1:2:end)),:);\n \n % average to get edge-stg-2\n Pu(v(inc(:,1:end-1,:)),:) = Pu(v(inc(:,1:end-1,:)),:) + .5 * yn(v(inf(1:2:end,2:2:end,1:2:end)),:);\n Pu(v(inc(:,2:end ,:)),:) = Pu(v(inc(:,2:end ,:)),:) + .5 * yn(v(inf(1:2:end,2:2:end,1:2:end)),:);\n \n % average to get edge-stg-3\n Pu(v(inc(:,:,1:end-1)),:) = Pu(v(inc(:,:,1:end-1)),:) + .5 * yn(v(inf(1:2:end,1:2:end,2:2:end)),:);\n Pu(v(inc(:,:,2:end )),:) = Pu(v(inc(:,:,2:end )),:) + .5 * yn(v(inf(1:2:end,1:2:end,2:2:end)),:);\n \n end\n Pu = Pu(:);\n \n end\n function Pu = mfInterNodal(this,yn,m)\n % =============================================================\n % function Pu = mfInterNodal(~,yn,m,)\n %\n % interpolates to nodal grid of a finer resolution.\n % =============================================================\n yn = reshape(yn,[],this.dim);\n v = @(x) x(:);\n mf = 2*m;\n \n % indices of coarse grid nodes (split by nodal, stg-i, c)\n ns = prod(ones(length(m),1)*m+eye(length(m)),2); %staggered\n inc = reshape(1:prod(m+1),m+1);\n is1c = reshape(prod(m+1)+(1:ns(1)),[m(1)+1 m(2) m(3)]);\n is2c = reshape(prod(m+1)+ns(1)+ (1:ns(2)),[m(1) m(2)+1 m(3)]);\n is3c = reshape(prod(m+1)+ns(1)+ns(2)+(1:ns(3)),[m(1) m(2) m(3)+1]);\n icc = reshape(prod(m+1)+ns(1)+ns(2)+ns(3)+(1:prod(m)),m);\n % indices of fine grid nodes\n inf = reshape(1:prod(mf+1),mf+1);\n \n % allocate space\n Pu = zeros(inf(end),this.dim);\n \n % include existing nodes (nodal-->nodal)\n Pu(v(inf(1:2:end,1:2:end,1:2:end)),:) = yn(inc(:),:);\n % include existing nodes (stg-1-->nodal)\n Pu(v(inf(1:2:end,2:2:end,2:2:end)),:) = yn(is1c(:),:);\n % include existing nodes (stg-2-->nodal)\n Pu(v(inf(2:2:end,1:2:end,2:2:end)),:) = yn(is2c(:),:);\n % include existing nodes (stg-3-->nodal)\n Pu(v(inf(2:2:end,2:2:end,1:2:end)),:) = yn(is3c(:),:);\n % include existing nodes (cc-->nodal)\n Pu(v(inf(2:2:end,2:2:end,2:2:end)),:) = yn(icc(:),:);\n \n % average to get edge-stg-1\n Pu(v(inf(2:2:end,1:2:end,1:2:end)),:) = ...\n .5*(yn(v(inc(1:end-1,:,:)),:) + yn(v(inc(2:end,:,:)),:)) ;\n % average to get edge-stg-2\n Pu(v(inf(1:2:end,2:2:end,1:2:end)),:) = ...\n .5*(yn(v(inc(:,1:end-1,:)),:) + yn(v(inc(:,2:end,:)),:)) ;\n % average to get edge-stg-3\n Pu(v(inf(1:2:end,1:2:end,2:2:end)),:) = ...\n .5*(yn(v(inc(:,:,1:end-1)),:) + yn(v(inc(:,:,2:end)),:)) ;\n \n \n Pu = Pu(:);\n \n end\n \n \n function P = getPuNodal(~,m)\n % =============================================================\n % function P = getPuNodal(~,m)\n %\n % returns prolongation operator for input of cell-width m\n % =============================================================\n \n v = @(x) x(:);\n \n mf = 2*m;\n % indices of coarse grid nodes (split by nodal, stg-i, c)\n ns = prod(ones(length(m),1)*m+eye(length(m)),2); %staggered\n inc = reshape(1:prod(m+1),m+1);\n is1c = reshape(prod(m+1)+(1:ns(1)),[m(1)+1 m(2) m(3)]);\n is2c = reshape(prod(m+1)+ns(1)+ (1:ns(2)),[m(1) m(2)+1 m(3)]);\n is3c = reshape(prod(m+1)+ns(1)+ns(2)+(1:ns(3)),[m(1) m(2) m(3)+1]);\n icc = reshape(prod(m+1)+ns(1)+ns(2)+ns(3)+(1:prod(m)),m);\n % indices of fine grid nodes\n ns = prod(ones(length(mf),1)*mf+eye(length(mf)),2); %staggered\n inf = reshape(1:prod(mf+1),mf+1);\n is1f = reshape(prod(mf+1)+(1:ns(1)),[mf(1)+1 mf(2) mf(3)]);\n is2f = reshape(prod(mf+1)+ns(1)+ (1:ns(2)),[mf(1) mf(2)+1 mf(3)]);\n is3f = reshape(prod(mf+1)+ns(1)+ns(2)+(1:ns(3)),[mf(1) mf(2) mf(3)+1]);\n icf = reshape(prod(mf+1)+ns(1)+ns(2)+ns(3)+(1:prod(mf)),mf);\n \n % allocate space\n I = []; J = []; W = [];\n \n % include existing nodes (nodal-->nodal)\n ii = inf(1:2:end,1:2:end,1:2:end);\n jj = inc;\n ww = ones(size(jj));\n I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % include existing nodes (stg-1-->nodal)\n ii = inf(1:2:end,2:2:end,2:2:end);\n jj = is1c;\n ww = ones(size(jj));\n I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % include existing nodes (stg-2-->nodal)\n ii = inf(2:2:end,1:2:end,2:2:end);\n jj = is2c;\n ww = ones(size(jj));\n I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % include existing nodes (stg-3-->nodal)\n ii = inf(2:2:end,2:2:end,1:2:end);\n jj = is3c;\n ww = ones(size(jj));\n I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % include existing nodes (cc-->nodal)\n ii = inf(2:2:end,2:2:end,2:2:end);\n jj = icc;\n ww = ones(size(jj));\n I = [I; ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n \n % average to get edge-stg-1\n ii = inf(2:2:end,1:2:end,1:2:end);\n jj = [reshape(inc(1:end-1,:,:),[],1); reshape(inc(2:end,:,:),[],1)];\n ww = .5*ones(size(jj));\n I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % average to get edge-stg-2\n ii = inf(1:2:end,2:2:end,1:2:end);\n jj = [reshape(inc(:,1:end-1,:),[],1); reshape(inc(:,2:end,:),[],1)];\n ww = .5*ones(size(jj));\n I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % average to get edge-stg-3\n ii = inf(1:2:end,1:2:end,2:2:end);\n jj = [reshape(inc(:,:,1:end-1),[],1); reshape(inc(:,:,2:end),[],1)];\n ww = .5*ones(size(jj));\n I = [I; ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n \n % coarse --> fine(nodal only)\n P1 = sparse(I,J,W,prod(mf+1),icc(end));\n % allocate space\n I = []; J = []; W = [];\n \n % get face-stg-1\n ii = is1f;\n jj = [\n v(inf(1:end,1:end-1,1:end-1));\n v(inf(1:end,2:end ,1:end-1));\n v(inf(1:end,2:end ,2:end ));\n v(inf(1:end,1:end-1,2:end ));\n ];\n ww = .25*ones(size(jj));\n I = [I; ii(:);ii(:);ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % get face-stg-2\n ii = is2f;\n jj = [\n v(inf(1:end-1,1:end ,1:end-1));\n v(inf(2:end ,1:end ,1:end-1));\n v(inf(2:end ,1:end ,2:end ));\n v(inf(1:end-1,1:end ,2:end ));\n ];\n ww = .25*ones(size(jj));\n I = [I; ii(:);ii(:);ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n % get face-stg-3\n ii = is3f;\n jj = [\n v(inf(1:end-1,1:end-1,1:end));\n v(inf(2:end ,1:end-1,1:end));\n v(inf(2:end ,2:end ,1:end));\n v(inf(1:end-1,2:end ,1:end));\n ];\n ww = .25*ones(size(jj));\n I = [I; ii(:);ii(:);ii(:);ii(:)]; J = [J; jj(:)]; W = [W; ww(:)];\n \n \n % get new cell-centers\n ii = icf;\n jj = [\n v(inf(1:end-1,1:end-1,1:end-1));\n v(inf(2:end ,1:end-1,1:end-1));\n v(inf(2:end ,2:end ,1:end-1));\n v(inf(1:end-1,2:end ,1:end-1));\n v(inf(1:end-1,1:end-1,2:end));\n v(inf(2:end ,1:end-1,2:end));\n v(inf(2:end ,2:end ,2:end));\n v(inf(1:end-1,2:end ,2:end));\n ];\n ww = .125*ones(size(jj));\n I = [I; repmat(ii(:),[8,1])]; J = [J; jj(:)]; W = [W; ww(:)];\n \n P2 = sparse(I-prod(mf+1),J,W,ns(1)+ns(2)+ns(3)+prod(mf),prod(mf+1));\n \n P = [P1; P2*P1];\n end\n \n \n \n % ========== get methods ========================================\n function dx1 = get.dx1(this)\n if isempty(this.dx1_),\n [this.dx1_, this.dx2_, this.dx3_] = getGradientMatrixFEM(this,0);\n end\n dx1 = this.dx1_;\n end\n \n function dx2 = get.dx2(this)\n if isempty(this.dx2_),\n [this.dx1_, this.dx2_, this.dx3_] = getGradientMatrixFEM(this,0);\n end\n dx2 = this.dx2_;\n end\n \n function dx3 = get.dx3(this)\n if isempty(this.dx3_),\n [this.dx1_, this.dx2_, this.dx3_] = getGradientMatrixFEM(this,0);\n end\n dx3 = this.dx3_;\n end\n \n function GRAD = get.GRAD(this)\n if isempty(this.GRAD_),\n this.GRAD_ = [this.dx1;this.dx2;this.dx3];\n end\n GRAD = this.GRAD_;\n end\n function B = get.B(this)\n if isempty(this.B_),\n this.B_ = blkdiag(this.GRAD,this.GRAD,this.GRAD);\n end\n B = this.B_;\n end\n \n function P1 = get.P1(this)\n if isempty(this.P1_),\n A = speye(this.nnodes);\n this.P1_ = A(this.tri(:,1),:);\n end\n P1 = this.P1_;\n end\n function P2 = get.P2(this)\n if isempty(this.P2_),\n A = speye(this.nnodes);\n this.P2_ = A(this.tri(:,2),:);\n end\n P2 = this.P2_;\n end\n \n function P3 = get.P3(this)\n if isempty(this.P3_),\n A = speye(this.nnodes);\n this.P3_ = A(this.tri(:,3),:);\n end\n P3 = this.P3_;\n end\n \n function P4 = get.P4(this)\n if isempty(this.P4_),\n A = speye(this.nnodes);\n this.P4_ = A(this.tri(:,4),:);\n end\n P4 = this.P4_;\n end\n function PC = get.PC(this)\n if isempty(this.PC_),\n this.PC_ = (this.P1+this.P2+this.P3+this.P4)/4;\n end\n PC = this.PC_;\n end\n function P = get.P(this)\n if isempty(this.P_),\n this.P_ = this.getPuNodal(this.m);\n end\n P = this.P_;\n end\n function Pt = get.Pt(this)\n if isempty(this.Pt_),\n this.Pt_ = this.getPuNodal(this.m/2);\n end\n Pt = this.Pt_;\n end\n \n function mfdx1 = get.mfdx1(this)\n if isempty(this.mfdx1_),\n [this.mfdx1_, this.mfdx2_, this.mfdx3_] = getGradientMatrixFEM(this,1);\n end\n mfdx1 = this.mfdx1_;\n end\n \n function mfdx2 = get.mfdx2(this)\n if isempty(this.mfdx2_),\n [this.mfdx1_, this.mfdx2_, this.mfdx3_] = getGradientMatrixFEM(this,1);\n end\n mfdx2 = this.mfdx2_;\n end\n \n function mfdx3 = get.mfdx3(this)\n if isempty(this.mfdx3_),\n [this.mfdx1_, this.mfdx2_, this.mfdx3_] = getGradientMatrixFEM(this,1);\n end\n mfdx3 = this.mfdx3_;\n end\n \n function mfGRAD = get.mfGRAD(this)\n if isempty(this.mfGRAD_),\n this.mfGRAD_ = getGradientMatrixFEM(this,1);\n end\n mfGRAD = this.mfGRAD_;\n end\n \n function idx = get.boundaryIdx(this)\n if isempty(this.boundaryIdx_),\n mkvc = @(v) v(:);\n ns = prod(ones(length(this.m),1)*this.m+eye(length(this.m)),2); %staggered\n \n % nodal points\n id = reshape(1:prod(this.m+1),this.m+1);\n idx = [ ...\n mkvc(id([1,end],:,:));\n mkvc(id(:,[1,end],:));\n mkvc(id(:,:,[1,end]));\n ];\n % stg-1 points\n id = prod(this.m+1) + reshape(1:prod(this.m+[1,0,0]),this.m+[1,0,0]);\n idx = [idx; mkvc(id([1,end],:,:)) ];\n % stg-2 points\n id = prod(this.m+1) +ns(1) + reshape(1:prod(this.m+[0,1,0]),this.m+[0,1,0]);\n idx = [idx; mkvc(id(:,[1,end],:)) ];\n % stg-3 points\n id = prod(this.m+1) +ns(1) + ns(2) + reshape(1:prod(this.m+[0,0,1]),this.m+[0,0,1]);\n idx = [idx; mkvc(id(:,:,[1,end])) ];\n \n this.boundaryIdx_ = unique( idx);\n end\n idx = this.boundaryIdx_;\n end\n \n function idx = get.boundaryProj(this)\n if isempty(this.boundaryProj_),\n idx = this.boundaryIdx;\n \n P = speye(size(this.xn,1));\n P = P(idx,:);\n P = kron(speye(3),P);\n \n this.boundaryProj_ = P;\n end\n idx = this.boundaryProj_;\n end \n \n end\nend\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/add-ons/FAIRFEM/meshes/TetraMesh1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6298618950709688}} {"text": "function [sigma,u,AD] = HodgeLaplacianE(node,elem,pde,bdFlag,option)\n%% HODEGELAPLACIANE Hodge Laplacian of edge element\n\n\nif ~exist('option','var'), option = []; end\nif ~exist('bdFlag','var'), bdFlag = []; end\n\n%% Data structure\n% elemold = elem;\n[elem,bdFlag] = sortelem(elem,bdFlag); % ascend ordering\n[elem2edge,edge] = dofedge(elem);\n[Dlambda,area,elemSign] = gradbasis(node,elem);\nlocEdge = [2 3; 1 3; 1 2];\nN = size(node,1); NT = size(elem,1); NE = size(edge,1);\nNsigma = N; Nu = NE; Ndof = Nsigma + Nu;\n\n%% Assemble matrix \n% Mass matrices\nMv = accumarray([elem(:,1);elem(:,2);elem(:,3)],[area;area;area]/3,[N,1]);\nMv = spdiags(Mv,0,N,N);\nMe = getmassmatvec(elem2edge,area,Dlambda,'ND1');\nMt = spdiags(1./area,0,NT,NT);\n% G. gradient operator: P1 -> (ND1)'\nG = Me*icdmat(double(edge),[-1 1]); % gradient matrix\n% R. rotation operator\nR = icdmat(double(elem2edge),[1 -1 1]);\nC = R'*Mt*R;\nA = [-Mv G'; G C];\n\n%% Assemble right hand side\nf = zeros(Ndof,1);\nif ~isfield(pde,'f') || (isfield(pde,'f') && isreal(pde.f) && all(pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order is 3\nend\nif isfield(pde,'f') && ~isempty(pde.f)\n [lambda,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n bt = zeros(NT,3);\n for p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:);\n fp = pde.f(pxy);\n for k = 1:3\n i = locEdge(k,1); j = locEdge(k,2);\n % phi_k = lambda_iDlambda_j - lambda_jDlambda_i;\n phi_k = lambda(p,i)*Dlambda(:,:,j)-lambda(p,j)*Dlambda(:,:,i);\n rhs = dot(phi_k,fp,2);\n bt(:,k) = bt(:,k) + w(p)*rhs;\n end\n end\n bt = bt.*repmat(area,1,3);\n f = accumarray(N+elem2edge(:),bt(:),[Ndof 1]);\nend\nclear pxy fp bt rhs phi_k Dlambda\n\n%% Boundary Conditions\n[AD,f,u,sigma,freeDof,isPureNeumann] = getbdHodgeLapE(f);\n\n%% Solve the linear system\ntemp = zeros(Ndof,1);\ntemp(freeDof) = A(freeDof,freeDof)\\f(freeDof);\nsigma(freeNode) = temp(freeNode);\nu(freeEdge) = temp(freeEdge+N);\n\nif isPureNeumann\n u = u - mean(u); % normalize u \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdHodgeLapE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,f,u,sigma,freeDof,isPureNeumann] = getbdHodgeLapE(f)\n\n u = zeros(NE,1); sigma = zeros(N,1); \n % Find boundary edges: Neumann\n isNeumann(elem2edge(bdFlag(:)==2)) = true;\n Neumann = edge(isNeumann,:); \n % Neumann boundary condition: modify nodal dof values\n if isnumeric(pde.gun) && all(pde.gun == 0)\n pde.gun = [];\n end\n if ~isempty(Neumann) && ~isempty(pde.gun)\n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 2; % default order exact for linear gN\n end\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n phigN = lambdagN; % linear bases\n nQuadgN = size(lambdagN,1);\n ge = zeros(size(Neumann,1),2);\n for pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNp = pde.gun(ppxy);\n for igN = 1:2\n ge(:,igN) = ge(:,igN) + weightgN(pp)*phigN(pp,igN)*gNp;\n end\n end\n ge = ge.*repmat(el,1,2);\n f = f + accumarray(Neumann(:), ge(:),[Ndof,1]); \n end\n % Neumann boundary condition: modify edge dof values\n edgeSign = ones(NE,1);\n idx = (bdFlag(:,1) ~= 0) & (elemSign == -1);% first edge is on boundary\n edgeSign(elem2edge(idx,1)) = -1;\n idx = (bdFlag(:,2) ~= 0) & (elemSign == 1); % second edge is on boundary\n edgeSign(elem2edge(idx,2)) = -1;\n idx = (bdFlag(:,3) ~= 0) & (elemSign == -1);% first edge is on boundary\n edgeSign(elem2edge(idx,3)) = -1;\n if isnumeric(pde.grotu) && all(pde.grotu==0)\n pde.grotu = [];\n end\n if ~isempty(pde.grotu) && ~isempty(Neumann)\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 2; % default order exact for linear gN\n end\n [lambda,weight] = quadpts1(option.gNquadorder);\n nQuad = size(lambda,1);\n Neumannidx = find(isNeumann) + N;\n for ip = 1:nQuad\n \tpxy = lambda(ip,1)*node(Neumann(:,1),:)+...\n lambda(ip,2)*node(Neumann(:,2),:); \n f(Neumannidx) = f(Neumannidx) + weight(ip)*pde.grotu(pxy);\n end\n f(Neumannidx) = f(Neumannidx).*edgeSign(isNeumann);\n % no edge length since the basis of edge element contains it.\n end\n \n % Find Dirichlet boundary nodes and edges\n isDirichlet = false(NE,1);\n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n Dirichlet = edge(isDirichlet,:);\n isfixedNode = false(N,1); \n isfixedNode(Dirichlet(:)) = true;\n fixedNode = find(isfixedNode);\n fixedDof = [fixedNode; N + find(isDirichlet)];\n freeNode = find(~isfixedNode);\n freeEdge = find(~isDirichlet);\n freeDof = [freeNode; N + freeEdge];\n isPureNeumann = false;\n if isempty(fixedNode) % pure Neumann boundary condition\n isPureNeumann = true;\n fixedDof = Ndof;\n freeDof = (1:Ndof-1)'; % eliminate the kernel\n end\n \n % Modify right hand side to include Dirichlet boundary condition\n if isnumeric(pde.gu) && all(pde.gu == 0) % zero gu\n pde.gu = [];\n end\n if isnumeric(pde.gsigma) && all(pde.gsigma == 0) % zero gsigma\n pde.gsigma = [];\n end\n if ~isPureNeumann && ~isempty(fixedNode) && (~isempty(pde.gu) || ~isempty(pde.gsigma))\n sigma = zeros(N,1);\n sigma(fixedNode) = pde.gsigma(node(fixedNode,:));\n u = zeros(NE,1);\n u(isDirichlet) = edgeinterpolate(pde.gu,node,Dirichlet);\n f = f - A*[sigma; u];\n f(fixedDof) = [sigma(fixedNode); u(isDirichlet)]; \n end\n \n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % AD(fixedNode,fixedNode)=I, AD(fixedNode,freeNode)=0, AD(freeNode,fixedNode)=0.\n if ~isempty(fixedDof)\n bdidx = zeros(Ndof,1); \n bdidx(fixedDof) = 1;\n Tbd = spdiags(bdidx,0,Ndof,Ndof);\n T = spdiags(1-bdidx,0,Ndof,Ndof);\n AD = T*A*T + Tbd;\n else\n AD = A;\n end \n \n % Pure Neumann boundary condition\n if isPureNeumann\n f(N+1:Ndof) = f(N+1:Ndof) - mean(f(N+1:Ndof)); % compatilbe condition: sum(b) = 0\n end\n end\nend\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/HodgeLaplacianE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6298618950245527}} {"text": "function [U,XI,YI] = takeo_asap(V,F,b,bc)\n % TAKEO_ASAP Solve \"As-Similar-As-Possible\" according to \"As-Rigid-As-Possible\n % Shape Manipulation\" by Igarashi et al., this is their \"First Step\". This is\n % equivalent up to factor of 2.5 to lscm\n %\n % U = takeo_arap(V,F,b,bc)\n %\n % Inputs:\n % V #V by 2 list of rest domain positions\n % F #F by 3 list of triangle indices into V\n % b #b list of indices of constraint (boundary) vertices\n % bc #b by 2 list of constraint positions for b\n % Outputs:\n % U #V by 2 list of new positions\n % X1 #F*3 by 1 list of coefficents, so that V(I,:) can be described in\n % terms of V(J,:) and V(K,:), where I,J,K are the indices of each\n % triangle\n % Y1 #F*3 by 1 list of coefficents, see above\n %\n % Note about X1,Y1:\n % V(I,:) = \n % (V(J,:) + [XI XI].* (V(K,:) - V(J,:)) + [YI -YI].* fliplr(V(K,:)-V(J,:)))\n %\n % See also: arap, takeo_arap, lscm\n %\n\n\n % We will build the quadratic system matrix per triangle\n % First we need for each triangle to write each vertex in terms of the other\n % two vertices.\n\n [XI,YI] = relative_coordinates(V,F);\n % reshape coordinate into single tall column\n XI = reshape(XI,size(F,1)*3,1);\n YI = reshape(YI,size(F,1)*3,1);\n\n % number of vertices\n n = size(V,1);\n % only works in 2D\n assert(size(V,2) == 2)\n % number of triangles\n nt = size(F,1);\n \n\n % Indices of each triangle vertex, I, and its corresponding two neighbors, J\n % and K\n I = [F(:,1);F(:,2);F(:,3)];\n J = [F(:,2);F(:,3);F(:,1)];\n K = [F(:,3);F(:,1);F(:,2)];\n % rename indices to so that I1 and I2 and so on index into vertex positions\n % as single column. Namely V(I,1) = V(I1) and V(I,2) = V(I2) etc.\n I1 = I;\n I2 = I+n;\n J1 = J;\n J2 = J+n;\n K1 = K;\n K2 = K+n;\n\n % Construct quadratic system matrix each triplet from II,JJ,VV contains an\n % set of elements per vertex per triangle in the quadratic energy summation\n II = [ ...\n J1\n J2\n J1\n K1\n J1\n K2\n J2\n K1\n J2\n K2\n K1\n K2\n I1\n J1\n I1\n J2\n I2\n J1\n I2\n J2\n I1\n I2\n I1\n K1\n I1\n K2\n I2\n K1\n I2\n K2\n ];\n JJ = [\n J1\n J2\n K1\n J1\n K2\n J1\n K1\n J2\n K2\n J2\n K1\n K2\n J1\n I1\n J2\n I1\n J1\n I2\n J2\n I2\n I1\n I2\n K1\n I1\n K2\n I1\n K1\n I2\n K2\n I2\n ];\n VV = [ ...\n (1-2*XI+XI.^2+YI.^2)\n (1-2*XI+XI.^2+YI.^2)\n (XI-XI.^2-YI.^2)\n (XI-XI.^2-YI.^2)\n (YI)\n (YI)\n (-YI)\n (-YI)\n (XI-XI.^2-YI.^2)\n (XI-XI.^2-YI.^2)\n (XI.^2+YI.^2)\n (XI.^2+YI.^2)\n (-1+XI)\n (-1+XI)\n (YI)\n (YI)\n (-YI)\n (-YI)\n (-1+XI)\n (-1+XI)\n ones(nt*3,1)\n ones(nt*3,1)\n (-XI)\n (-XI)\n (-YI)\n (-YI)\n (YI)\n (YI)\n (-XI)\n (-XI)\n ];\n % Assembly matrix\n A = sparse(II,JJ,VV,2*n,2*n);\n\n % solve\n U = min_quad_with_fixed(A,zeros(2*n,1),[b b+n],bc(:));\n % reshape into columns\n U = reshape(U,n,2);\n\nend \n\n%E = ...\n% sum(sum(((U(J,:) + [XI XI].* (U(K,:) - U(J,:)) + [YI -YI].* fliplr(U(K,:)-U(J,:))) - U(I,:)).^2,2));\n% E\n%\n%\n%E = ...\n% sum( ...\n% (U(J,1) + XI.* U(K,1) - XI.*U(J,1) + YI.* U(K,2) - YI.*U(J,2) - U(I,1)).^2 + ...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n%\n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% 2.*XI.*U(J,1).*U(K,1) - 2.*XI.*U(J,1).^2 + 2.*YI.*U(J,1).*U(K,2) - 2.*YI.*U(J,1).*U(J,2) - 2.*U(J,1).*U(I,1) + ...\n% (XI.* U(K,1) - XI.*U(J,1) + YI.* U(K,2) - YI.*U(J,2) - U(I,1)).^2 + ...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n% \n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% 2.*XI.*U(J,1).*U(K,1) - 2.*XI.*U(J,1).^2 + 2.*YI.*U(J,1).*U(K,2) - 2.*YI.*U(J,1).*U(J,2) - 2.*U(J,1).*U(I,1) + ...\n% XI.^2.*U(K,1).^2 + ...\n% -2.*XI.^2.*U(J,1).*U(K,1) + 2.*XI.*YI.*U(K,1).*U(K,2) - 2.*XI.*YI.*U(K,1).*U(J,2) - 2.*XI.*U(K,1).*U(I,1) + ...\n% (- XI.*U(J,1) + YI.* U(K,2) - YI.*U(J,2) - U(I,1)).^2 + ...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n% \n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% 2.*XI.*U(J,1).*U(K,1) - 2.*XI.*U(J,1).^2 + 2.*YI.*U(J,1).*U(K,2) - 2.*YI.*U(J,1).*U(J,2) - 2.*U(J,1).*U(I,1) + ...\n% XI.^2.*U(K,1).^2 + ...\n% -2.*XI.^2.*U(J,1).*U(K,1) + 2.*XI.*YI.*U(K,1).*U(K,2) - 2.*XI.*YI.*U(K,1).*U(J,2) - 2.*XI.*U(K,1).*U(I,1) + ...\n% XI.^2.*U(J,1).^2 + ...\n% -2.*XI.*U(J,1).*YI.* U(K,2) + 2.*XI.*U(J,1).*YI.*U(J,2) + 2.*XI.*U(J,1).*U(I,1) + ...\n% (YI.* U(K,2) - YI.*U(J,2) - U(I,1)).^2 + ...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n% \n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% 2.*XI.*U(J,1).*U(K,1) - 2.*XI.*U(J,1).^2 + 2.*YI.*U(J,1).*U(K,2) - 2.*YI.*U(J,1).*U(J,2) - 2.*U(J,1).*U(I,1) + ...\n% XI.^2.*U(K,1).^2 + ...\n% -2.*XI.^2.*U(J,1).*U(K,1) + 2.*XI.*YI.*U(K,1).*U(K,2) - 2.*XI.*YI.*U(K,1).*U(J,2) - 2.*XI.*U(K,1).*U(I,1) + ...\n% XI.^2.*U(J,1).^2 + ...\n% -2.*XI.*U(J,1).*YI.* U(K,2) + 2.*XI.*U(J,1).*YI.*U(J,2) + 2.*XI.*U(J,1).*U(I,1) + ...\n% YI.^2.*U(K,2).^2 + ...\n% - 2.*YI.^2.*U(J,2).*U(K,2) - 2.*YI.*U(I,1).*U(K,2) + ...\n% (- YI.*U(J,2) - U(I,1)).^2 + ...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n% \n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% 2.*XI.*U(J,1).*U(K,1) - 2.*XI.*U(J,1).^2 + 2.*YI.*U(J,1).*U(K,2) - 2.*YI.*U(J,1).*U(J,2) - 2.*U(J,1).*U(I,1) + ...\n% XI.^2.*U(K,1).^2 + ...\n% -2.*XI.^2.*U(J,1).*U(K,1) + 2.*XI.*YI.*U(K,1).*U(K,2) - 2.*XI.*YI.*U(K,1).*U(J,2) - 2.*XI.*U(K,1).*U(I,1) + ...\n% XI.^2.*U(J,1).^2 + ...\n% -2.*XI.*U(J,1).*YI.* U(K,2) + 2.*XI.*U(J,1).*YI.*U(J,2) + 2.*XI.*U(J,1).*U(I,1) + ...\n% YI.^2.*U(K,2).^2 + ...\n% - 2.*YI.^2.*U(J,2).*U(K,2) - 2.*YI.*U(I,1).*U(K,2) + ...\n% YI.^2.*U(J,2).^2 + ...\n% + 2.*YI.*U(I,1).*U(J,2) + ...\n% U(I,1).^2+...\n% (U(J,2) + XI.* U(K,2) - XI.*U(J,2) - YI.* U(K,1) + YI.*U(J,1) - U(I,2)).^2 ...\n% );\n% \n%E = ...\n% sum( ...\n% U(J,1).^2 + ...\n% - 2.*XI.*U(J,1).^2 + ...\n% XI.^2.*U(J,1).^2 + ...\n% YI.^2.*U(J,1).^2 + ...\n% ...\n% U(J,2).^2 + ...\n% YI.^2.*U(J,2).^2 + ...\n% - 2.*XI.*U(J,2).^2 + ...\n% XI.^2.*U(J,2).^2 + ...\n% ...\n% - 2.*YI.*U(J,1).*U(J,2) +...\n% 2.*XI.*YI.*U(J,1).*U(J,2) + ...\n% 2.*YI.*U(J,1).*U(J,2) + ...\n% - 2.*XI.*YI.*U(J,1).*U(J,2) + ...\n% ...\n% 2.*XI.*U(J,1).*U(K,1) + ...\n% -2.*XI.^2.*U(J,1).*U(K,1) + ...\n% - 2.*YI.^2.*U(J,1).*U(K,1) + ...\n% ...\n% 2.*YI.*U(J,1).*U(K,2) + ...\n% -2.*XI.*YI.*U(J,1).* U(K,2) + ...\n% 2.*XI.*YI.*U(J,1).*U(K,2) + ...\n% ...\n% - 2.*XI.*YI.*U(J,2).*U(K,1) + ...\n% - 2.*YI.*U(J,2).*U(K,1) + ...\n% 2.*XI.*U(J,2).*YI.* U(K,1) + ...\n% ...\n% - 2.*YI.^2.*U(J,2).*U(K,2) + ...\n% 2.*XI.*U(J,2).*U(K,2) + ...\n% -2.*XI.^2.*U(J,2).*U(K,2) + ...\n% ...\n% - 2.*U(I,1).*U(J,1) + ...\n% 2.*XI.*U(I,1).*U(J,1) + ...\n% - 2.*YI.*U(I,2).*U(J,1) + ...\n% ...\n% 2.*YI.*U(I,1).*U(J,2) + ...\n% ...\n% - 2.*U(I,2).*U(J,2) + ...\n% 2.*XI.*U(I,2).*U(J,2) + ...\n% ...\n% XI.^2.*U(K,1).^2 + ...\n% YI.^2.*U(K,1).^2 + ...\n% ...\n% YI.^2.*U(K,2).^2 + ...\n% XI.^2.*U(K,2).^2 + ...\n% ...\n% U(I,1).^2+...\n% ...\n% U(I,2).^2 + ...\n% ...\n% 2.*XI.*YI.*U(K,1).*U(K,2) + ...\n% - 2.*XI.*YI.*U(K,1).*U(K,2) + ...\n% ...\n% - 2.*XI.*U(I,1).*U(K,1) + ...\n% ...\n% - 2.*YI.*U(I,1).*U(K,2) + ...\n% ...\n% 2.*YI.*U(I,2).*U(K,1) + ...\n% ...\n% - 2.*XI.*U(I,2).*U(K,2) + ...\n% 0 ...\n% );\n%\n%\n%E = ...\n% sum( ...\n% (1-2*XI+XI.^2+YI.^2).*U(J,1).^2 + ...\n% ...\n% (1-2*XI+XI.^2+YI.^2).*U(J,2).^2 + ...\n% ...\n% (2*XI-2*XI.^2-2*YI.^2).*U(J,1).*U(K,1) + ...\n% ...\n% (2.*YI).*U(J,1).*U(K,2) + ...\n% ...\n% (-2*YI).*U(J,2).*U(K,1) + ...\n% ...\n% (2*XI-2*XI.^2-2*YI.^2).*U(J,2).*U(K,2) + ...\n% ...\n% (-2+2*XI).*U(I,1).*U(J,1) + ...\n% ...\n% (2.*YI).*U(I,1).*U(J,2) + ...\n% ...\n% (-2*YI).*U(I,2).*U(J,1) + ...\n% ...\n% (-2+2*XI).*U(I,2).*U(J,2) + ...\n% ...\n% (XI.^2+YI.^2).*U(K,1).^2 + ...\n% ...\n% (XI.^2+YI.^2).*U(K,2).^2 + ...\n% ...\n% (1).*U(I,1).^2+...\n% ...\n% (1).*U(I,2).^2 + ...\n% ...\n% (-2*XI).*U(I,1).*U(K,1) + ...\n% ...\n% (-2*YI).*U(I,1).*U(K,2) + ...\n% ...\n% (2*YI).*U(I,2).*U(K,1) + ...\n% ...\n% (-2*XI).*U(I,2).*U(K,2) + ...\n% 0 ...\n% );\n%\n%E = ...\n% sum( ...\n% (1-2*XI+XI.^2+YI.^2).*U(J,1).^2 + ...\n% ...\n% (1-2*XI+XI.^2+YI.^2).*U(J,2).^2 + ...\n% ...\n% 2*(XI-XI.^2-YI.^2).*U(J,1).*U(K,1) + ...\n% ...\n% 2*(YI).*U(J,1).*U(K,2) + ...\n% ...\n% 2*(-YI).*U(J,2).*U(K,1) + ...\n% ...\n% (2*XI-2*XI.^2-2*YI.^2).*U(J,2).*U(K,2) + ...\n% ...\n% 2*(-1+XI).*U(I,1).*U(J,1) + ...\n% ...\n% 2*(YI).*U(I,1).*U(J,2) + ...\n% ...\n% 2*(-YI).*U(I,2).*U(J,1) + ...\n% ...\n% 2*(-1+XI).*U(I,2).*U(J,2) + ...\n% ...\n% (XI.^2+YI.^2).*U(K,1).^2 + ...\n% ...\n% (XI.^2+YI.^2).*U(K,2).^2 + ...\n% ...\n% (1).*U(I,1).^2+...\n% ...\n% (1).*U(I,2).^2 + ...\n% ...\n% 2*(-XI).*U(I,1).*U(K,1) + ...\n% ...\n% 2*(-YI).*U(I,1).*U(K,2) + ...\n% ...\n% 2*(YI).*U(I,2).*U(K,1) + ...\n% ...\n% 2*(-XI).*U(I,2).*U(K,2) + ...\n% 0 ...\n% );\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/takeo_asap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6298618898718691}} {"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% Calibrating kl, and ku for a sabr model for Kienitz extrapolation\n% the prices are calculated from known sabr parameters\n\nf = 0.03; t =1; % forward and time\na = 0.25; b = 0.5; r = -.5; n = 0.2; % sabr parameters\nmu = 1.5; nu = 3; % tail decay\n\nk = 0.001:0.0001:1; % strike range\n\ncall = sprice(a, b, r, n, f, k, t,1); % call prices (standard sabr)\nput = sprice(a, b, r, n, f, k, t,0); % put prices (standard sabr)\nput(1) = 0;\ncall(1) = f; % assures forward is matched\n\nNparam = 2; % number of calibrated params\n\n% objective function\nof = @(x) of_sabr(a, b, r, n, f, k, t, mu, nu, x(1), x(2), call, put);\n\nx0 = [.25*f; 25.5*f]; % starting values \n\nA = zeros(Nparam,Nparam); bc= zeros(Nparam,1);\nAeq = A; beq = bc;\nlb = [.25*f; f]; % lower bound\nub = [f; 30*f]; % upper bound\n\ny = fmincon(of,x0,A,bc,Aeq,beq,lb,ub); % optimization\n\n% verification of results\nxval = 0:0.001:.25; % x-values\n[cl, bl, al, cu, bu, au] = ...\n psabr_param_3(a, b, r, n, f, t,mu,nu,y(1),y(2));\nyval = psabr_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n mu, cl, bl,al, nu, cu,bu,au);% y-values calculated\n\nplot(xval,yval); % plot the results\nFactor = 1000000; % used for plotting\n\nyval_call = sprice_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n mu, cl, bl,al, nu, cu,bu,au, 1); % SABR Call prices\nfigure; hold on; \n plot(xval,Factor*yval_call,'r'); \n plot(k,Factor*call,'g'); \nhold off;\n\nyval_put = sprice_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n mu, cl, bl,al, nu, cu,bu,au, 0); % SABR Put prices\nfigure; hold on; \n plot(xval,Factor*yval_put,'r'); \n plot(k,Factor*put,'g'); \nhold off;\n\nfval = sprice_5(a, b, r, n, f, 0, t, y(1), y(2), ...\n mu, cl, bl,al, nu, cu,bu,au, 1); % calculate forward value\ny % calibrated values\nf - fval % display difference to forward\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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/Cal_sabr_dens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6298618797521672}} {"text": "function [Bt]=GetCoriolisMatrix1(T,Pcii,Icii,mcii,dq)\n%% About the function: this is a function that is used to calculate\n% Coriolis matrix of the serially linked manipulator, the return value of\n% the function is (nxn) Coriolis matrix.\n\n\n%% Arreguemnts:\n% T is (4x4xn) transformation matrix of the serially linked robot, each\n% (4x4) matrix represents the transform for each link in the base frame. \n% Pcii is 3Xn matrix while each column represents the local coordinates\n% of the center of mass of each link.\n% Icii is (3x3xn) matrix, each 3x3 matrix of which represnets the\n% associated link inertial tensor represented in its local inertial frame\n% mcii is (1xn) vector, each element of which specifies a mass of one of\n% the links\n\n\n% Copyright Mohammad SAFEEA\n\nn=max(size(mcii));\n%% Initialization of Ai and Bi.\nBi=zeros(3,n,n);\nDi=zeros(3,n,n);\nL=zeros(3,3);\nLj_1=zeros(3,1);\nwj=zeros(3,n);\nhalf_wj=zeros(3,n);\n%% Calculate === some auxuliary variables\nPcii_A=zeros(3,n);\nw=zeros(3,n);\nvci=zeros(3,n);\nvi=zeros(3,n);\nmcii_Pcii_A=zeros(3,n);\nPcii_A(:,1)=T(1:3,1:3,1)*Pcii(:,1);\nw(:,1)=T(1:3,3,1)*dq(1);\nwj(:,1)=w(:,1);\nhalf_wj(:,1)=0.5*wj(:,1);\nmcii_Pcii_A(:,1)=mcii(1)*Pcii_A(:,1);\ndouble_kj=zeros(3,n);\ndouble_kj(:,1)=2*T(1:3,3,1);\nfor i=2:n\n Pcii_A(:,i)=T(1:3,1:3,i)*Pcii(:,i);\n wj(:,i)=T(1:3,3,i)*dq(i);\n half_wj(:,i)=0.5*wj(:,i);\n w(:,i)=w(:,i-1)+wj(:,i);\n double_kj(:,i)=2*T(1:3,3,i);\n mcii_Pcii_A(:,i)=mcii(i)*Pcii_A(:,i);\nend\n%% calculating the links model, Mci and ddPci\nfor i=1:n\n %% calculating the Mci term\n Pci=Pcii_A(:,i)+T(1:3,4,i);\n L=T(1:3,1:3,i)*(trace(Icii(:,:,i))*eye(3)-2*Icii(:,:,i))*T(1:3,1:3,i)';\n Lj_1=L*T(1:3,3,i);\n for j=i:-1:2\n Bi(:,j,i)=Bi(:,j,i)+cross(Lj_1,half_wj(:,j));\n Lj_1=L*T(1:3,3,j-1);\n Bi(:,j-1,i)=Bi(:,j-1,i)+cross(Lj_1,w(:,i)-w(:,j-1)); \n end\n j=1;\n %Bi(:,j,i)=Bi(:,j,i)+0.5*cross(Lj_1,wj(:,j)); \n Bi(:,j,i)=Bi(:,j,i)+cross(Lj_1,half_wj(:,j)); \n %% calculating the ddPci term\n vr=zeros(3,1);\n for j=i:-1:2\n Pcij=Pci-T(1:3,4,j);\n %Di(:,j,i)=Di(:,j,i)+(dq(j))*cross(T(1:3,3,j),cross(T(1:3,3,j),Pcij\n %));\n Di(:,j,i)=Di(:,j,i)+(dq(j))*(T(1:3,3,j)*(T(1:3,3,j)'*Pcij)-Pcij);\n vr=vr+cross(wj(:,j),Pcij);\n Di(:,j-1,i)=Di(:,j-1,i)+cross(double_kj(:,j-1),vr);\n end\n j=1;\n Pcij=Pci-T(1:3,4,j);\n Di(:,j,i)=Di(:,j,i)+(dq(j))*(T(1:3,3,j)*(T(1:3,3,j)'*Pcij)-Pcij);\nend\nBt=zeros(n,n);\nFac_D=zeros(3,n);\nMac_B=zeros(3,n);\nPjp1_j=zeros(3,1);\n%% calculating Mac for all of the links, then calculating two by filling At\n%% and Bt\n\nstart=n-1;\nj=n;\n%% recursive rprocedure on moments and forces\n for k=1:n %% iterate through the matrix\n Mac_B(:,k)=Bi(:,k,j)+cross(mcii_Pcii_A(:,j),Di(:,k,j)); \n end\n %% on forces\n Fac_D=mcii(j)*Di(:,:,j); \n Bt(j,:)=T(1:3,3,j)'*Mac_B;\n \nfor j=start:-1:1 %% iterate through the joints\n Pjp1_j=T(1:3,4,j+1)-T(1:3,4,j);\n %% recursive rprocedure on moments and forces\n for k=1:j %% iterate through the matrix\n Mac_B(:,k)=Mac_B(:,k)+Bi(:,k,j)+cross(Pjp1_j,Fac_D(:,k))+cross(mcii_Pcii_A(:,j),Di(:,k,j)); \n end\n for k=j+1:n\n Mac_B(:,k)=Mac_B(:,k)+cross(Pjp1_j,Fac_D(:,k));\n end\n %% on forces\n Fac_D(:,1:j)=Fac_D(:,1:j)+mcii(j)*Di(:,1:j,j); \n Bt(j,:)=T(1:3,3,j)'*Mac_B;\n \nend\n%% close the function\nend\n\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/GetCoriolisMatrix1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6298618797521671}} {"text": "function [X,err,iter] = lrtcR_snn(M,omega,alpha,opts)\n\n% Solve the Noisy Low-Rank Tensor Completion (LRTC) based on Sum of Nuclear Norm (SNN) problem by M-ADMM\n%\n% min_{X,E} \\sum_i \\alpha_i*||X_{i(i)}||_* + loss(E),\n% s.t. P_Omega(X) + E = M.\n% loss(E) = ||E||_1 or 0.5*||E||_F^2\n%\n% ---------------------------------------------\n% Input:\n% M - d1*d2*...dk tensor\n% omega - index of the observed entries\n% alpha - k*1 vector, parameters\n% opts - Structure value in Matlab. The fields are\n% opts.loss - 'l1' (default): loss(E) = ||E||_1 \n% 'l2': loss(E) = 0.5*||E||_F^2\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% X - d1*d2*...*dk tensor\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 24/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\nloss = 'l1';\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'loss'); loss = opts.loss; end\nif isfield(opts, 'tol'); tol = opts.tol; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\ndim = size(M);\nk = length(dim);\n\nomegac = setdiff(1:prod(dim),omega);\n\nX = zeros(dim);\nY = cell(k,1);\nZ = Y;\nE = X;\nY2 = E;\nfor i = 1 : k\n Y{i} = X;\n Z{i} = X;\nend\n\niter = 0;\nfor iter = 1 : max_iter\n Xk = X;\n Ek = E;\n Zk = Z;\n % first super block {Z_i,E}\n sumtemp = zeros(dim);\n for i = 1 : k\n Z{i} = Fold(prox_nuclear(Unfold(X+Y{i}/mu,dim,i), alpha(i)/mu),dim,i);\n sumtemp = sumtemp + Z{i} - Y{i}/mu;\n end \n if strcmp(loss,'l1')\n E = prox_l1(-X+M-Y2/mu,1/mu);\n elseif strcmp(loss,'l2')\n E = (-X+M-Y2/mu)*(mu/(1+mu));\n else\n error('not supported loss function');\n end\n % second super block {X}\n X(omega) = (sumtemp(omega)-Y2(omega)/mu-E(omega)+M(omega))/(k+1);\n X(omegac) = sumtemp(omegac)/k;\n \n chg = max([max(abs(Xk(:)-X(:))), max(abs(Ek(:)-E(:))) ]);\n err = 0;\n for i = 1 : k\n dY = X-Z{i};\n err = err+norm(dY(:))^2;\n Y{i} = Y{i}+mu*dY;\n chg = max([chg,max(abs(dY(:))), max(abs((Zk{i}(:)-Z{i}(:))))]);\n end\n dY = E-M; \n dY(omega) = dY(omega)+X(omega);\n chg = max(chg,max(abs(dY(:))));\n Y2 = Y2 + mu*dY;\n err = sqrt(err+norm(dY(:))^2);\n\n if DEBUG\n if iter == 1 || mod(iter, 10) == 0\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', err=' num2str(chg)]); \n end\n end\n if chg < tol\n break;\n end \n mu = min(rho*mu,max_mu); \nend\n ", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/lrtcR_snn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6298618797057509}} {"text": "function [tt]=tt_qshift_p(d,m)\n\n% for integer m\n% returns the periodic downward m-position shift matrix of size 2^d x 2^d\n% in the QTT format\n% The shift is (-m)-position upward for m < 0\n% m=0 corresponds to the identity matrix\n% m=2^d corresponds to the identity matrix\n% m=-2^d corresponds to the identity matrix\n%\n% January 28, 2011\n% Vladimir Kazeev\n% vladimir.kazeev@gmail.com\n% INM RAS\n% Moscow, Russia\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% For details please see the preprint\n% http://www.mis.mpg.de/publications/preprints/2011/prepr2011-36.html\n% Vladimir A. Kazeev, Boris N. Khoromskij and Eugene E. Tyrtyshnikov\n% Multilevel Toeplitz matrices generated by QTT tensor-structured vectors and convolution with logarithmic complexity\n% January 12, 2012\n% Vladimir Kazeev,\n% Seminar for Applied Mathematics, ETH Zurich\n% vladimir.kazeev@sam.math.ethz.ch\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nI=eye(2);\nJ=[0,1;0,0];\nO=zeros(2);\nP=J+J';\n\nm=mod(m,2^d);\nm=dec2bin(m,d);\n\ntt=cell(d,1);\n\nif (m(1) == '1')\n\ttt{1}=[P,I];\nelse\n\ttt{1}=[I,P];\nend\ntt{1}=reshape(tt{1},[2,2,2]);\n\nfor k=2:d-1\n\tif (m(k) == '1')\n\t\ttt{k}=[J',O;J,I];\n\telse\n\t\ttt{k}=[I,J';O,J];\n\tend\n\ttt{k}=permute(reshape(tt{k},[2,2,2,2]),[1,3,2,4]);\nend\n\nif (m(d) == '1')\n\ttt{d}=[J',J];\nelse\n\ttt{d}=[I,O];\nend\ntt{d}=reshape(tt{d},[2,2,2]);\n\ntt=tt_reverse(tt,2);\n\nreturn\nend", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/core/tt_qshift_p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6298618695860485}} {"text": "%% kronecker\n% http://www.mathworks.com/matlabcentral/fileexchange/24499-kronecker\n%\nfunction K = kronecker(A,B)\n%KRONECKER Kronecker tensor product.\n% KRONECKER(X,Y) is the Kronecker tensor product of X and Y.\n% The result is a large matrix formed by taking all possible\n% products between the elements of X and those of Y. For\n% example, if X is 2 by 3, then KRONECKER(X,Y) is\n%\n% [ X(1,1)*Y X(1,2)*Y X(1,3)*Y\n% X(2,1)*Y X(2,2)*Y X(2,3)*Y ]\n%\n% If either X or Y is sparse, only nonzero elements are multiplied\n% in the computation, and the result is sparse.\n%\n% Class support for inputs X,Y:\n% float: double, single\n%\n% NOTE: This function does exactly what Matlab KRON does, but for large\n% full matrices, the engine uses BSXFUN to accelerate the calculation. \n% Another advantage is no intermediates large matrices is generated\n% (four temporary arrays in case of KRON)\n%\n% Benchmark on Intel Core2 Duo T7250 @2GHz and 2Go RAM\n% Size A/B Speed gain\n% 10 1.17 \n% 20 3.48 \n% 30 3.78 \n% 40 3.73 \n% 50 3.68 \n% 60 4.22 \n% 70 3.81\n%\n% Restriction: MATLAB 2007A or later is required\n%\n% See also: KRON\n%\n% Author: Bruno Luong \n% History:\n% Original 21-Jun-2009\n\n\n\nif ~issparse(A) && ~issparse(B)\n if ndims(A) > 2 || ndims(B) > 2\n error('kronecker:TwoDInput','Inputs must be 2-D.');\n end\n % Both inputs are full, result is full. This is faster than\n % MATLAB stock kron (indexing based)\n [ma na] = size(A);\n [mb nb] = size(B);\n A = reshape(A,[1 ma 1 na]);\n B = reshape(B,[mb 1 nb 1]);\n K = bsxfun(@times,A,B);\n K = reshape(K,[ma*mb na*nb]);\n \nelse % One of the input matrix is sparse\n \n % Call MATLAB stock KRON\n K = kron(A,B);\n \nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/kronecker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279739, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6298355198055929}} {"text": "function [ J, grad, u ] = optimal_control ( x, e_conn, q, y1, y2, Md, Nd, L )\n\n%*****************************************************************************80\n%\n%% OPTIMAL_CONTROL is a script to solve the optimal control problem.\n%\n% Discussion:\n%\n% The differential equation being solved has the form:\n%\n% ( q(x) u_x(x) )_x = f(x)\n%\n% The solution is approxiamted using 1D linear finite elements.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Parameters:\n%\n% Input, X\n%\n% Input, E_CONN\n%\n% Input, Q\n%\n% Input, Y1\n%\n% Input, Y2\n%\n% Input, MD\n%\n% Input, ND\n%\n% Input, L\n%\n% Output, J\n%\n% Output, GRAD\n%\n% Output, U\n%\n alpha = 0.000003;\n\n [n_nodes , n_dimensions] = size(x );\n [n_elements, nel_dof ] = size(e_conn);\n\n n_equations = n_nodes-2;\n ide(1) = -1;\n ide(2:n_nodes-1) = 1:n_equations;\n ide(n_nodes) = -2;\n\n dir = zeros(2,1);\n\n n_gauss = 3; % number of points used in Gaussian integration\n\n\n% q = x./(1-3*x.^2);\n% q = x.^3;\n% q = x.*(1-x);\n%---------------------------------------------------------------------\n% Build the finite element matrices\n%---------------------------------------------------------------------\n\n M = sparse(n_nodes ,n_nodes );\n K = sparse(n_equations,n_equations);\n b = zeros (n_equations,1 );\n u = zeros (n_nodes ,1 );\n\n [r,w] = oned_gauss(n_gauss);\n\n o_g = ones(size(r));\n\n for n_el=1:n_elements\n\n % compute value of each test function and their spatial derivaties\n % at the integration points\n nodes_local = e_conn(n_el,:);\n x_local = x(nodes_local,:);\n [x_g,w_g,phi,p_x] = oned_shape(x_local,r,w);\n\n q_local = q(nodes_local);\n q_g = phi*q_local;\n\n % compute the value of functions at the Gauss points\n f_g = f_function(x_g, y1, y2, Md, Nd, L);\n\n %--------------------------------------------------------------------\n % Integrate the weak form of the equations (element contributions)\n %--------------------------------------------------------------------\n M_loc = oned_bilinear(o_g, phi, phi, w_g);\n K_loc =-oned_bilinear(q_g, p_x, p_x, w_g);\n b_loc = oned_f_int (f_g, phi, w_g);\n\n %-----------------------------------------------------------------\n % Assemble contributions into the global system matrix\n %-----------------------------------------------------------------\n\n M(nodes_local,nodes_local) = M(nodes_local,nodes_local) + M_loc;\n\n for n_t=1:nel_dof\n n_test = ide(nodes_local(n_t));\n if (n_test > 0) % this is an unknown, fill the row\n for n_u=1:nel_dof\n n_unk = ide(nodes_local(n_u));\n if (n_unk > 0)\n K(n_test,n_unk) = K(n_test,n_unk) + K_loc(n_t,n_u);\n end\n end\n b(n_test) = b(n_test) + b_loc(n_t);\n end\n end\n\n end\n\n %-----------------------------------------------------------------------\n % Perform Implicit Solve\n %-----------------------------------------------------------------------\n% figure(5); spy(A); % view the sparsity pattern in A\n\n du = K\\b;\n\n %-----------------------------------------------------------------------\n % Construct the Solution (here, we simply apply the Dirichlet bc's)\n %-----------------------------------------------------------------------\n for n=1:n_nodes\n i = ide(n);\n if (i>0)\n % get the nodal value out of the linear system solve\n u(n) = du(i);\n else\n % get the nodal value from the specified Dirichlet bc\n u(n) = dir(-i);\n end\n end\n\n% figure(12)\n% plot(x,u)\n% hold on\n% up = u_hat(x, y);\n% plot(x,up,'r+')\n\n lam = zeros(n_nodes ,1);\n c = zeros(n_equations,1);\n % Compute the right hand side of the adjoint equation\n for n_el=1:n_elements\n\n nodes_local = e_conn(n_el,:);\n x_local = x(nodes_local,:);\n [x_g,w_g,phi,p_x] = oned_shape(x_local,r,w);\n\n u_local = u(nodes_local);\n u_g = phi*u_local;\n\n % compute the value of functions at the Gauss points\n uhat_g = u_hat(x_g, y1, Md, L);\n\n %--------------------------------------------------------------------\n % Integrate the weak form of the equations (element contributions)\n %--------------------------------------------------------------------\n c_loc = oned_f_int ( uhat_g-u_g, phi, w_g);\n\n %-----------------------------------------------------------------\n % Assemble contributions into the global system matrix\n %-----------------------------------------------------------------\n for n_t=1:nel_dof\n n_test = ide(nodes_local(n_t));\n if (n_test > 0) % this is an unknown, fill the row\n c(n_test) = c(n_test) + c_loc(n_t);\n end\n end\n\n end\n\n J = 0.5*sqrt(c'*M(2:end-1,2:end-1)*c);\n dlam = K'\\c;\n\n for n=1:n_nodes\n i = ide(n);\n if (i>0)\n lam(n) = dlam(i);\n else\n lam(n) = dir(-i);\n end\n end\n\n% figure\n% plot(x,lam)\n\n grad = zeros(n_nodes,1);\n\n % Compute the gradient\n for n_el=1:n_elements\n\n nodes_local = e_conn(n_el,:);\n x_local = x(nodes_local,:);\n [x_g,w_g,phi,p_x] = oned_shape(x_local,r,w);\n\n u_local = u(nodes_local);\n u_g = phi*u_local;\n ux_g = p_x*u_local;\n\n q_local = q(nodes_local);\n q_g = phi*q_local;\n qx_g = p_x*q_local;\n\n lam_local = lam(nodes_local);\n lam_g = phi*lam_local;\n lamx_g = p_x*lam_local;\n\n% grad_loc = alpha*oned_f_int( q_g, phi, w_g) ...\n% - oned_f_int( lamx_g.*ux_g, phi, w_g);\n grad_loc = alpha*oned_f_int( qx_g, p_x, w_g) ...\n - oned_f_int( lamx_g.*ux_g, phi, w_g);\n\n for n_t=1:nel_dof\n n_test = nodes_local(n_t);\n grad(n_test) = grad(n_test) + grad_loc(n_t);\n end\n\n end\n\n% figure\n% plot(x,grad)\n% title('gradient')\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/stochastic_gradient_nd_noise/optimal_control.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6298348913247422}} {"text": "function x = mg_ns_iter(mgdata,x0,f,level,npre,npost,sweeps)\n%mg_ns_iter performs one MG iteration (Navier-Stokes)\n% x = mg_ns_iter(mgdata,x0,f,level,npre,npost,sweeps)\n% input\n% mgdata structure containing matrices, grid transfer \n% operators and smoothing operators\n% x0 initial iterate\n% f right-hand side\n% level grid level\n% npre number of presmoothing steps\n% npost number of postsmoothing steps\n% sweeps type of sweeping strategy used for Gauss-Seidel\n% smoothing\n% output\n% x result of one MG iteration\n%\n% IFISS function: HCE; 18 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\n\nA = mgdata(level).matrix;\nP = mgdata(level).prolong;\nfor i=2:level, smoother(i) = mgdata(i).smoother; end \n\nif level==2,\n n = length(A);\n [U,Sig,V] = svd(full(A));\n s = diag(Sig);\n if abs(s(n))<1.d-14, si = [1./s(1:n-1);0];\n else si = 1./s(1:n);\n end\n Sigi = diag(si);\n x = V*(Sigi*(U'*f));\nelse\n\n % presmooth \n x = mg_pre(A,x0, f,npre,smoother,level,sweeps);\n % Restrict residual \n r = f - A*x;\n rc = P'*r;\n % coarse grid correction\n cc = mg_ns_iter(mgdata,zeros(size(rc)),rc,level-1,npre,npost,sweeps);\n % add this line for W-cycle\n% cc = mg_ns_iter(mgdata,cc,rc,level-1,npre,npost,sweeps);\n x = x + P*cc; \n % postsmooth\n x = mg_post(A,x,f,npost,smoother,level,sweeps);\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/toms866/solvers/mg_ns_iter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6298348887257393}} {"text": "function [aic, sbic] = aicsbic(errors,constant,p,q,X)\n% Computes the Akaike and Schwartz/Bayes Information Criteria for an ARMA(P,Q) as parameterized in\n% ARMAXFILTER \n%\n% USAGE:\n% [AIC] = aicsbic(ERRORS,CONSTANT,P,Q)\n% [AIC,SBIC] = aicsbic(ERRORS,CONSTANT,P,Q,X)\n% \n% INPUTS:\n% ERRORS - A T by 1 length vector of errors from the regression\n% CONSTANT - Scalar variable: 1 to include a constant, 0 to exclude\n% P - Non-negative integer vector representing the AR orders to include in the model.\n% Q - Non-negative integer vector representing the MA orders to include in the model.\n% X - [OPTIONAL] a T by K matrix of exogenous variables.\n% \n% OUTPUTS:\n% AIC - The Akaike Information Criteria \n% SBIC - The Schwartz/Bayes Information Criteria\n% \n% COMMENTS:\n% This is a helper for ARMAXFILTER and uses the same inputs, CONSTANT, P, Q and X. ERRORS should\n% be the errors returned from a call to ARMAXFILTER with the same values of P, Q, etc. \n%\n% EXAMPLES:\n% Compute AIC and SBIC from an ARMA\n% [parameters, LL, errors] = armaxfilter(y, constant, p, q);\n% [aic,sbic] = aicsbic(errors,constant,p,q)\n% \n% See also ARMAXFILTER, HETEROGENEOUSAR\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 10/19/2009\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input Checking\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin<3 || nargin>5\n error('3 to 5 inputs required')\nend\nif nargin==3\n q = [];\n X=[];\nelseif nargin==4\n X=[];\nend\n%%%%%%%%%%%%%%%\n% y\n%%%%%%%%%%%%%%%\nif size(errors,2) > 1 || length(errors)==1\n error('ERRORS series must be a column vector.')\nelseif isempty(errors)\n error('ERRORS is empty.')\nend\n\n%%%%%%%%%%%%%%%\n% P\n%%%%%%%%%%%%%%%\nif size(p,2)>size(p,1)\n p=p';\nend\nif isempty(p)\n p=0;\nend\nif min(size(p))~=1\n error('P must be a column vector of included lags')\nend\nif any(p<0) || any(floor(p)~=p)\n error('P must contain non-negative integers only')\nend\nif max(p)>=(length(errors)-max(p))\n error('Too many lags in the AR. max(P)size(q,1)\n q=q';\nend\nif isempty(q)\n q=0;\nend\nif min(size(q))~=1\n error('Q must be a column vector of included lags')\nend\nif any(q<0) || any(floor(q)~=q)\n error('Q must contain non-negative integers only')\nend\nif max(q)>=length(errors)\n error('Too many lags in the AR. max(Q) 0) .* res_.dzdx ;\ndw = ...\n + dwdcs .* repmat(1./n, [1 1 2*ly.NO]) ...\n - bsxfun(@times, sum(bsxfun(@rdivide, dwdcs.*x/ly.NO, n.*n2),3), x) ;\nres.dzdx = bsxfun(@times, sum(res_.dzdx .* w, 3), dn) + bsxfun(@times, n, dw) ;\n", "meta": {"author": "aravindhm", "repo": "deep-goggle", "sha": "cc667f02dd079f060542594a3592d6b7feb1137c", "save_path": "github-repos/MATLAB/aravindhm-deep-goggle", "path": "github-repos/MATLAB/aravindhm-deep-goggle/deep-goggle-cc667f02dd079f060542594a3592d6b7feb1137c/experiments/networks/dsift_net.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6297867074636663}} {"text": "function C = ecov_music_1d(design, wavelength, doas, P, noise_var, snapshot_count)\n%ECOV_MUSIC_1D Asymptotic covariance matrix of the estimation errors\n%of the classical MUSIC algorithm.\n%Syntax:\n% C = ECOV_MUSIC_1D(design, wavelength, doas, P, noise_var[, snapshot_count])\n%Inputs:\n% design - Array design.\n% wavelength - Wavelength.\n% doas - DOA vector in radians.\n% P - Source covariance matrix. If all sources are uncorrelated and\n% shares the same power, you can just pass in a scalar. If all\n% sources are uncorrelated but have different powers, you can just\n% pass in a vector.\n% noise_var - Noise power.\n% snapshot_count - (Optional) number of snapshots. Default is one.\n%Output:\n% C - Asymptotic error covariance matrix.\n%Reference:\n% [1] P. Stoica and A. Nehorai, \"MUSIC, maximum likelihood, and\n% Cramer-Rao bound: further results and comparisons,\" IEEE\n% Transactions on Acoustics, Speech and Signal Processing, vol. 38,\n% no. 12, pp. 2140-2150, Dec. 1990.\n% [2] P. Stoica and A. Nehorai, \"MUSIC, maximum likelihood, and\n% Cramer-Rao bound,\" IEEE Transactions on Acoustics, Speech and\n% Signal Processing, vol. 37, no. 5, pp. 720-741, May 1989.\nif design.dim ~= 1\n error('1D array expected.');\nend\nif nargin <= 5\n snapshot_count = 1;\nend\nm = design.element_count;\nk = length(doas);\nP = unify_source_power_matrix(P, k);\n[A, D] = steering_matrix(design, wavelength, doas);\nH = D'*(eye(m) - A/(A'*A)*A')*D;\nB = P\\(P + noise_var*eye(k)/(A'*A))/P;\nh = real(1 ./ diag(H));\nC = (noise_var/2/snapshot_count) * (real(H .* B.') .* (h*h'));\nend", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/performance/ecov_music_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6297867000776539}} {"text": "function N = tangentspherefactory(M, x)\n% Returns a manifold struct. for the sphere on the tangent space to M at x.\n%\n% N = tangentspherefactory(M, x)\n%\n% N defines a manifold that is the unit sphere on the tangent space to M\n% at x. Points are represented as tangent vectors of unit norm. Tangent\n% vectors are represented as tangent vectors orthogonal to the root point,\n% with respect to the Riemannian metric on the tangent space.\n%\n% This is chiefly useful to solve optimization problems involving unit norm\n% tangent vectors to M at x, which notably comes up when looking for\n% extreme eigenvectors of the Hessian of a cost function on M at x, for\n% example. The Riemannian structure on this sphere is that of a Riemannian\n% submanifold of the (Euclidean) tangent space, equipped with the\n% Riemannian metric of M at that point.\n%\n% See also: hessianextreme\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, March 16, 2015.\n% Contributors: \n% Change log: \n%\n% Nov 27, 2015 (NB):\n% Extra projection added in the retraction, to prevent numerical\n% drift.\n%\n% Jun 23, 2021 (QR):\n% Extra projection in retraction changed to M.tangent.\n%\n% Jun 23, 2021 (NB):\n% Several fixes to the logic of this factory that should help for\n% more sophisticated manifolds where representations of points,\n% tangent vectors and ambient vectors are not straightforward.\n\n % N is the manifold we build.\n % y is a point on N, thus also a tangent vector to M at x.\n % This is a typical Riemannian submanifold of a Euclidean space,\n % hence it is easy to describe in terms of the tools available for M.\n N = struct();\n N.name = @() sprintf('Sphere in a tangent space of [%s]', M.name());\n \n % u, u1 and u2 are tangent vectors to N at y.\n % The tangent space to N at y is a subspace of the tangent space to M\n % at x, thus u, u1 and u2 are also tangent vectors to M at x.\n \n N.dim = @() M.dim() - 1;\n N.inner = @(y, u1, u2) M.inner(x, u1, u2);\n N.norm = @(y, u) M.norm(x, u);\n N.proj = @(y, v) M.lincomb(x, 1, v, -M.inner(x, v, y), y);\n N.typicaldist = @() 1;\n N.tangent = N.proj;\n N.egrad2rgrad = N.proj;\n N.retr = @retraction;\n N.exp = N.retr;\n function yy = retraction(y, u, t)\n if nargin == 2\n t = 1;\n end\n y_plus_tu = M.lincomb(x, 1, y, t, u);\n % Mathematically, y_plus_tu is exactly in the tangent space to M at\n % x. However, numerically, it may 'leave' the tangent space\n % slightly. The extra 'projection' on the next line is not required\n % mathematically but helps prevent numerical issues sometimes.\n % If this proves to be a huge slow down, one could consider adding\n % a type of counter that only executes this extra step every so\n % often, instead of at every call.\n y_plus_tu = M.tangent(x, y_plus_tu);\n nrm = M.norm(x, y_plus_tu);\n yy = M.lincomb(x, 1/nrm, y_plus_tu);\n end\n N.rand = @random;\n function y = random()\n y = M.randvec(x);\n nrm = M.norm(x, y);\n y = M.lincomb(x, 1/nrm, y);\n end\n N.randvec = @randvec;\n function u = randvec(y)\n u = N.proj(y, M.randvec(x));\n nrm = N.norm(y, u);\n u = M.lincomb(x, 1/nrm, u);\n end\n N.zerovec = @(y) M.zerovec(x);\n N.transp = @(y1, y2, u) N.proj(y2, u);\n N.hash = @(y) ['z' hashmd5(M.vec(x, y))];\n \n N.lincomb = @Nlincomb;\n function v = Nlincomb(y, a1, d1, a2, d2) %#ok\n if nargin == 3\n v = M.lincomb(x, a1, d1);\n elseif nargin == 5\n v = M.lincomb(x, a1, d1, a2, d2);\n else\n error('lincomb takes either 3 or 5 inputs.');\n end\n end\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/tools/tangentspherefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6297866951536454}} {"text": "function Xtensor = tucker2multiarray(X)\n% Converts a 3d Tucker form tensor to a multiarray.\n%\n% function Xtensor = tucker2multiarray(X)\n%\n% X has fields U1, U2, U3, and G.\n%\n% The matrices U1 (n1-by-r1), U2 (n2-by-r2) and U3 (n3-by-r3) are\n% orthogonal matrices.\n% G (r1-by-r2-by-r3) is a multidimensional array.\n%\n% See also: fixedrankfactory_tucker_preconditioned\n\n% This file is part of Manopt: www.manopt.org.\n% Original authors: Hiroyuki Kasai and Bamdev Mishra, June 05, 2015.\n% Contributors:\n% Change log:\n \n U1 = X.U1;\n U2 = X.U2;\n U3 = X.U3;\n G = X.G;\n \n % Tensor size\n n1 = size(U1, 1);\n n2 = size(U2, 1);\n n3 = size(U3, 1);\n \n % Core size\n [r1, r2, r3] = size(G);\n \n % Multplication by U1\n G1 = reshape(G, r1, r2*r3);\n GU1 = reshape(U1*G1, n1, r2, r3);\n \n % Further multplication by U2\n G2 = reshape(permute(GU1, [2 1 3]), r2, n1*r3);\n GU1U2 = permute(reshape(U2*G2, n2, n1, r3), [2 1 3]);\n \n % Further multplication by U3\n G3 = reshape(permute(GU1U2, [3 1 2]), r3, n1*n2); \n GU1U2U3 = permute(reshape(U3*G3, n3, n1, n2), [2 3 1]);\n \n Xtensor = GU1U2U3;% Full tensor\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/fixedranktensors/tucker2multiarray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6297043207638341}} {"text": "function rval=rtest_1()\n\nn = 49;\n[A,b] = testmat(n,2);\nx0 = [1:n]'/(n+1);\ny0 = [1:n]'/(n+1);\nx = repmat(x0,1,n);\ny = repmat(y0',n,1);\nxy = [x(:),y(:)];\n\nrval = 0;\ntry \n T = mst(A);\n T = T + diag(diag(A));\n rval = 1;\ncatch\n lasterr\nend;\n\ntry\n A(1,2)= -1; \n A(2,1)= -1; \n T = prim_mst(A);\n rval = 0;\ncatch\n rval = 1;\nend;\n\nfunction [A,b] = testmat( n,stencil )\n h = 1/(n+1);\n \n % initialization\n x = [1:n]'/(n+1);\n y = [1:n]'/(n+1);\n u = zeros(n,n);\n \n % exact solution\n u0 = repmat(x.^4,1,n) + repmat(12*y'.^2,n,1);\n \n % matices\n T0 = -ones(n);\n T0 = sparse( triu(tril(T0,-1),-1) + triu(tril(T0,1),1) );\n I = speye(n);\n if stencil == 1\n T = (-8*I - T0) / 3;\n B = (I - T0) / 3;\n else\n T = (-20*I - 4*T0) / 6;\n B = (4*I - T0) / 6;\n end\n \n A = kron(I,T) - kron(T0,B);\n\n % boundary\n b = zeros(n);\n if stencil == 1\n b(1,:) = b(1,:) + 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2;\n b(n,:) = b(n,:) + 3 + 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2;\n b(:,1) = b(:,1) + x.^2 + (x-h).^2 + (x+h).^2;\n b(:,n) = b(:,n) + x.^2 + (x-h).^2 + (x+h).^2 + 12*3;\n else\n b(1,:) = b(1,:) + 4* 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2;\n b(n,:) = b(n,:) + 6 + 4* 12*y'.^2 + 12*(y-h)'.^2 + 12*(y+h)'.^2;\n b(:,1) = b(:,1) + 4* x.^2 + (x-h).^2 + (x+h).^2;\n b(:,n) = b(:,n) + 4* x.^2 + (x-h).^2 + (x+h).^2 + 12*6;\n end\n % fix corners\n b(1,n) = b(1,n) - 12;\n b(n,1) = b(n,1) - 1;\n b(n,n) = b(n,n) - 13;\n % normalize\n if stencil == 1\n b = - b / 3;\n else\n b = - b / 6;\n end\n % add source\n f = 12*x.^2 + 24;\n f = repmat(f,1,n);\n b = b + f * h^2;\n \n b = b(:);\nreturn ", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/matlab_bgl/test/rtest_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6297043147279074}} {"text": "function [ h,mycolormap ] = PlotVorticity( STATE,varargin )\n\n\nmycolormap = VorticityColormap( 64 );\n h=0;\n\nif nargout>1\n return;\nend\n% cavity grid and PDE operators\n\nN = sqrt(size(STATE,1))-1;\n\n[Grid]=CollocationGrid_q(N); % the computational grid\n[~,Grid.wc] = clencurt(N);Grid.W = kron(Grid.wc,Grid.wc); % integration weights\n disp('grid created')\n\n\n[ Operators ] = CreateOperators_psi( Grid.D,eye(N+1));\ndisp('operators for psi created')\n\n\n% grid for the plot\n[xx2,yy2] = meshgrid(Grid.x,Grid.x);\n[xxx,yyy] = meshgrid(-1:.005:1,-1:.005:1); \n% vorticity \nw = - Operators.del2*STATE;\nww = reshape(real(w),N+1,N+1);\nwww = interp2(xx2,yy2,ww,xxx,yyy,'spline');\n\na = 2;\nif ~isempty(varargin)\n a = varargin{1};\nend\n\nwww(www>a)=a;www(www<-a)=-a;\n\n% figure(100+randi(100))\n contourf(xxx,yyy,www,100,'LineStyle','None') ; % vorticty\n axis square; \n box on;\n colormap(mycolormap);\n caxis([-a,a]);\n ax = gca;\n ax.XTick = [-1 1];\n ax.YTick = [-1 1];\nend\n\nfunction [ cmap ] = VorticityColormap( ncol )\n%VORTICITYCOLORMAP Summary of this function goes here\n% Detailed explanation goes here\ncmap=jet(ncol);\nfor i=ncol/8+1:7*ncol/16\n cmap(i,:)=[(i-ncol/8)/(5*ncol/16),(i-ncol/8)/(5*ncol/16),1]; % blue fading to white\nend\n\n cmap(7*ncol/16+1:9*ncol/16,:)=1; % white\n\nfor i=9*ncol/16+1:7*ncol/8\n cmap(i,:)=[1,1-(i-9*ncol/16)/(5*ncol/16),1-(i-9*ncol/16)/(5*ncol/16)]; % white turning red\nend\n\nend", "meta": {"author": "arbabiha", "repo": "KoopmanMPC_for_flowcontrol", "sha": "4581c284bed5420fee7a7e9a58590fe93a196c97", "save_path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol", "path": "github-repos/MATLAB/arbabiha-KoopmanMPC_for_flowcontrol/KoopmanMPC_for_flowcontrol-4581c284bed5420fee7a7e9a58590fe93a196c97/thehood/PlotVorticity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6297043100869687}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Setting up advection-diffusion solver\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [C,laplacian_C] = please_Update_Adv_Diff_Concentration_Flux_Limiter_FV(C,dt,dx,dy,uX,uY,k)\n\n% C: concentration \n% dt: time-step\n% dx,dy: spatial steps in x and y, respectively\n% uX: x-Component of Velocity\n% uY: y-Component of Velocity\n% k: diffusion coefficient\n\n% Compute Fluxes (Note: these calculations could be parallalized)\nselection = 'superbee';\nFx = give_Necessary_Fluxes(C,dx,uX,'x',selection,dt); % Fluxes in x\nFy = give_Necessary_Fluxes(C,dy,uY,'y',selection,dt); % Fluxes in y\n\n% \"forward difference of fluxes in x\"\nF2x = [Fx(:,2:end) Fx(:,1)];\nF1x = [Fx(:,end) Fx(:,1:end-1)];\ndiffX = 0.5/dx*( F2x - F1x );\n \n% \"forward differences of fluxes in y\"\nF2y = [Fy(2:end,:); Fy(1,:)];\nF1y = [Fy(end,:); Fy(1:end-1,:)];\ndiffY = 0.5/dy*( F2y - F1y );\n \n\n% Compute 2nd Derivative Terms\nCxx = DD(C,dx,'x');\nCyy = DD(C,dy,'y');\n\n\n% Forms Laplacian\nlaplacian_C = Cxx+Cyy;\n \n% UPWIND\nC = C - dt * ( diffX + diffY ) + dt*( k*laplacian_C );\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes derivative based on sign of Velocity, u, using UPWIND\n% approach\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C_z = give_Necessary_Fluxes(C,dz,uZ,string,selection,dt)\n\nC_z = zeros(size(C));\nlen = length(uZ(:,1));\nsigns = sign(uZ);\n\nif strcmp(string,'x')\n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %left side of grid\n if signs(i,1) <= 0 \n r = ( C(i,2) - C(i,1) ) / ( C(i,1) - C(i,len) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,1) = uZ(i,1)*C(i,2) + 0.5*abs( uZ(i,1) )*( 1 - abs( 0.5*dt*uZ(i,1)/dz ) )*phi*( C(i,2) - C(i,len) );\n else\n r = ( C(i,1) - C(i,len) ) / ( C(i,2) - C(i,1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,1) = uZ(i,1)*C(i,len) + 0.5*abs( uZ(i,1) )*( 1 - abs( 0.5*dt*uZ(i,1)/dz ) )*phi*( C(i,2) - C(i,len) );\n end\n\n %right side of grid\n if signs(len,1) <= 0\n r = ( C(i,1) - C(i,len) ) / ( C(i,len) - C(i,len-1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,len) = uZ(i,len)*C(i,1) + 0.5*abs( uZ(i,len) )*( 1 - 0.5*abs( dt*uZ(i,len)/dz ) )*phi*( C(i,1) - C(i,len-1) );\n else\n r = ( C(i,len) - C(i,len-1) ) / ( C(i,1) - C(i,len) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,len) = uZ(i,len)*C(i,len-1) + 0.5*abs( uZ(i,len) )*( 1 - 0.5*abs( dt*uZ(i,len)/dz ) )*phi*( C(i,1) - C(i,len-1) );\n end\n\n end\n %Standard Upwind \n for i=1:len\n for j=2:len-1\n if signs(i,j) <= 0\n r = ( C(i,j+1) - C(i,j) ) / ( C(i,j) - C(i,j-1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,j) = uZ(i,j)*C(i,j+1) + 0.5*abs( uZ(i,j) )*( 1 - 0.5*abs( dt*uZ(i,j)/dz ) )*phi*( C(i,j+1) - C(i,j-1) );\n else\n r = ( C(i,j) - C(i,j-1) ) / ( C(i,j+1) - C(i,j) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,j) = uZ(i,j)*C(i,j-1) + 0.5*abs( uZ(i,j) )*( 1 - 0.5*abs( dt*uZ(i,j)/dz ) )*phi*( C(i,j+1) - C(i,j-1) );\n end\n end\n end\n\n % Ends x-Direction calculation %\n \nelseif strcmp(string,'y') \n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %bottom of grid\n if signs(1,i) <= 0\n r = ( C(2,i) - C(1,i) ) / ( C(1,i) - C(len,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(1,i) = uZ(1,i)*C(2,i) + 0.5*abs( uZ(1,i) )*( 1 - abs( 0.5*dt*uZ(1,i)/dz ) )*phi*( C(2,i) - C(len,i) );\n else\n r = ( C(1,i) - C(len,i) ) / ( C(2,i) - C(1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(1,i) = uZ(1,i)*C(len,i) + 0.5*abs( uZ(1,i) )*( 1 - abs( 0.5*dt*uZ(1,i)/dz ) )*phi*( C(2,i) - C(len,i) );\n end\n\n %top of grid\n if signs(len,1) <= 0\n r = ( C(1,i) - C(len,i) ) / ( C(len,i) - C(len-1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(len,i) = uZ(len,i)*C(1,i) + 0.5*abs( uZ(len,i) )*( 1 - abs( 0.5*dt*uZ(len,i)/dz ) )*phi*( C(1,i) - C(len-1,i) );\n else\n r = ( C(len,i) - C(len-1,i) ) / ( C(1,i) - C(len,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(len,i) = uZ(len,i)*C(len-1,i) + 0.5*abs( uZ(len,i) )*( 1 - abs( 0.5*dt*uZ(len,i)/dz ) )*phi*( C(1,i) - C(len-1,i) );\n end\n\n end\n \n %Standard Upwind\n for i=1:len\n for j=2:len-1\n if signs(j,i) <= 0\n r = ( C(j+1,i) - C(j,i) ) / ( C(j,i) - C(j-1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(j,i) = uZ(j,i)*C(j+1,i) + 0.5*abs( uZ(j,i) )*( 1 - abs( 0.5*dt*uZ(j,i)/dz ) )*phi*( C(j+1,i) - C(j-1,i) );\n else\n r = ( C(j,i) - C(j-1,i) ) / ( C(j+1,i) - C(j,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(j,i) = uZ(j,i)*C(j-1,i) + 0.5*abs( uZ(j,i) )*( 1 - abs( 0.5*dt*uZ(j,i)/dz ) )*phi*( C(j+1,i) - C(j-1,i) );\n end\n end\n end\n\n % Ends y-Direction calculation %\n \nelse\n \n fprintf('\\n\\n\\n ERROR IN FUNCTION FOR COMPUTING FLUX LIMITERS\\n');\n \nend\n \nclear signs; clear len;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes flux limiter with choice of which one\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction phi = please_Give_Flux_Limiter(r,selection)\n\nif strcmp(selection,'superbee')\n max1 = max( min(1,2*r),min(2,r) );\n phi = max(0,max1);\nelse\n fprintf('\\n\\n');\n error('NEED TO CHOOSE AN APPROPRIATE FLUX LIMITER');\nend", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/IBM_Blackbox/please_Update_Adv_Diff_Concentration_Flux_Limiter_FV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.629699422993966}} {"text": "function [map, dist] = imPointsInfluenceZones(varargin)\n%IMPOINTSINFLUENCEZONES Maps influence zones of a set of 2D/3D points\n%\n% MAP = imPointsInfluenceZones(DIM, POINTS)\n% DIM is a 1-by-2 or 1-by-3 row vector containing dimensions of ouput\n% label map. POINTS is a N-by-2 or N-by-3 array of coordinates.\n%\n% MAP = imPointsInfluenceZones(LX, LY, POINTS)\n% MAP = imPointsInfluenceZones(LX, LY, LZ, POINTS)\n% LX and LY and optionnaly LZ are row vectors containing the values of\n% XData, YData, and ZData. The size of MAP if given by:\n% * length(LY)-by-length(LX) in case of 2D points\n% * length(LY)-by-length(LX)-by-length(LZ) in case of 3D points\n%\n% [MAP, DIST] = imPointsInfluenceZones(...)\n% Also returns the distance map, containing for each pixel or voxel the\n% distance to the closest point in the input point set.\n%\n% Example\n% % Planar example\n% points = rand(20, 2) * 200;\n% map = imPointsInfluenceZones([200 200], points);\n% rgb = label2rgb(map, jet(20), 'w', 'shuffle');\n% figure; imshow(rgb);\n%\n% % 3D example\n% dim = [100 100 100];\n% np = 200;\n% points = rand(np, 3) * dim(1);\n% tic; [map, dist] = imPointsInfluenceZones(dim, points); toc\n% rgb = label2rgb3d(map, jet(np+1), 'w', 'shuffle');\n% figure; imshow(rgb(:,:,:,50));\n%\n% See also\n% imDistance, imvoronoi2d, imvoronoi3d\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2019-05-10, using Matlab 9.6.0.1072779 (R2019a)\n% Copyright 2019 INRA - Cepia Software Platform.\n\n\n%% Extract input arguments\n\n% checkup on input argument number\nif nargin < 2\n error('Requires at least two input arguments');\nend\n\n% extraction of image dimensions\nvar1 = varargin{1};\nif size(var1, 1) == 1 && (size(var1, 2) == 2 || size(var1, 2) == 3)\n % first argument contains the size of the output image\n lx = 1:var1(2);\n ly = 1:var1(1);\n if length(var1) == 3\n lz = 1:var1(3);\n end\n varargin(1) = [];\n \nelseif size(var1, 1) == 1 && size(varargin{2}, 1) == 1\n % first and second arguments contain vector for each coordinate\n % respectively\n lx = var1;\n ly = varargin{2};\n if size(varargin{3}, 1) == 1\n lz = varargin{3};\n varargin(1:3) = [];\n else\n varargin(1:2) = [];\n end\n \nelse\n error(['wrong input arguments in ' mfilename]);\nend\n\n% extraction of points\npoints = varargin{1};\n\n\n%% Initialisations\n\n% number of points\nnPoints = size(points, 1);\nnd = size(points, 2);\n\n% size of output image\nNx = length(lx);\nNy = length(ly);\n\n\n%% Generation of distance function\n\nif nd == 2\n % allocate memory for label map\n map = zeros([Ny Nx]);\n % initialize distance map with arbitrarily large distance\n dist = inf * ones([Ny Nx]);\n \n % pixels coordinates\n [x, y] = meshgrid(lx, ly);\n \n % update distance for each point\n for i = 1:nPoints\n % squared distance from each pixel to current point\n di = (x - points(i,1)).^2 + (y - points(i,2)).^2;\n \n % update arrays for current influence zone\n inds = di < dist;\n map(inds) = i;\n dist(inds) = di(inds);\n end\n \n % convert squared distance to Euclidean distance\n dist = sqrt(dist);\n \nelseif nd == 3\n % size in third dimension\n Nz = length(lz);\n \n % allocate memory for label map\n map = zeros([Ny Nx Nz]);\n \n % initialize distance map with arbitrarily large distance\n dist = inf * ones([Ny Nx Nz]);\n \n % pixels coordinates\n [x, y, z] = meshgrid(lx, ly, lz);\n \n % update distance for each point\n for i = 1:nPoints\n % distance from each pixel to current point\n di = (x - points(i,1)).^2 + (y - points(i,2)).^2 + (z - points(i,3)).^2;\n \n % update arrays for current influence zone\n inds = di < dist;\n map(inds) = i;\n dist(inds) = di(inds);\n end \n \n % convert squared distance to Euclidean distance\n dist = sqrt(dist);\nend\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imShapes/imPointsInfluenceZones.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6296630632887422}} {"text": "%% ------------------------solveRWF.m--------------------------------------\n\n\n% Solver for Reweighted Wirtinger Flow as given in Algorithm 1\n% of the Reweightde Wirtinger Flow (TAF) paper. Refer to the userguide for\n% a detailed usage of the package.\n\n% PAPER TITLE:\n% Phase Retrieval via Reweighted Wirtinger Flow\n% ARXIV LINK:\n% https://doi.org/10.1364/AO.56.002418\n\n% INPUTS:\n% A: Function handle/numerical matrix for data matrix A. The rows\n% of this matrix are the measurement vectors that produce\n% amplitude measurements '\\psi'.\n% At: Function handle/numerical matrix for A transpose.\n% b0: Observed data vector consisting of amplitude measurements\n% generated from b0 = |A*x|. We assign it to 'psi' to be\n% consistent with the notation in the paper.\n% x0: The initial vector to be used by any solver. \n% opts: struct consists of the options for the algorithm. For\n% details,see header in solvePhaseRetrieval.m or the User\n% Guide.\n\n% OUPTUT :\n% sol: n x 1 vector. It is the estimated signal.\n% outs: A struct consists of the convergence info. For details,\n% see header in solvePhaseRetrieval.m or the User Guide.\n\n% Note: When a function handle is used, the value of 'n' (the length\n% of the unknown signal) and 'At' (a function handle for the\n% adjoint of 'A') must be supplied. When 'A' is numeric, the\n% values of 'At' and 'n' are ignored and inferred from the\n% arguments\n\n\n% DESCRIPTION:\n% The spectral method proposed by Candes et al. in their\n% seminal Wirtinger Flow paper suffers from fat tails that can\n% distort the true solution. A possible way to overcome this is\n% to truncate the outliers. In this paper, the authors propose\n% a weighted truncated iterative descent method that removes\n% those measurement vector a_m that are not correlated to the\n% intial guess. This truncation and weighting step is done at\n% each iteration of the gradient descent method.\n\n% METHOD:\n% 1) Our implementation uses FASTA, a fast gradient solver.\n%\n% 2) Set the objectve f = @(z) 1/2 * sum(weights .* \n% (abs(z) - b0).^2). The weights are computed according to\n% equation (14) in algorithm 1 of the proposing paper\n%\n% 3) The gradient is grad = @(z) weights .* (z - b0 .* sign(z)).\n%\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n\n\n\n%% -----------------------------START----------------------------------- \n \nfunction [sol, outs] = solveRWF(A, At, b0, x0, opts)\n% addpath('solvers/linesearch');\n \n m = length(b0);\n \n innerOpts = struct;\n innerOpts.maxIters = opts.maxIters;\n innerOpts.maxTime = opts.maxTime;\n innerOpts.tol = opts.tol;\n innerOpts.verbose = opts.verbose;\n innerOpts.recordTimes = opts.recordTimes;\n innerOpts.recordResiduals = opts.recordResiduals;\n innerOpts.recordMeasurementErrors = opts.recordMeasurementErrors;\n innerOpts.recordReconErrors = opts.recordReconErrors;\n innerOpts.xt = opts.xt;\n \n innerOpts.updateObjectivePeriod = opts.reweightPeriod;\n innerOpts.searchMethod = opts.searchMethod;\n innerOpts.betaChoice = opts.betaChoice;\n \n [sol, outs] = gradientDescentSolver(A, At, x0, b0, @updateObjective, innerOpts);\n \n function [f, gradf] = updateObjective(~, Ax)\n weights = 1 ./ (abs(abs(Ax).^2 - b0.^2) + opts.eta*ones(m, 1));\n s = sum(weights);\n f = @(z) 0.5/s * sum(weights .* (abs(z).^2 - b0.^2).^2);\n gradf = @(z) (1.0/s)*weights .* (abs(z).^2 - b0.^2) .* z;\n end\nend", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/solvers/solveRWF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6296630585249335}} {"text": "function [m,v,w,g,f,pp,gg]=gaussmix(x,c,l,m0,v0,w0)\n%GAUSSMIX fits a gaussian mixture pdf to a set of data observations [m,v,w,g,f]=(x,c,l,m0,v0,w0)\n%\n% Inputs: n data values, k mixtures, p parameters, l loops\n%\n% X(n,p) Input data vectors, one per row.\n% c(1) Minimum variance of normalized data (Use [] to take default value of 1/n^2)\n% L The integer portion of l gives a maximum loop count. The fractional portion gives\n% an optional stopping threshold. Iteration will cease if the increase in\n% log likelihood density per data point is less than this value. Thus l=10.001 will\n% stop after 10 iterations or when the increase in log likelihood falls below\n% 0.001.\n% As a special case, if L=0, then the first three outputs are omitted.\n% Use [] to take default value of 100.0001\n% M0(k,p) Initial mixture means, one row per mixture.\n% V0(k,p) Initial mixture variances, one row per mixture.\n% or V0(p,p,k) one full-covariance matrix per mixture\n% W0(k,1) Initial mixture weights, one per mixture. The weights should sum to unity.\n%\n% Alternatively, if initial values for M0, V0 and W0 are not given explicitly:\n%\n% M0 Number of mixtures required\n% V0 Initialization mode:\n% 'f' Initialize with K randomly selected data points [default]\n% 'p' Initialize with centroids and variances of random partitions\n% 'k' k-means algorithm ('kf' and 'kp' determine initialization of kmeans)\n% 'h' k-harmonic means algorithm ('hf' and 'hp' determine initialization of kmeans)\n% 's' do not scale data during initialization to have equal variances\n% 'm' M0 contains the initial centres\n% 'v' full covariance matrices\n% Mode 'hf' [the default] generally gives the best results but 'f' is faster and often OK\n%\n% Outputs: (Note that M, V and W are omitted if L==0)\n%\n% M(k,p) Mixture means, one row per mixture. (omitted if L==0)\n% V(k,p) Mixture variances, one row per mixture. (omitted if L==0)\n% or V(p,p,k) if full covariance matrices in use (i.e. either 'v' option or V0(p,p,k) specified)\n% W(k,1) Mixture weights, one per mixture. The weights will sum to unity. (omitted if L==0)\n% G Average log probability of the input data points.\n% F Fisher's Discriminant measures how well the data divides into classes.\n% It is the ratio of the between-mixture variance to the average mixture variance: a\n% high value means the classes (mixtures) are well separated.\n% PP(n,1) Log probability of each data point\n% GG(l+1,1) Average log probabilities at the beginning of each iteration and at the end\n\n% Bugs/Suggestions\n% (2) Allow processing in chunks by outputting/reinputting an array of sufficient statistics\n% (6) Other initialization options:\n% 'l' LBG algorithm\n% 'm' Move-means (dog-rabbit) algorithm\n\n% Copyright (C) Mike Brookes 2000-2009\n% Version: $Id: gaussmix.m,v 1.22 2009/09/21 14:03:13 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[n,p]=size(x);\nmx0=sum(x,1)/n; % calculate mean and variance of input data\nvx0=sum(x.^2,1)/n-mx0.^2;\nsx0=sqrt(vx0);\nsx0(sx0==0)=1; % do not divide by zero when scaling\nscaled=0; % data is not yet scaled\nmemsize=voicebox('memsize'); % set memory size to use\nif isempty(c)\n c=1/n^2;\nelse\n c=c(1); % just to prevent legacy code failing\nend\nfulliv=0; % initial variance is not full\nif isempty(l)\n l=100+1e-4; % max loop count + stopping threshold\nend\nif nargin<6 % no initial values specified for m0, v0, w0\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % No initialvalues given, so we must use k-means or equivalent\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if nargin<5\n v0='hf'; % default initialization mode: hf\n end\n if any(v0=='m')\n k=size(m0,1);\n else\n k=m0;\n end\n fv=any(v0=='v'); % full covariance matrices requested\n if n<=k % each data point can have its own mixture\n xs=(x-mx0(ones(n,1),:))./sx0(ones(n,1),:); % scale the data\n m=xs(mod((1:k)-1,n)+1,:); % just include all points several times\n v=zeros(k,p); % will be set to floor later\n w=zeros(k,1);\n w(1:n)=1/n;\n if l>0\n l=0.1; % no point in iterating\n end\n else % more points than mixtures\n if any(v0=='s')\n xs=x; % do not scale data during initialization\n else\n xs=(x-mx0(ones(n,1),:))./sx0(ones(n,1),:); % else scale now\n if any(v0=='m')\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % scale specified means as well\n end\n end\n w=repmat(1/k,k,1); % all mixtures equally likely\n if any(v0=='k') % k-means initialization\n if any(v0=='m')\n [m,e,j]=kmeans(xs,k,m);\n elseif any(v0=='p')\n [m,e,j]=kmeans(xs,k,'p');\n else\n [m,e,j]=kmeans(xs,k,'f');\n end\n elseif any(v0=='h') % k-harmonic means initialization\n if any(v0=='m')\n [m,e,j]=kmeanhar(xs,k,[],4,m);\n else\n if any(v0=='p')\n [m,e,j]=kmeanhar(xs,k,[],4,'p');\n else\n [m,e,j]=kmeanhar(xs,k,[],4,'f');\n end\n end\n elseif any(v0=='p') % Initialize using a random partition\n j=ceil(rand(n,1)*k); % allocate to random clusters\n j(rnsubset(k,n))=1:k; % but force at least one point per cluster\n for i=1:k\n m(i,:)=mean(xs(j==i,:),1);\n end\n else\n if any(v0=='m')\n m=m0; % use specified centres\n else\n m=xs(rnsubset(k,n),:); % Forgy initialization: sample k centres without replacement [default]\n end\n [e,j]=kmeans(xs,k,m,0); % find out the cluster allocation\n end\n if any(v0=='s')\n xs=(x-mx0(ones(n,1),:))./sx0(ones(n,1),:); % scale data now if not done previously\n end\n v=zeros(k,p); % diagonal covariances\n w=zeros(k,1);\n for i=1:k\n ni=sum(j==i); % number assigned to this centre\n w(i)=(ni+1)/(n+k); % weight of this mixture\n if ni\n v(i,:)=sum((xs(j==i,:)-repmat(m(i,:),ni,1)).^2,1)/ni;\n else\n v(i,:)=zeros(1,p);\n end\n end\n end\nelse\n %%%%%%%%%%%%%%%%%%%%%%%%\n % use initial values given as input parameters\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n [k,p]=size(m0);\n xs=(x-mx0(ones(n,1),:))./sx0(ones(n,1),:); % scale the data\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % and the means\n v=v0;\n w=w0;\n fv=ndims(v)>2 || size(v,1)>k; % full covariance matrix is supplied\n if fv\n mk=eye(p)==0; % off-diagonal elements\n fulliv=any(v(repmat(mk,[1 1 k]))~=0); % check if any are non-zero\n if ~fulliv\n v=reshape(v(repmat(~mk,[1 1 k])),p,k)'./repmat(sx0.^2,k,1); % just pick out and scale the diagonal elements for now\n else\n v=v./repmat(sx0'*sx0,[1 1 k]); % scale the full covariance matrix\n end\n end\nend\nlsx=sum(log(sx0));\nif ~fulliv % initializing with diagonal covariance\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Diagonal Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n v=max(v,c); % apply the lower bound\n xs2=xs.^2; % square the data for variance calculations\n\n % If data size is large then do calculations in chunks\n\n nb=min(n,max(1,floor(memsize/(8*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n\n im=repmat(1:k,1,nb); im=im(:);\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n\n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n\n % EM loop\n\n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n for j=1:lp\n g1=g; % save previous log likelihood (2*pi factor omitted)\n m1=m; % save previous means, variances and weights\n v1=v;\n w1=w;\n vi=-0.5*v.^(-1); % data-independent scale factor in exponent\n lvm=log(w)-0.5*sum(log(v),2); % log of external scale factor (excluding -0.5*p*log(2pi) term)\n\n % first do partial chunk\n\n jx=jx0;\n ii=1:jx;\n kk=repmat(ii,k,1);\n km=repmat(1:k,1,jx);\n py=reshape(sum((xs(kk(:),:)-m(km(:),:)).^2.*vi(km(:),:),2),k,jx)+lvm(:,wnj);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=sum(px,2); % effective number of data points for each mixture (could be zero due to underflow)\n sx=px*xs(ii,:);\n sx2=px*xs2(ii,:);\n\n for il=2:nl\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx;\n kk=repmat(ii,k,1);\n py=reshape(sum((xs(kk(:),:)-m(im,:)).^2.*vi(im,:),2),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+sum(px,2); % effective number of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xs(ii,:);\n sx2=sx2+px*xs2(ii,:);\n end\n g=sum(lpx); % total log probability summed over all data points\n gg(j)=g;\n w=pk/n; % normalize to get the weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp);\n v=sx2./pk(:,wp);\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); % number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=m;\n m(wm,:)=xs(mk(1:nz),:); % set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; % set these weights non-zero\n w=w*n/(n+nz); % normalize so the weights sum to unity\n wm=~wm; % mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wp);\n end\n v=max(v-m.^2,c); % apply floor to variances\n\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n\n end\n if sd && ~fv % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)/n-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n % gg' % *** DEBUG ***\n m=m1; % back up to previous iteration\n v=v1;\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/sum(v(:));\n end\n if ~fv\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:); % unscale means\n v=v.*repmat(sx0.^2,k,1); % and variances\n else\n v1=v;\n v=zeros(p,p,k);\n mk=eye(p)==1; % mask for diagonal elements\n v(repmat(mk,[1 1 k]))=v1'; % set from v1\n end\nend\nif fv % check if full covariance matrices were requested\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Full Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n pl=p*(p+1)/2;\n lix=1:p^2;\n cix=repmat(1:p,p,1);\n rix=cix';\n lix(cix>rix)=[]; % index of lower triangular elements\n cix=cix(lix); % index of lower triangular columns\n rix=rix(lix); % index of lower triangular rows\n dix=find(rix==cix);\n lixi=zeros(p,p);\n lixi(lix)=1:pl;\n lixi=lixi';\n lixi(lix)=1:pl; % reverse index to build full matrices\n v=reshape(v,p^2,k);\n v=v(lix,:)'; % lower triangular in rows\n\n % If data size is large then do calculations in chunks\n\n nb=min(n,max(1,floor(memsize/(24*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n %\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n %\n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n\n wpl=ones(1,pl); % 1 index for lower triangular matrix\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n\n % EM loop\n\n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n vi=zeros(p*k,p); % stack of k inverse cov matrices each size p*p\n vim=zeros(p*k,1); % stack of k vectors of the form inv(v)*m\n mtk=vim; % stack of k vectors of the form m\n lvm=zeros(k,1);\n wpk=repmat((1:p)',k,1);\n for j=1:lp\n g1=g; % save previous log likelihood (2*pi factor omitted)\n m1=m; % save previous means, variances and weights\n v1=v;\n w1=w;\n\n for ik=1:k\n\n % these lines added for debugging only\n % vk=reshape(v(k,lixi),p,p);\n % condk(ik)=cond(vk);\n %%%%%%%%%%%%%%%%%%%%\n [uvk,dvk]=eig(reshape(v(ik,lixi),p,p)); % convert lower triangular to full and find eigenvalues\n dvk=max(diag(dvk),c); % apply variance floor to eigenvalues\n vik=-0.5*uvk*diag(dvk.^(-1))*uvk'; % calculate inverse\n vi((ik-1)*p+(1:p),:)=vik; % vi contains all mixture inverses stacked on top of each other\n vim((ik-1)*p+(1:p))=vik*m(ik,:)'; % vim contains vi*m for all mixtures stacked on top of each other\n mtk((ik-1)*p+(1:p))=m(ik,:)'; % mtk contains all mixture means stacked on top of each other\n lvm(ik)=log(w(ik))-0.5*sum(log(dvk)); % vm contains the weighted sqrt of det(vi) for each mixture\n end\n %\n % % first do partial chunk\n %\n jx=jx0;\n ii=1:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnj)).*(xii(wpk,:)-mtk(:,wnj)),p,jx*k),1),k,jx)+lvm(:,wnj);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=sum(px,2); % effective number of data points for each mixture (could be zero due to underflow)\n sx=px*xs(ii,:);\n sx2=px*(xs(ii,rix).*xs(ii,cix)); % accumulator for variance calculation (lower tri cov matrix as a row)\n\n for il=2:nl\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnb)).*(xii(wpk,:)-mtk(:,wnb)),p,nb*k),1),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+sum(px,2); % effective number of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xs(ii,:); % accumulator for mean calculation\n sx2=sx2+px*(xs(ii,rix).*xs(ii,cix)); % accumulator for variance calculation\n end\n g=sum(lpx); % total log probability summed over all data points\n gg(j)=g; % save convergence history\n w=pk/n; % normalize to get the column of weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp); % find mean and mean square\n v=sx2./pk(:,wpl);\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); % number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=zeros(k,pl);\n m(wm,:)=xs(mk(1:nz),:); % set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; % set these weights non-zero\n w=w*n/(n+nz); % normalize so the weights sum to unity\n wm=~wm; % mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wpl);\n end\n v=v-m(:,cix).*m(:,rix); % subtract off mean squared\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n end\n if sd % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)/n-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n % gg' % *** DEBUG ONLY ***\n m=m1; % back up to previous iteration\n v=zeros(p,p,k);\n trv=0; % sum of variance matrix traces\n for ik=1:k\n [uvk,dvk]=eig(reshape(v1(ik,lixi),p,p)); % convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n trv=trv+sum(dvk);\n end\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/trv;\n else\n v1=v; % lower triangular form\n v=zeros(p,p,k);\n for ik=1:k\n [uvk,dvk,]=eig(reshape(v1(ik,lixi),p,p)); % convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n end\n end\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:); % unscale means\n v=v.*repmat(sx0'*sx0,[1 1 k]);\nend\nif l==0 % suppress the first three output arguments if l==0\n m=g;\n v=f;\n w=pp;\nend\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/gaussmix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.6296435417188715}} {"text": "function [A,B,flag] = hmxRSVD(varargin)\n%+========================================================================+\n%| |\n%| OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA |\n%| openHmx is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : hmxRSVD.m |\n%| # | VERSION : 0.52 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 01.01.2019 |\n%| ( === ) | SYNOPSIS : RSVD from Halko et al. 'finding structure with|\n%| `---' | randomness'. Adapted from Antoine Liutkus. |\n%+========================================================================+\n\n% Input analysis\nif (numel(varargin{2}) == 1)\n % Input\n M = varargin{1};\n tol = varargin{2};\n rk = varargin{3};\n \n % Dimensions\n [m,n] = size(M);\n \n % Matrix vectot product\n MV = @(V) M * V;\n VM = @(V) V * M;\n \n % Type\n typ = class(M);\n \nelse\n % Input\n A = varargin{1};\n B = varargin{2};\n tol = varargin{3};\n \n % Dimensions\n [m,rk] = size(A);\n n = size(B,2);\n \n % Type\n typ = class(A);\n \n % Matrix vectot product\n MV = @(V) A * (B * V);\n VM = @(V) (V * A) * B;\nend\n\n% Randomized\np = min(2*rk,n);\nX = randn(n,p,typ);\nY = MV(X);\ntry\n W1 = orth(Y);\ncatch\n A = [];\n B = [];\n flag = 0;\n return\nend\nB = VM(W1');\n\n% Truncated SVD\ntry\n [W2,S,V] = svd(B,'econ');\ncatch\n A = [];\n B = [];\n flag = 0;\n return\nend\n\n% Product \nU = W1*W2;\n\n% Rank with fixed accuracy \nif (numel(S) ~= 0)\n I = find(abs(diag(S)/S(1)) >= tol);\nelse\n I = [];\nend\n \n% No values\nif isempty(I)\n A = zeros(m,0);\n B = zeros(0,n);\n flag = 1;\n\n% Accuracy not reached\nelseif (length(I) >= rk)\n A = [];\n B = [];\n flag = 0;\n \n% Low-rank representation\nelse\n A = U(:,I);\n B = S(I,I) * V(:,I)';\n flag = 1;\nend\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openHmx/hmxRSVD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6296435400305483}} {"text": "%IMM_UPDATE Interacting Multiple Model (IMM) Filter update step\n%\n% Syntax:\n% [X_i,P_i,MU,X,P] = IMM_UPDATE(X_p,P_p,c_j,ind,dims,Y,H,R)\n%\n% In:\n% X_p - Cell array containing N^j x 1 mean state estimate vector for\n% each model j after prediction step\n% P_p - Cell array containing N^j x N^j state covariance matrix for \n% each model j after prediction step\n% c_j - Normalizing factors for mixing probabilities\n% ind - Indices of state components for each model as a cell array\n% dims - Total number of different state components in the combined system\n% Y - Dx1 measurement vector.\n% H - Measurement matrices for each model as a cell array.\n% R - Measurement noise covariances for each model as a cell array.\n%\n% Out:\n% X_i - Updated state mean estimate for each model as a cell array\n% P_i - Updated state covariance estimate for each model as a cell array\n% MU - Estimated probabilities of each model\n% X - Combined state mean estimate\n% P - Combined state covariance estimate\n% \n% Description:\n% IMM filter measurement update step.\n%\n% See also:\n% IMM_PREDICT, IMM_SMOOTH, IMM_FILTER\n\n% History:\n% 01.11.2007 JH The first official version.\n%\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% $Id: imm_update.m 111 2007-11-01 12:09:23Z jmjharti $\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nfunction [X_i,P_i,MU,X,P] = imm_update(X_p,P_p,c_j,ind,dims,Y,H,R)\n % Number of models \n m = length(X_p);\n\n % Space for update state mean, covariance and likelihood of measurements\n X_i = cell(1,m);\n P_i = cell(1,m);\n lambda = zeros(1,m);\n\n % Update for each model\n for i = 1:m\n % Update the state estimates\n [X_i{i}, P_i{i}, K, IM, IS, lambda(i)] = kf_update(X_p{i},P_p{i},Y,H{i},R{i});\n end\n \n % Calculate the model probabilities\n MU = zeros(1,m); \n c = sum(lambda.*c_j);\n MU = c_j.*lambda/c;\n \n % Output the combined updated state mean and covariance, if wanted.\n if nargout > 3\n % Space for estimates\n X = zeros(dims,1);\n P = zeros(dims,dims);\n % Updated state mean\n for i = 1:m\n X(ind{i}) = X(ind{i}) + MU(i)*X_i{i};\n end\n % Updated state covariance\n for i = 1:m\n P(ind{i},ind{i}) = P(ind{i},ind{i}) + MU(i)*(P_i{i} + (X_i{i}-X(ind{i}))*(X_i{i}-X(ind{i}))');\n end\n end\n \n ", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/imm_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6296435252314471}} {"text": "% ASTROTIK by Francesco Santilli\n% R2BP (Restricted Two Bodies Problem)\n% Compute the Minimum Orbit Intersection Distance (MOID)\n%\n% Usage: [d,f] = moid(orbitA,orbitB)\n%\n% where: orbit = [p e i o w] = 3d orbit elements\n% orbit = [p e w] = 2d orbit elements\n% p = semi-latus rectum [L] (p>0)\n% e = eccentricity [-] (0<=e<1)\n% i = inclinaion [rad]\n% o = raan [rad]\n% w = argument of perifocus [rad]\n% d = MOID [L]\n% f = [fA fB] = true anomalies [rad]\n\nfunction [d,f] = moid(orbitA,orbitB)\n\n if ~(nargin == 2)\n error('Wrong number of input arguments.')\n end\n \n DA = check(orbitA,1);\n DB = check(orbitB,1);\n \n if DA ~= DB\n error('Wrong size of input arguments.')\n end\n \n if ~(DA==3 || DA==5)\n error('Wrong size of input arguments.')\n end\n d3 = (DA==5);\n \n % rotation matrix\n if d3\n [pA,eA,iA,oA,wA] = take(orbitA);\n [pB,eB,iB,oB,wB] = take(orbitB);\n RA = rotation([oA iA wA]);\n RB = rotation([oB iB wB]);\n RA = RA(1:2,:);\n RB = RB(1:2,:);\n else\n [pA,eA,wA] = take(orbitA);\n [pB,eB,wB] = take(orbitB);\n cwA = cos(wA);\n swA = sin(wA);\n cwB = cos(wB);\n swB = sin(wB);\n RA = [ cwA swA\n -swA cwA];\n RB = [ cwB swB\n -swB cwB];\n end\n \n if pA<=0 || pB<=0\n error('p must be a stricly positive value.')\n end\n \n if eA<0 || eB<0 || eA>=1 || eB>=1\n error('e must be in the range [0,1).')\n end\n \n L2 = pA^2+pB^2;\n f0 = [+1 +1 -1 -1 \n +1 -1 +1 -1]*pi/2;\n \n f = zeros(2,4);\n d = zeros(1,4);\n ef = zeros(1,4);\n \n opt = optimset('LargeScale','on','Display','off','GradObj','on',...\n 'TolX',eps,'TolFun',0,... % 'Hessian','on',\n 'MaxFunEvals',Inf,'MaxIter',Inf);\n for k = 1:4\n try\n [f(:,k),d(k),ef(k)] = fminunc(@fun,f0(:,k),opt);\n catch\n f(:,k) = [NaN NaN]';\n d(k) = NaN;\n ef(k) = 0;\n end\n end\n \n bad = (ef==0);\n f(:,bad) = [];\n d(:,bad) = [];\n if isempty(f)\n error('No solution found.')\n end\n \n d = sqrt(d*L2);\n f = mod(f+pi,2*pi)-pi;\n [d,k] = min(d);\n f = f(:,k(1))';\n \n function [F,FF,FFF] = fun(f)\n\n fA = f(1);\n fB = f(2);\n\n cA = cos(fA);\n cB = cos(fB);\n sA = sin(fA);\n sB = sin(fB);\n\n rA = pA/(1+eA*cA);\n rB = pB/(1+eB*cB);\n\n A = rA*[cA sA]*RA;\n B = rB*[cB sB]*RB;\n \n D = A-B;\n F = D*D' / L2;\n \n if nargout > 1\n\n kA = rA^2/pA;\n kB = rB^2/pB;\n \n GA = [-sA eA+cA]*RA;\n GB = [-sB eB+cB]*RB;\n \n FA = 2*kA*D*GA';\n FB = -2*kB*D*GB';\n FF = [FA; FB] / L2;\n \n if nargout > 2\n\n kAA = 2*kA^2/rA*eA*sA;\n kBB = 2*kB^2/rB*eB*sB;\n\n GAA = -[cA sA]*RA;\n GBB = -[cB sB]*RB;\n\n FAA = 2*(kAA*D*GA' + kA*D*GAA' + kA^2*GA*GA');\n FBB = -2*(kBB*D*GB' + kB*D*GBB' + kB^2*GB*GB');\n FAB = -2*kA*kB*GA*GB';\n\n FFF = [FAA FAB\n FAB FBB] / L2;\n \n end\n end\n \n %fprintf('%.20f %.20f -> %.20f\\n',f',F);\n \n end\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/27308-astrotik-1-0/orbits/moid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6296435171856389}} {"text": "% Copyright Andrew Binning 2013\n% Please feel free to use and modify this code as you see if fit. If you\n% use this code in any academic work, please cite \n% Andrew Binning, 2013.\n% \"Underidentified SVAR models: A framework for combining short and long-run restrictions with sign-restrictions,\"\n% Working Paper 2013/14, Norges Bank.\nfunction C = generateDraw(C,k)\n%==========================================================================\n% Generates a draw that is consistent with the shock variance/covariance\n% matrix. Based on Juan F. Rubio-Ramirez & Daniel F. Waggoner & Tao Zha, 2010.\n% \"Structural Vector Autoregressions: Theory of Identification and\n% Algorithms for Inference,\" Review of Economic Studies, Oxford University Press, vol. 77(2), pages 665-696.\n%\n% inputs:\n% C = initial impact matrix, usually from the cholesky decomposition of the\n% forecast error variance decomposition\n% k = number of dependent variables\n% \n% outputs:\n% C = new draw of the short run impact matrix\n%==========================================================================\n\nnewmatrix = randn(k,k);\n\n[Q,R] = qr(newmatrix);\n\nfor ii = 1:k\n if R(ii,ii)<0\n Q(:,ii) = -Q(:,ii);\n end\nend\n\nC = C*Q;", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/generateDraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6296412437427538}} {"text": "% Log-harmonic scale\n%\n% Inputs\n% Hb : Below this harmonic limit, the scale is linear\n% (similar to the mel scale which is linear below 1000Hz)\n% (e.g. 12)\n% Based on observation of the LF model, the asymptotic behavior of the\n% spectrum starts around the 12th harmonic (for the most tense voice)\n% Hmax : The maxmimum number of harmonic considered during synthesis\n% (e.g. 256)\n% order : The reduced number of phase coefficients (e.g. 24)\n%\n% Outputs\n% hsl : The log-harmonic scale\n%\n% Copyright (c) 2013 University of Crete - Computer Science Department(UOC-CSD)/ \n% Foundation for Research and Technology-Hellas - Institute\n% of Computer Science (FORTH-ICS)\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% Jonas Ballani for the bezier curve (see nested function)\n%\n\nfunction hsl = hlin2hlog(Hb, Hmax, order)\n\n % The last compressed coef (i.e. order) corresponds to a given Hmax\n\n % Use linear scale below Hb (higher coefs will be overwritten)\n hsl = 1:Hmax;\n\n % Build a Bezier curve to start with a linear scale and finish smoothly\n % at (Hmax,order)\n p(1,:) = [Hb, Hb];\n p(2,:) = [order, order];\n p(3,:) = [Hmax, order];\n t = 0:0.01:1;\n [X,Y,p_bez] = CASTELJAU(0,1,p,t);\n hsl(Hb+1:end) = interp1(p_bez(:,1), p_bez(:,2), (Hb+1):Hmax);\n\n if 0\n hs = 1:Hmax;\n plot(hs, hsl, 'k');\n\n hold on;\n keyboard\n end\n\nreturn\n\n\nfunction [X,Y,val] = CASTELJAU(a,b,p,y)\n\n % function val = CASTELJAU(a,b,p,y)\n %\n % INPUT: a Linke Intervallgrenze\n % b Rechte Intervallgrenze\n % p Stützstellen (nx2-Matrix)\n % y Auswertungspunkte (Spaltenvektor)\n %\n % OUTPUT: val Werte des Bezierpolynoms an y (mx2-Matrix)\n %\n % Date: 2007-11-05\n % Author: Jonas Ballani\n\n % Notes from degottex@csd.uoc.gr:\n % From bezier.zip\n % From http://m2matlabdb.ma.tum.de/download.jsp?MC_ID=7&SC_ID=8&MP_ID=480\n % No license or copyright specified.\n\n n = size(p,1);\n m = length(y);\n T = zeros(n,n);\n val = zeros(m,2);\n X(:,1) = p(:,1);\n Y(:,1) = p(:,2);\n\n for j = 1:m\n for i = 2:n\n X(i:n,i) = (b-y(j))/(b-a)*X(i-1:n-1,i-1) + (y(j)-a)/(b-a)*X(i:n,i-1);\n Y(i:n,i) = (b-y(j))/(b-a)*Y(i-1:n-1,i-1) + (y(j)-a)/(b-a)*Y(i:n,i-1);\n end\n val(j,1) = X(n,n);\n val(j,2) = Y(n,n);\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/vocoder/hmpd/private/hlin2hlog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6296412361668804}} {"text": "function [ output ] = FW_T( par)\n\n% this function implements Frank-Wolfe-thresholding method\n% 0.5*norm(Omega.*(L+S-M), 'fro')^2 + lambda_1 ||L||_* + lambda_2 ||S||_1\n%\n%\n%% Cun Mu and John Wright, Mar '14\n\nM = par.M; % data matrix\n[m,n] = size(M);\n\nepsilon = 10^-3; compare = 0; % by default (if no specification)\nif isfield(par, 'epsilon') epsilon = par.epsilon; end\nlambda_1 = par.lambda_1;\nlambda_2 = par.lambda_2;\niter = par.iter;\ndisplay = par.display;\nmethod = par.method; % power or exact\nOmega = par.Omega; \nrho = sum(sum(Omega))/m/n;\n%% FW-T method\n\n% initialization\nL = zeros(m,n); S = zeros(m,n);\nt_1 = 0; t_2 = 0;\n\nU_1 = 0.5*norm(M,'fro')^2/lambda_1; % initial rough guess\nU_2 = 0.5*norm(M,'fro')^2/lambda_2; % initial rough guess\n\nhistory = 0; % to store the values of each iteration\ntic\n%% full observation scenario\n%if ~isfield(par, 'Omega')\nif rho == 1\n fprintf('full observation. \\n');\n history(1) = norm(M,'fro')^2/2;\n temp = L + S - M; % gradient\n count = 0;\n for k = 1: iter\n \n if k>=2\n if abs(history(k)-history(k-1))/history(k-1)= ev\n V_L = 0; V_t_1 = 0;\n else\n V_L = U_1*D_L; V_t_1 = U_1;\n end\n \n [mag ind] = max(vec(abs(temp)));\n j = floor((ind-1)/m)+1; i = mod(ind-1,m)+1;\n sign_ = sign(temp(i,j));\n D_S = zeros(m,n);\n D_S(i,j) = -sign_;\n \n if lambda_2 >= mag\n V_S = 0; V_t_2 = 0;\n else\n V_S = U_2*D_S; V_t_2 = U_2;\n end\n \n H = zeros(2,2);\n temp_1 = V_L-L; temp_2 = V_S-S; % temp = L + S - M;\n H(1,1) = norm(temp_1, 'fro')^2;\n H(2,2) = norm(temp_2, 'fro')^2;\n H(1,2) = sum(sum(temp_1.*temp_2));\n H(2,1) = H(1,2);\n f = zeros(1,2);\n f(1) = sum(sum(temp_1.*temp));\n f(2) = sum(sum(temp_2.*temp));\n f = f + [lambda_1*(V_t_1-t_1), lambda_2*(V_t_2-t_2)];\n \n % using QP solvers\n lb = zeros(2,1);\n ub = [1;1];\n options.Display = 'off';\n options.TolFun = 10^-5;\n x = quadprog(H,f,[],[],[],[],lb,ub,[],options);\n x = quadprog(H,f,[],[],[],[],lb,ub,[],options);\n\n \n \n %----------------------- update L and S --------------------------%\n alpha = x(1);\n beta = x(2);\n L = (1-alpha)*L + alpha*V_L; t_1 = t_1 + alpha*(V_t_1-t_1);\n S = (1-beta)*S + beta*V_S; t_2 = t_2 + beta*(V_t_2-t_2);\n \n %------------------------ thresholding----------------------------%\n \n temp_3 = M-L;\n \n S = max(temp_3 - lambda_2, 0);\n S = S + min(temp_3 + lambda_2, 0);\n \n t_2 = sum(sum(abs(S)));\n \n %----------- update U_1 and U_2 to a better esitmate -------------%\n temp = L + S - M;\n history(k+1) = norm(temp,'fro')^2/2+lambda_1*t_1+lambda_2*t_2;\n U_1 = min(history(k+1)/lambda_1,U_1);\n U_2 = min(history(k+1)/lambda_2,U_2);\n \n end\n \nend\n\n%% partial observation scenario\nif rho<1\n fprintf('partial observation. \\n');\n temp = Omega.*(L + S - M); % gradient\n history(1) = norm(temp,'fro')^2/2+lambda_1*t_1+lambda_2*t_2;\n count = 0;\n \n for k = 1: iter\n \n if k>=2\n if abs(history(k)-history(k-1))*2/history(1)= ev\n V_L = 0; V_t_1 = 0;\n else\n V_L = U_1*D_L; V_t_1 = U_1;\n end\n \n [mag ind] = max(vec(abs(temp)));\n j = floor((ind-1)/m)+1; i = mod(ind-1,m)+1;\n sign_ = sign(temp(i,j));\n D_S = zeros(m,n);\n D_S(i,j) = -sign_;\n \n if lambda_2 >= mag\n V_S = 0; V_t_2 = 0;\n else\n V_S = U_2*D_S; V_t_2 = U_2;\n end\n \n \n %--------------------- use QP (exact search) ---------------------%\n H = zeros(2,2);\n temp_1 = Omega.*(V_L-L); temp_2 = Omega.*(V_S-S); % temp = L + S - M;\n H(1,1) = norm(temp_1, 'fro')^2;\n H(2,2) = norm(temp_2, 'fro')^2;\n H(1,2) = sum(sum(temp_1.*temp_2));\n H(2,1) = H(1,2);\n f = zeros(1,2);\n f(1) = sum(sum(temp_1.*temp));\n f(2) = sum(sum(temp_2.*temp));\n f = f + [lambda_1*(V_t_1-t_1), lambda_2*(V_t_2-t_2)];\n \n % using QP solvers\n lb = zeros(2,1);\n ub = [1;1];\n options.Display = 'off';\n options.TolFun = 10^-5;\n x = quadprog(H,f,[],[],[],[],lb,ub,[],options);\n x = quadprog(H,f,[],[],[],[],lb,ub,[],options);\n \n \n \n %----------------------- update L and S --------------------------%\n alpha = x(1);\n beta = x(2);\n L = (1-alpha)*L + alpha*V_L; t_1 = t_1 + alpha*(V_t_1-t_1);\n S = (1-beta)*S + beta*V_S; t_2 = t_2 + beta*(V_t_2-t_2);\n \n %------------------------ thresholding----------------------------%\n temp_3 = S-Omega.*(L+S-M);;\n S = max(temp_3 - lambda_2, 0);\n S = S + min(temp_3 + lambda_2, 0);\n t_2 = norm(vec(S),1);\n \n %----------- update U_1 and U_2 to a better esitmate -------------%\n temp = Omega.*(L + S - M); % gradient\n history(k+1) = norm(temp,'fro')^2/2+lambda_1*t_1+lambda_2*t_2;\n U_1 = min(history(k)/lambda_1,U_1);\n U_2 = min(history(k)/lambda_2,U_2);\n \n end\n \nend\ntoc\n%% output\noutput.L = L;\noutput.S = S;\noutput.hist = history;\noutput.iter = k;\nend\n\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/rpca/FW-T/FW_T.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6296107959960556}} {"text": "function [T]=affineTransformationMatrixDirect(V1,V2)\n\n%%\n%Force input to 3D\nif size(V1,2)==2\n V1(:,3)=0; \nend\n\nif size(V2,2)==2\n V2(:,3)=0; \nend\n\n%Expand to nx4\nV1_M=V1;\nV1_M(:,4)=1; \nV2_M=V2;\nV2_M(:,4)=1; \n\n%Get transformation using left devide\nT=(V1_M\\V2_M)';\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/affineTransformationMatrixDirect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6296107912055428}} {"text": "% Calculate the value of lambda so that if lambda >= lambdamax, the TVD\n% functional solved by l1pwc is minimized by the trivial constant\n% solution x = mean(y). This can then be used to determine a useful range\n% of values of lambda, for example.\n%\n% Usage:\n% lambdamax = l1pwclmax(y)\n%\n% Input arguments:\n% - y Original signal to denoise, size N x 1.\n%\n% Output arguments:\n% - lambdamax Value of at which x = mean(y) is the output of the l1pwc\n% function.\n%\n% (c) Max Little, 2010. If you use this code for your research, please\n% cite:\n% M.A. Little, Nick S. Jones (2010)\n% \"Sparse Bayesian Step-Filtering for High-Throughput Analysis of Molecular\n% Machine Dynamics\", in 2010 IEEE International Conference on Acoustics,\n% Speech and Signal Processing, 2010, ICASSP 2010 Proceedings.\n% \n\nfunction lambdamax = ML_l1pwclmax(y)\n\nnarginchk(1,1);\ny = y(:);\nN = length(y);\nM = N - 1;\n\n% Construct sparse operator matrices\nI1 = speye(M,M);\nO1 = spalloc(M,1,M);\nD = [I1 O1]-[O1 I1];\n\nDDT = D*D';\nDy = D*y;\n\nlambdamax = max(abs(DDT\\Dy));\n\nend", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/Max_Little/steps_bumps_toolkit/ML_l1pwclmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6295990768543226}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MATLAB Code for %\n% %\n% Multi-Objective Particle Swarm Optimization (MOPSO) %\n% Version 1.0 - Feb. 2011 %\n% %\n% According to: %\n% Carlos A. Coello Coello et al., %\n% \"Handling Multiple Objectives with Particle Swarm Optimization,\" %\n% IEEE Transactions on Evolutionary Computation, Vol. 8, No. 3, %\n% pp. 256-279, June 2004. %\n% %\n% Developed Using MATLAB R2009b (Version 7.9) %\n% %\n% Programmed By: S. Mostapha Kalami Heris %\n% %\n% e-Mail: sm.kalami@gmail.com %\n% kalami@ee.kntu.ac.ir %\n% %\n% Homepage: http://www.kalami.ir %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction G=CreateHypercubes(costs,ngrid,alpha)\n\n nobj=size(costs,1);\n \n empty_grid.Lower=[];\n empty_grid.Upper=[];\n G=repmat(empty_grid,nobj,1);\n \n for j=1:nobj\n \n min_cj=min(costs(j,:));\n max_cj=max(costs(j,:));\n \n dcj=alpha*(max_cj-min_cj);\n \n min_cj=min_cj-dcj;\n max_cj=max_cj+dcj;\n \n gx=linspace(min_cj,max_cj,ngrid-1);\n \n G(j).Lower=[-inf gx];\n G(j).Upper=[gx inf];\n \n end\n\nend", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/美赛A题常见代码/多目标粒子群优化算法代码/CreateHypercubes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6295990654445419}} {"text": "function imgOut = ConvertXYZtoYxy(img, inverse)\n%\n% imgOut = ConvertxXYZtoYxy(img, inverse)\n%\n%\n% Input:\n% -img: image to convert from XYZ to Yxy or from Yxy to XYZ.\n% -inverse: takes as values 0 or 1. If it is set to 0 the\n% transformation from XYZ to Yxy is applied, otherwise\n% the transformation from Yxy to XYZ.\n%\n% Output:\n% -imgOut: converted image in Yxy or XYZ.\n%\n% Copyright (C) 2013 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\ncheck3Color(img);\n[r, c, col] = size(img);\nimgOut = zeros(r, c, col);\n\nif(inverse == 0)%forward transform \n norm = zeros(r, c);\n for i=1:3\n norm = norm + img(:,:,i);\n end\n \n imgOut(:,:,1) = img(:,:,2);\n \n imgOut(:,:,2) = img(:,:,1) ./ (norm);\n imgOut(:,:,3) = img(:,:,2) ./ (norm);\nend\n\nif(inverse == 1)%inverse transform\n Y_over_y = img(:,:,1) ./ img(:,:,3); \n imgOut(:,:,1) = Y_over_y .* img(:,:,2);\n imgOut(:,:,2) = img(:,:,1);\n imgOut(:,:,3) = Y_over_y .* (1.0 - img(:,:,2) - img(:,:,3));\nend\n\nimgOut = RemoveSpecials(imgOut);\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/ColorSpace/ConvertXYZtoYxy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.6294687664229804}} {"text": "function [Va, success] = dcpf(B, Pbus, Va0, ref, pv, pq)\n%DCPF Solves a DC power flow.\n% [VA, SUCCESS] = DCPF(B, PBUS, VA0, REF, PV, PQ) solves for the bus\n% voltage angles at all but the reference bus, given the full system\n% B matrix and the vector of bus real power injections, the initial\n% vector of bus voltage angles (in radians), and column vectors with\n% the lists of bus indices for the swing bus, PV buses, and PQ buses,\n% respectively. Returns a vector of bus voltage angles in radians.\n%\n% See also RUNDCPF, RUNPF.\n\n% MATPOWER\n% Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n% by Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Nacional de Colombia\n% and Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% constant\nVa_threshold = 1e5; %% arbitrary threshold on |Va| for declaring failure\n\n%% initialize result vector\nVa = Va0;\nsuccess = 1; %% successful by default\n\n%% set up to trap non-singular matrix warnings\n[lastmsg, lastid] = lastwarn;\nlastwarn('');\n\n%% update angles for non-reference buses\nVa([pv; pq]) = B([pv; pq], [pv; pq]) \\ ...\n (Pbus([pv; pq]) - B([pv; pq], ref) * Va0(ref));\n\n[msg, id] = lastwarn;\n%% Octave is not consistent in assigning proper warning id, so we'll just\n%% check for presence of *any* warning\nif ~isempty(msg) || max(abs(Va)) > Va_threshold\n success = 0;\nend\n\n%% restore warning state\nlastwarn(lastmsg, lastid);\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/dcpf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6294268875886627}} {"text": "function [Detect] = cfar_ca1D_square(Xcube,noiseWin,guardLen,Pfa,wrapMode,ord_stat)\nN = noiseWin*2;\nalpha = N*(Pfa^(-1/N)-1);\nalpha_oneside = noiseWin*(Pfa^(-1/noiseWin)-1);\nXcube = Xcube.^2;\nXlength = length(Xcube);\nDetect = [];\nnumOfDet = 0;\n% ord_stat = 0.7;\n% if not CAOS-CFAR, set ord_stat = 1\n\nif wrapMode == 0 %%% disabled warpped mode\n for i = 1:Xlength\n if i < noiseWin+guardLen+1 %%% one-sided comparision for left section\n Xcube_select = sort(Xcube(i+guardLen+1:i+guardLen+noiseWin), 'descend');\n num_filter = round(length(Xcube_select) * (1-ord_stat));\n noiseWin_len = noiseWin - num_filter;\n if num_filter > 0\n Xcube_select(1:num_filter) = 0;\n end\n noise_estimate = sum(Xcube_select)/noiseWin_len;\n if Xcube(i) > alpha_oneside*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n elseif i < Xlength-noiseWin-guardLen+1 %%% two-sided comparison for middle section \n Xcube_select = sort(Xcube(i+guardLen+1:i+guardLen+noiseWin), 'descend');\n Xcube_select2 = sort(Xcube(i-guardLen-noiseWin:i-guardLen-1), 'descend');\n num_filter = round(length(Xcube_select) * (1-ord_stat));\n noiseWin_len = noiseWin - num_filter;\n if num_filter > 0\n Xcube_select(1:num_filter) = 0;\n Xcube_select2(1:num_filter) = 0;\n end\n noise_estimate = (sum(Xcube_select) + sum(Xcube_select2))/(2*noiseWin_len); \n if Xcube(i) > alpha*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n else %%% one-sided comparision for right section\n Xcube_select = sort(Xcube(i-guardLen-noiseWin:i-guardLen-1), 'descend');\n num_filter = round(length(Xcube_select) * (1-ord_stat));\n noiseWin_len = noiseWin - num_filter;\n if num_filter > 0\n Xcube_select(1:num_filter) = 0;\n end\n noise_estimate = sum(Xcube_select)/noiseWin_len;\n if Xcube(i) > alpha_oneside*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n end\n end\nelse %%% enabled wrapped mode\n for i = 1:Xlength\n if i < noiseWin+guardLen+1 %%% two-sided comparision for left section with wrap\n %%% discuss the wrap scenario\n if i <= guardLen\n noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...\n + sum(Xcube(Xlength+i-guardLen-noiseWin:Xlength+i-guardLen-1)))/N;\n else \n noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...\n + sum(Xcube(Xlength+i-guardLen-noiseWin:Xlength))+sum(Xcube(1:i-1-guardLen)))/N;\n end\n \n if Xcube(i) > alpha*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n \n elseif i < Xlength-noiseWin-guardLen+1 %%% two-sided comparison for middle section\n noise_estimate = (sum(Xcube(i+guardLen+1:i+guardLen+noiseWin))...\n + sum(Xcube(i-guardLen-noiseWin:i-guardLen-1)))/N;\n if Xcube(i) > alpha*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n \n else %%% two-sided comparision for right section with wrap\n if i >= Xlength-guardLen+1\n noise_estimate = (sum(Xcube(i-guardLen-noiseWin:i-guardLen-1))...\n + sum(Xcube(guardLen+i-Xlength+1:guardLen+i-Xlength+noiseWin)))/N;\n else\n noise_estimate = (sum(Xcube(i-guardLen-noiseWin:i-guardLen-1))...\n + sum(Xcube(guardLen+i+1:Xlength))+sum(Xcube(1:noiseWin-Xlength+i+guardLen)))/N;\n end\n \n if Xcube(i) > alpha*noise_estimate\n numOfDet = numOfDet + 1;\n Detect(1,numOfDet) = i; %%% index\n Detect(2,numOfDet) = Xcube(i); %%% object power\n Detect(3,numOfDet) = noise_estimate; %%% estimated noise\n end\n end\n end\nend\nend", "meta": {"author": "Xiangyu-Gao", "repo": "mmWave-radar-signal-processing-and-microDoppler-classification", "sha": "3d59968ed7059e96a8a5befe32ecb34e49f291bd", "save_path": "github-repos/MATLAB/Xiangyu-Gao-mmWave-radar-signal-processing-and-microDoppler-classification", "path": "github-repos/MATLAB/Xiangyu-Gao-mmWave-radar-signal-processing-and-microDoppler-classification/mmWave-radar-signal-processing-and-microDoppler-classification-3d59968ed7059e96a8a5befe32ecb34e49f291bd/modules/detection/cfar_ca1D_square.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.629335638829703}} {"text": "%This file will generate the library we prepared for the MMK example.\n% Last Updated: 2019/04/22\n% Coded By: K\n\nfunction [Data,Sym_Struct]=SINDyLib(X,dX,u,Highest_Poly_Order,Highest_Trig_Order,Highest_U_Order,Highest_dPoly_Order)\n%% First get the size of the X matrix, determin the data length and the number of variables we have.\n[Data_Length,Variable_Number]=size(X);\n[~,Variable_Number_dX]=size(dX);\n[~,Variable_Number_u]=size(u);\n%Also create the symbolic variable\nSymbol=sym('z',[Variable_Number,1]);\nSymbol_dX=sym('dz',[Variable_Number,1]);\nSymbol_u=sym('u',[Variable_Number_u,1]);\n\n%Now according the Highest Polynomial Order entered, we will calculate the data matrix.\nData=[];\nIndex=1;\n\n%% First calculate the polynomial term\n%Order zero:\nIndex=1;\nData(:,Index)=ones(Data_Length,1);\nSym_Struct{1,Index}=1;\n\n\n%Order One:\nif Highest_Poly_Order>=1\n for i=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=X(:,i);\n Sym_Struct{1,Index}=Symbol(i,1);\n end\nend\n\n%Order Two:\nif Highest_Poly_Order>=2\n for i=1:Variable_Number\n for j=i:Variable_Number\n Index=Index+1;\n Data(:,Index)=X(:,i).*X(:,j);\n Sym_Struct{1,Index}=Symbol(i,1)*Symbol(j,1);\n end\n end\nend\n\n%Order Three:\nif Highest_Poly_Order>=3\n for i=1:Variable_Number\n for j=i:Variable_Number\n for k=j:Variable_Number\n Index=Index+1;\n Data(:,Index)=X(:,i).*X(:,j).*X(:,k);\n Sym_Struct{1,Index}=Symbol(i,1)*Symbol(j,1)*Symbol(k,1);\n end\n end\n end\nend\n\n%Order Four:\nif Highest_Poly_Order>=4\n for i=1:Variable_Number\n for j=i:Variable_Number\n for k=j:Variable_Number\n for pi=k:Variable_Number\n Index=Index+1;\n Data(:,Index)=X(:,i).*X(:,j).*X(:,k).*X(:,pi);\n Sym_Struct{1,Index}=Symbol(i,1)*Symbol(j,1)*Symbol(k,1)*Symbol(pi,1);\n end\n end\n end\n end\nend\n\n%% Then add the Trigonometric Function in the output data:\n\n%Order One:\nif Highest_Trig_Order>=1\n for i=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i));\n Sym_Struct{1,Index}=sin(Symbol(i,1));\n end\n for i=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i));\n Sym_Struct{1,Index}=cos(Symbol(i,1));\n end\nend\n\n%Order Two:\nif Highest_Trig_Order>=2\n for i=1:Variable_Number\n for j=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i)+X(:,j));\n Sym_Struct{1,Index}=sin(Symbol(i,1)+Symbol(j,1));\n end\n end\n for i=1:Variable_Number\n for j=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)+X(:,j));\n Sym_Struct{1,Index}=cos(Symbol(i,1)+Symbol(j,1));\n end\n end\n %\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i)-X(:,j));\n Sym_Struct{1,Index}=sin(Symbol(i,1)-Symbol(j,1));\n end\n end\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)-X(:,j));\n Sym_Struct{1,Index}=cos(Symbol(i,1)-Symbol(j,1));\n end\n end\n %\n for i=1:Variable_Number\n for j=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i)-2*X(:,j));\n Sym_Struct{1,Index}=sin(Symbol(i,1)-2*Symbol(j,1));\n end\n end\n %\n for i=1:Variable_Number\n for j=1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)-2*X(:,j));\n Sym_Struct{1,Index}=cos(Symbol(i,1)-2*Symbol(j,1));\n end\n end\nend\n\n%Order Three:\nif Highest_Trig_Order>=3\n %\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)-X(:,j)).^2;\n Sym_Struct{1,Index}=cos(Symbol(i,1)-Symbol(j,1))^2;\n end\n end\n %\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i)-X(:,j)).^2;\n Sym_Struct{1,Index}=sin(Symbol(i,1)-Symbol(j,1))^2;\n end\n end\nend\n\n%Order Four\nif Highest_Trig_Order>=4\n %\n for i=1:Variable_Number\n for j=i:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(2*X(:,i)-2*X(:,j)).*X(:,i).^2;\n Sym_Struct{1,Index}=sin(2*Symbol(i,1)-2*Symbol(j,1))*Symbol(i,1)^2;\n end\n end\n %\n for i=1:Variable_Number\n for j=i:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(2*X(:,i)-2*X(:,j)).*X(:,i).^2;\n Sym_Struct{1,Index}=cos(2*Symbol(i,1)-2*Symbol(j,1))*Symbol(i,1)^2;\n end\n end\n %\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=sin(X(:,i)-X(:,j)).*X(:,i).^2;\n Sym_Struct{1,Index}=sin(Symbol(i,1)-Symbol(j,1))*Symbol(i,1)^2;\n end\n end\n %\n for i=1:Variable_Number\n for j=i+1:Variable_Number\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)-X(:,j)).*X(:,i).^2;\n Sym_Struct{1,Index}=cos(Symbol(i,1)-Symbol(j,1))*Symbol(i,1)^2;\n end\n end\n %\n for i=1:Variable_Number\n j=2;\n Index=Index+1;\n Data(:,Index)=cos(X(:,i)-X(:,j)).*sin(X(:,i));\n Sym_Struct{1,Index}=cos(Symbol(i,1)-Symbol(j,1))*sin(Symbol(i,1));\n end\nend\n\npin=Index;\n\n%% From here, we add the dX*Theta elements in our data.\nif Highest_dPoly_Order>=1\n for j=1:Variable_Number_dX\n for k=1:pin\n Index=Index+1;\n Data(:,Index)=dX(:,j).*Data(:,k);\n Sym_Struct{1,Index}=Symbol_dX(j,1)*(Sym_Struct{1,k});\n end\n end\nend\n\n%% Frome here, we add the u*Theta elements in our data\nif Highest_U_Order>=1\n for j=1:Variable_Number_u\n for k=1:pin\n Index=Index+1;\n Data(:,Index)=u(:,j).*Data(:,k);\n Sym_Struct{1,Index}=Symbol_u(j,1)*(Sym_Struct{1,k});\n end\n end\nend\n\n", "meta": {"author": "dynamicslab", "repo": "SINDy-PI", "sha": "42799b8e5a7585e400aa4bc3c83cfd659046cbb4", "save_path": "github-repos/MATLAB/dynamicslab-SINDy-PI", "path": "github-repos/MATLAB/dynamicslab-SINDy-PI/SINDy-PI-42799b8e5a7585e400aa4bc3c83cfd659046cbb4/Comparison/NoiseSensitivity/Michaelis-Menten kinetics/Functions/SINDyLib.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899664, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6293356288923596}} {"text": "function x = english_word_length_cdf_inv ( cdf )\n\n%*****************************************************************************80\n%\n%% ENGLISH_WORD_LENGTH_CDF_INV inverts the English Word Length CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 August 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Henry Kucera, Winthrop Francis,\n% Computational Analysis of Present-Day American English,\n% Brown University Press, 1967.\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Output, integer X, the corresponding word length for which\n% CDF(X-1) < CDF <= CDF(X)\n%\n word_length_max = 27;\n\n pdf_vec = [ ...\n 0.03160, ...\n 0.16975, ...\n 0.21192, ...\n 0.15678, ...\n 0.10852, ...\n 0.08524, ...\n 0.07724, ...\n 0.05623, ...\n 0.04032, ...\n 0.02766, ...\n 0.01582, ...\n 0.00917, ...\n 0.00483, ...\n 0.00262, ...\n 0.00099, ...\n 0.00050, ...\n 0.00027, ...\n 0.00022, ...\n 0.00011, ...\n 0.00006, ...\n 0.00005, ...\n 0.00002, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001, ...\n 0.00001 ];\n pdf_sum = 0.99997;\n\n if ( cdf < 0.0 || 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ENGLISH_WORD_LENGTH_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'ENGLISH_WORD_LENGTH_CDF_INV - Fatal error!' );\n end\n\n cum = 0.0;\n\n for j = 1 : word_length_max\n\n cum = cum + pdf_vec(j);\n\n if ( cdf <= cum / pdf_sum )\n x = j;\n return\n end\n\n end\n\n x = word_length_max;\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/english_word_length_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6292319073417569}} {"text": "function [f] = fact(n)\n%FACT Vectorized Factorial function\n%\n%usage: f = fact(n)\n%\n%tested under version 5.3.1\n%\n% This function computes the factorial of \n% the elements of N.\n% N can be any size but must contain\n% Real, Non-Negative, Integers.\n%\n% This routine is much more robust than\n% the built in FACTORIAL function.\n%\n%see also: Gamma, Prod, Factorial, Binomial\n\n%Paul Godfrey\n%pgodfrey@conexant.com\n%8-23-00\n\n[row,col]=size(n);\nn=n(:);\n\nf=NaN*n;\n\npp=find(imag(n)==0 & real(n)>=0 & round(n)==n);\n%find integer values\nnn=n(pp);\nff=zeros(length(pp),1);\n\ns=1;\np=[];\nif ~isempty(nn)\n p=find(nn==0);\nend\nif ~isempty(p)\n ff(p)=s;\nend\n\n%upper limit here depends upon realmax\nif ~isempty(nn)\nfor k=1:170\n s=s*k;\n%empty=scalar warning\n p=find(nn==k);\n if ~isempty(p)\n ff(p)=s;\n end\nend\nend\n\np=find(nn>170);\nif ~isempty(p)\n ff(p)=Inf;\nend\n\nf(pp)=ff;\nf=reshape(f,row,col);\n\nreturn\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/978-special-functions-math-library/fact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6292318875764613}} {"text": "% Test script for solving the 2D advection\nGlobals2D;\n\n% Generate simple mesh\nfilename = 'Maxwell025.neu';\n\n[Nv, VX, VY, K, EToV] = MeshReaderGambit2D(filename);\nNfaces = 3;\n[EToE,EToF] = tiConnect2D(EToV);\nBCType = Wall*(EToE==((1:K)'*ones(1,Nfaces)));\n\n% Build mesh \nNorder = ceil(10*rand(K,1));\n\n% Set up arbitrary order elements mesh\n[pinfo] = BuildPNonCon2D(Norder, K, VX, VY, EToV, BCType);\n\n% Set initial conditions\nmmode = 1; nmode = 1;\n\nx = []; y = [];\nfor N1=1:max(Norder)\n pinf = pinfo(N1);\n x(pinf.ids) = pinf.x;\n y(pinf.ids) = pinf.y;\nend\nx = x'; y = y';\nEz = sin(mmode*pi*x).*sin(nmode*pi*y);\nHx = zeros(size(x)); Hy = zeros(size(x));\n\n% Solve Problem for exactly one period\nFinalTime = 1;\n[Hx,Hy,Ez,time] = MaxwellPNonCon2D(pinfo, Hx,Hy,Ez,FinalTime);\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/Codes2D/MaxwellPNonConDriver2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6292232668603315}} {"text": "% ALS Completion\n% as described in \n% \n% Michael Steinlechner, Riemannian optimization for high-dimensional tensor completion,\n% Technical report, March 2015, revised December 2015. \n% To appear in SIAM J. Sci. Comput. \n%\n\n% TTeMPS Toolbox. \n% Michael Steinlechner, 2013-2016\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\nfunction [X,cost,test,stats] = completion_als( A_Omega, Omega, A_Gamma, Gamma, X, opts )\n\t\n if ~isfield( opts, 'maxiter'); opts.maxiter = 100; end\n if ~isfield( opts, 'tol'); opts.tol = 1e-6; end\n if ~isfield( opts, 'reltol'); opts.reltol = 1e-6; end\n\n\tn = X.size;\n\tr = X.rank;\n d = X.order;\n\t\n\tcost = zeros(2*opts.maxiter,1);\n\ttest = zeros(2*opts.maxiter,1);\n\n norm_A_Omega = norm( A_Omega );\n norm_A_Gamma = norm( A_Gamma );\n\n X = orthogonalize( X, 1 );\n\n t = tic;\n stats.time = [0];\n stats.conv = false;\n\n\tfor i = 1:opts.maxiter\n \n % ===================\n % FORWARD SWEEP:\n % ===================\n fprintf(1,'Currently optimizing core: ')\n for mu = 1:d-1\n fprintf(1,'%i ', mu)\n X.U{mu} = solve_least_squares( A_Omega, Omega, X, mu );\n X = orth_at( X, mu, 'left' );\n end\n\t\tcost(2*i-1) = sqrt(2*func(A_Omega, X, Omega)) / norm_A_Omega;\n\t\t\n\n if cost(2*i-1) < opts.tol \n disp(sprintf('CONVERGED AFTER %i HALF-SWEEPS. Rel. residual smaller than %0.3g', ...\n 2*i-1, opts.tol))\n stats.conv = true;\n cost = cost(1:2*i-1,1);\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i-1) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n test = test(1:2*i-1,1);\n break\n end\n\n if i > 1\n reltol = abs(cost(2*i-1) - cost(2*i-2)) / cost(2*i-1);\n if reltol < opts.reltol\n disp(sprintf('No more progress in gradient change, but not converged after %i half-sweeps. ABORTING!. \\nRelative change is smaller than %0.3g', ...\n i, opts.reltol))\n stats.conv = false;\n cost = cost(1:2*i-1,1);\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i-1) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n test = test(1:2*i-1,1);\n break\n end\n end\n\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i-1) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n t = tic;\n\n fprintf(1,'\\nFinished forward sweep.\\n Cost: %e\\n Test: %e\\n', cost(2*i-1), test(2*i-1) );\n % ===================\n % BACKWARD SWEEP:\n % ===================\n fprintf(1,'Currently optimizing core: ')\n for mu = d:-1:2\n fprintf(1,'%i ', mu)\n X.U{mu} = solve_least_squares( A_Omega, Omega, X, mu );\n X = orth_at( X, mu, 'right' );\n end\n\n\t\tcost(2*i) = sqrt(2*func(A_Omega, X, Omega)) / norm_A_Omega;\n\t\t\n\n if cost(2*i) < opts.tol\n disp(sprintf('CONVERGED AFTER %i HALF-SWEEPS. Rel. residual smaller than %0.3g', ...\n 2*i, opts.tol))\n stats.conv = true;\n cost = cost(1:2*i,1);\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n test = test(1:2*i,1);\n break\n end\n \n if i > 1\n reltol = abs(cost(2*i) - cost(2*i-1)) / cost(2*i);\n if reltol < opts.reltol\n disp(sprintf('No more progress in gradient change, but not converged after %i half-sweeps. ABORTING!. \\nRelative change is smaller than %0.3g', ...\n 2*i, opts.reltol))\n stats.conv = false;\n cost = cost(1:2*i,1);\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n test = test(1:2*i,1);\n break\n end\n end\n\n stats.time = [stats.time stats.time(end)+toc(t)];\n test(2*i) = sqrt(2*func(A_Gamma, X, Gamma)) / norm_A_Gamma;\n t = tic;\n fprintf(1,'\\nFinished backward sweep.\\n Cost: %e\\n Test: %e\\n', cost(2*i), test(2*i) );\n \n \n disp('_______________________________________________________________')\n end\n\n % This is to match original shape of stats.time, since we artificially start w/ [0]\n % for consistency in how we count time\n stats.time = stats.time(2:end);\n\nend\n\n\nfunction res = func(A_Omega, X, Omega)\n\tres = 0.5*norm( A_Omega - X(Omega) )^2;\nend\n\n\nfunction res = solve_least_squares( A_Omega, Omega, X, mu )\n\n n = X.size;\n d = X.order;\n r = X.rank;\n \n [jmu,idx] = sort(Omega(:,mu),'ascend');\n Omega = Omega(idx,:);\n A_Omega = A_Omega(idx);\n \n C = cell(1,d);\n for i=1:d\n C{i} = permute( X.U{i}, [1 3 2]);\n end\n res = zeros( size(C{mu}) );\n\n %B = zeros(size(Omega,1), r(mu)*r(mu+1));\n\n %imu = 1;\n %for sample = 1:size(Omega,1)\n\n % L = 1;\t\t\n % for i = 1:mu-1\n % L = L * C{i}(:,:,Omega(sample,i));\n % end\n\n % R = 1;\n % for i = d:-1:mu+1\n % R = C{i}(:,:,Omega(sample,i)) * R;\n % end\n % \n % %B(sample,:) = kron(R',L);\n % B(sample,:) = reshape( L'*R', 1, r(mu)*r(mu+1) );\n %end\n\n B = als_solve_mex( n, r, C, Omega', mu)';\n\n for i = 1:X.size(mu)\n idx = find(jmu == i);\n\n if isempty(idx) \n error('No samples for this slice!')\n end\n res(:,:,i) = reshape(B(idx,:)\\A_Omega(idx), r(mu), r(mu+1));\n end\n \n \n res = permute( res, [1 3 2] );\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/ttfixedrank/TTeMPS_1.1/algorithms/completion/completion_als.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6291268685766398}} {"text": "function C = exp(X,p)\n%EXP Long exponential function\n%\n% C = exp(X,p)\n%\n%for long number X. Input parameter p is optional; if specified,\n%approximate accuracy of C approximately p decimals, otherwise that of X.\n%Input X must be less than beta.\n%\n\n% written 12/30/98 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n INTLAB_LONG_BETA = getappdata(0,'INTLAB_LONG_BETA');\n INTLAB_LONG_LOGBETA = getappdata(0,'INTLAB_LONG_LOGBETA');\n \n % convert decimal precision in beta-digits\n if nargin==2\n longprecision(p);\n p = ceil( p/log10(INTLAB_LONG_BETA) );\n else\n p = size(X.mantissa,2) + 1;\n end\n\n if any( X.exponent>1 )\n error('exponent too big for long exponential')\n end\n\n index = ( X.exponent>0 );\n if any( index )\n large = 1;\n E = zeros(size(X.sign));\n while any(index)\n E(index) = E(index) + 1;\n X(index) = X(index)/2;\n index = ( X.exponent>0 );\n end\n else\n large = 0;\n end\n\n C = 1 + X;\n T = X;\n i = 1;\n while 1\n i = i+1;\n T = T * X / i;\n if all( T.exponent<-p )\n if isequal( longinit('ErrorTerm',0) , 'WithErrorTerm' )\n C.error = errorupdate( 1 , C.error , 0 , 1 , 1 , -p );\n end\n break\n end\n C = C + T;\n end\n\n if large\n index = ( E~=0 );\n while any(index)\n C(index) = C(index)*C(index);\n E(index) = E(index) - 1;\n index = ( E~=0 );\n end\n end\n \n if rndold\n setround(rndold)\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/long/@long/exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6291268685766398}} {"text": "function redoxsteady\n% Steady state redox zones\n% using MATLAB ode \n%\n% $Ekkehard Holzbecher $Date: 2006/03/31 $\n%--------------------------------------------------------------------------\nL = 100; % length [m]\nv = 1; % velocity [m/s]\nD = 0.2; % diffusivity [m*m/s]\nlambda = 0.01; % organic carbon degradation parameter [1/m] \nk1 = [0.1; 1; 0.9]; % 1. Michaelis-Menten parameter\nk2 = [0.035; 1; 1]; % 2. Michaelis-Menten parameter [kg/m*m*m]\nk3 = [3.5e-3; 1]; % inhibition coefficient [kg/m*m*m]\ncorg = 1; % organic carbon concentration at interface \ncin = [4; 3; 0.001]; % interface concentrations [kg/m*m*m]\nN = 100; % number of nodes \n\n%----------------------execution-------------------------------------------\n\nx = linspace(0,L,N);\nsolinit = bvpinit (x,[cin; zeros(3,1)]);\nsol = bvp4c(@redox,@bcs,solinit,odeset,D,v,lambda,k1,k2,k3,corg,cin);\n\n%---------------------- graphical output ----------------------------------\n\nplot (x,corg*exp(-lambda*x),sol.x,sol.y(1:3,:));\nlegend ('C_{org}','O_2','NO_2','Mn'); grid;\n\n%----------------------functions------------------------------\nfunction dydx = redox(x,y,D,v,lambda,k1,k2,k3,corg,cin)\n\nc0 = corg*exp(-lambda*x);\nmonod = k1.*(y(1:3)>0).*y(1:3)./(k2+y(1:3)); \nmonod(3) = k1(3); \ninhib = k3./(k3+y(1:2));\ndydx = zeros (6,1);\ndydx(1) = y(4);\ndydx(4) = (v*y(4)+c0*monod(1))/D;\ndydx(2) = y(5);\ndydx(5) = (v*y(5)+c0*monod(2)*inhib(1))/D;\ndydx(3) = y(6);\ndydx(6) = (v*y(6)-c0*monod(3)*inhib(1)*inhib(2))/D;\n\nfunction res = bcs (ya,yb,D,v,lambda,k1,k2,k3,corg,cin)\nres = [ya(1:3)-cin; yb(4:6)-zeros(3,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/15646-environmental-modeling/redoxsteady.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6291257524218657}} {"text": "% nufft_table_test.m\n\n\n%\n% 3D test\n%\nif 1\n\tif ~isvar('s.t'), disp 'precompute structure'\n%\t\tktype = 'minmax:kb';\n\t\tktype = 'kaiser';\n\t\tJd = [3 4 3];\n\t\tNd = [10 8 9];\n\t\tLd = [2^8 2^7 2^7];\n\t\tKd = 2 * Nd;\n%\t\tn_shift = zeros(size(Nd)); disp 'easy: 0 shift'\n\t\tn_shift = [3 7 2]; % stress it\n\n\t\tgam = 2*pi ./ Kd;\n\t\tk1 = linspace(-2*Kd(1), 2*Kd(1), 21)';\n\t\tk2 = linspace(-2*Kd(2), 2*Kd(2), 18)';\n\t\tk3 = linspace(-2*Kd(3), 2*Kd(3), 23)';\n\t\t[kk1 kk2 kk3] = ndgrid(k1, k2, k3);\n\t\tom = [gam(1)*kk1(:) gam(2)*kk2(:) gam(3)*kk3(:)];\n\n\t\ttic\n\t\ts.p = nufft_init(om, Nd, Jd, Kd, n_shift, ktype);\n\t\tprintf('pre time init %g', toc)\n\n\t\ttic\n\t\ts.t = nufft_init(om, Nd, Jd, Kd, n_shift, 'table', Ld, ktype);\n\t\tprintf('tab time init %g', toc)\n\tend\n\n\t% 3D forward direction\n\tif 1, disp '3D forward'\n%\t\tx = [1:Nd(1)]'*triang(Nd(2))';\n\t\trand('state', 0);\n\t\tx = rand(Nd);\n\t\tx = zeros(Nd);\n\t\tx(4, 2, 3) = 1;\n\n\t\ttic\n\t\tY.d = dtft(x, om, n_shift); % exact\n\t\tprintf('dtft3 time %g', toc)\n\n\t\ttic\n\t\tY.p = nufft(x, s.p);\n\t\tprintf('pre time nufft %g', toc)\n\t\tprintf('pre max%%diff = %g', max_percent_diff(Y.d, Y.p))\n\n\t\ttic\n\t\tY.t = nufft(x, s.t);\n\t\tprintf('tab time nufft %g', toc)\n\t\tprintf('tab max%%diff = %g', max_percent_diff(Y.d, Y.t))\n\t\tprintf('tab vs pre max%%diff = %g', max_percent_diff(Y.p, Y.t))\n\n\t\tif 1\n\t\t\tclf\n\t\t\tim(231, k1, k2, abs(Y.p - Y.d), 'pre'), cbar\n\t\t\tim(232, k1, k2, abs(Y.t - Y.d), 'tab'), cbar\n\t\t\tim(233, k1, k2, abs(Y.t - Y.p), 'tab-pre'), cbar\n\t\tend\n\tend\n\n\t% 3D adjoint\n\tif 1, disp '3D adjoint'\n\t\tX = [1:s.t.M]' + 1i * ones(s.t.M,1);\n\n\t\ttic\n\t\tc.d = dtft_adj(X, om, Nd, n_shift); % exact\n\t\tprintf('dtft time adj %g', toc)\n\t\ttic\n\t\tc.p = nufft_adj(X, s.p);\n\t\tprintf('pre time nufft adj %g', toc)\n\t\ttic\n\t\tc.t = nufft_adj(X, s.t);\n\t\tprintf('tab time nufft adj %g', toc)\n\n\t\tprintf('pre max%%diff = %g', max_percent_diff(c.d, c.p))\n\t\tprintf('tab max%%diff = %g', max_percent_diff(c.d, c.t))\n\t\tprintf('tab vs pre max%%diff = %g', max_percent_diff(c.p, c.t))\n\n\t\tif 1\n\t\t\tim(234, abs(c.p - c.d), 'pre adj err'), cbar\n\t\t\tim(235, abs(c.t - c.d), 'tab adj err'), cbar\n\t\t\tim(236, abs(c.t - c.p), 'tab-pre adj'), cbar\n\t\tend\n\tend\nreturn\nend\n\n\n%\n% 2D test\n%\nif 1\n\tif ~isvar('s.t'), disp 'precompute structure'\n%\t\tktype = 'minmax:kb';\n\t\tktype = 'kaiser';\n\t\tJd = [4 5];\n\t\tNd = [20 16];\n\t\tLd = [2^12 2^13];\n\t\tKd = 2 * Nd;\n%\t\tn_shift = zeros(size(Nd));\n\t\tn_shift = [3 7]; % stress it\n\n\t\tgam = 2*pi ./ Kd;\n\t\tk1 = linspace(-2*Kd(1), 2*Kd(1), 51)';\n\t\tk2 = linspace(-2*Kd(2), 2*Kd(2), 81)';\n\t\t[kk1 kk2] = ndgrid(k1, k2);\n\t\tom = [gam(1)*kk1(:) gam(2)*kk2(:)];\n\n\t\ttic\n\t\ts.p = nufft_init(om, Nd, Jd, Kd, n_shift, ktype);\n\t\tprintf('pre time init %g', toc)\n\n\t\ttic\n\t\ts.t = nufft_init(om, Nd, Jd, Kd, n_shift, 'table', Ld, ktype);\n\t\tprintf('tab time init %g', toc)\n\tend\n\n\t% forward direction\n\tif 1, disp 'test forward'\n\t\tx = [1:Nd(1)]'*triang(Nd(2))';\n\n\t\ttic\n\t\tY.d = dtft2(x, om, n_shift); % exact\n\t\tprintf('dtft2 time %g', toc)\n\n\t\ttic\n\t\tY.p = nufft(x, s.p);\n\t\tprintf('pre time nufft %g', toc)\n\t\tprintf('pre max%%diff = %g', max_percent_diff(Y.d, Y.p))\n\n\t\ttic\n\t\tY.t = nufft(x, s.t);\n\t\tprintf('tab time nufft %g', toc)\n\t\tprintf('tab max%%diff = %g', max_percent_diff(Y.d, Y.t))\n\t\tprintf('tab vs pre max%%diff = %g', max_percent_diff(Y.p, Y.t))\n\n\t\tclf\n\t\tim(231, k1, k2, abs(Y.p - Y.d), 'pre'), cbar\n\t\tim(232, k1, k2, abs(Y.t - Y.d), 'tab'), cbar\n\t\tim(233, k1, k2, abs(Y.t - Y.p), 'tab-pre'), cbar\n\tend\n\n\t% 2D adjoint\n\tif 1, disp '2D adjoint'\n\t\tX = [1:s.t.M]' + 1i * ones(s.t.M,1);\n\n\t\ttic\n\t\tc.d = dtft2_adj(X, om, Nd(1), Nd(2), n_shift); % exact\n\t\tprintf('dtft2 time adj %g', toc)\n\t\ttic\n\t\tc.p = nufft_adj(X, s.p);\n\t\tprintf('pre time nufft adj %g', toc)\n\t\ttic\n\t\tc.t = nufft_adj(X, s.t);\n\t\tprintf('tab time nufft adj %g', toc)\n\n\t\tprintf('pre max%%diff = %g', max_percent_diff(c.d, c.p))\n\t\tprintf('tab max%%diff = %g', max_percent_diff(c.d, c.t))\n\t\tprintf('tab vs pre max%%diff = %g', max_percent_diff(c.p, c.t))\n\n\t\tim(234, abs(c.p - c.d), 'pre adj err'), cbar\n\t\tim(235, abs(c.t - c.d), 'tab adj err'), cbar\n\t\tim(236, abs(c.t - c.p), 'tab-pre adj'), cbar\n\tend\nreturn\nend\n\n\n%\n% 1D test\n%\nif ~isvar('s.t')\n%\tktype = 'minmax:kb';\n\tktype = 'kaiser';\n\tJd = 4;\n\tNd = 32;\n\tLd = 2^14; % table over-sampling\n\tKd = 2 * Nd;\n\tn_shift = zeros(size(Nd));\n\t% n_shift = Nd/2;\n\n\tgam = 2*pi ./ Kd;\n\tkv = 2*Kd;\n\tkv = linspace(-kv, kv, 1001)';\n\tom = gam * kv;\n\n\ttic\n\ts.p = nufft_init(om, Nd, Jd, Kd, n_shift, ktype);\n\tprintf('pre time init %g', toc)\n\n\ttic\n\ts.t = nufft_init(om, Nd, Jd, Kd, n_shift, 'table', Ld, ktype);\n\tprintf('tab time init %g', toc)\nend\n\n\nif 0\n\tramp = [1:Nd]';\n\n\tY.dr = dtft(ramp, om, n_shift);\n\tY.de = dtft(eye(Nd), om, n_shift);\n\tprintf('dtft max%%diff = %g', max_percent_diff(Y.dr,Y.de*ramp))\n\n\tY.pr = nufft(ramp, s.p);\n\tY.pe = nufft(eye(Nd), s.p);\n\tprintf('pre max%%diff = %g', max_percent_diff(Y.pr,Y.pe*ramp))\n\n\tprintf('max%%diff = %g', max_percent_diff(Y.dr,Y.pr))\n\tprintf('max%%diff = %g', max_percent_diff(Y.de,Y.pe))\n\n\te = Y.pr - Y.dr;\n\tclf, plot(kv, abs(e), 'c-')\n%\tclf, plot(kv, sum(abs(e),2), 'c-')\nreturn\nend\n\n% forward direction\nif 1\n\tx = [1:Nd]';\n\t% x = unitv(Nd, ii);\n\n\tY.d = dtft(x, om, n_shift); % exact\n\ttic\n\tY.p = nufft(x, s.p);\n\tprintf('pre time nufft %g', toc)\n\tprintf('pre max%%diff = %g', max_percent_diff(Y.d,Y.p))\n\n\ttic\n\tY.t = nufft(x, s.t);\n\tprintf('tab time nufft %g', toc)\n\tprintf('tab max%%diff = %g', max_percent_diff(Y.d, Y.t))\n\n\tclf\n\tsubplot(211)\n\tplot(kv, abs(Y.p - Y.d), 'c-'), title 'pre'\n\tsubplot(212)\n\tplot(kv, abs(Y.t - Y.d), 'y-'), title 'tab'\nprompt\nend\n\n% adjoint\nif 1\n\tX = [1:s.t.M]' + 1i * ones(size(om));\n\n\tc.d = dtft2_adj(X, [om 0*om], Nd(1), 1, [n_shift 0]); % exact\n\ttic\n\tc.p = nufft_adj(X, s.p);\n\tprintf('pre time nufft adj %g', toc)\n\ttic\n\tc.t = nufft_adj(X, s.t);\n\tprintf('tab time nufft adj %g', toc)\n\n\tprintf('pre nufft adj vs dtft adj max%%diff = %g', max_percent_diff(c.d,c.p))\n\tprintf('tab nufft adj vs dtft adj max%%diff = %g', max_percent_diff(c.d,c.t))\n\n\tclf\n\tnn = 0:Nd(1)-1;\n\tsubplot(211)\n\tplot(nn, abs(c.p - c.d) / mean(abs(c.d)), 'c-'), title 'pre'\n\tsubplot(212)\n\tplot(nn, abs(c.t - c.d) / mean(abs(c.d)), 'y-'), title 'tab'\nend\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@NUFFT/private/nufft_table_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6290450304128828}} {"text": "%% data association for every kalman filter (every object from previous frame)\nfunction [k, ocn, szn] = asc(k, ocn, szn)\nfor i = 1 : size(k, 2) % for every kalman filter\n[k(i).s, idx] = assoc(k(i).s, ocn); % apply data association\nk(i).sz = szn(:, idx);\nszn(:, idx) = [];\nocn(:, idx) = []; % eliminated checked objects from the new frame and go for\nend % associating remained objects to the next kalman filter\nend\n%% data association: 1. no object, 2. one object, 3. multiple objects\nfunction [s, idx] = assoc(s, ocn)\ncan = ocn(1 : 2, :); % candidates \npe = [s.x(1); s.x(3)]; % previous estimate (to do: replace with last prediction!)\ngate = 4; % gating: 7 \nidx = ((sum((can - repmat(pe, 1, size(can, 2)))... % indexes of objects inside the gate\n .^2)) .^0.5) < gate;\nif sum(idx) == 0 % 1. no object\ns.z = pe; % previous estimate/prediction!\nelseif sum(idx) == 1 % 2. one object\ns.z = can(:, idx); % associated object\nelseif sum(idx) > 1 % 3. multiple objects (take nearest object)\nidx = ((sum((can - repmat(pe, 1, size(can, 2)))... % index of the nearest object\n .^2)) .^0.5) == min((sum((can - repmat(pe...\n , 1, size(can, 2))) .^2)) .^0.5);\ns.z = can(:, idx); % associated object\nend\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/检测算法/moving_object_detection_2.5d_maps-master/25Ddatmo/25Ddatmo/asc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6290450279611473}} {"text": "function [ n_data, x, fx ] = bessel_y1_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BESSEL_Y1_VALUES returns some values of the Y1 Bessel function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% BesselY[1,x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 16;\n\n fx_vec = [ ...\n -0.6458951094702027E+01, ...\n -0.7812128213002887E+00, ...\n -0.1070324315409375E+00, ...\n 0.3246744247918000E+00, ...\n 0.3979257105571000E+00, ...\n 0.1478631433912268E+00, ...\n -0.1750103443003983E+00, ...\n -0.3026672370241849E+00, ...\n -0.1580604617312475E+00, ...\n 0.1043145751967159E+00, ...\n 0.2490154242069539E+00, ...\n 0.1637055374149429E+00, ...\n -0.5709921826089652E-01, ...\n -0.2100814084206935E+00, ...\n -0.1666448418561723E+00, ...\n 0.2107362803687351E-01 ];\n\n x_vec = [ ...\n 0.1E+00, ... \n 1.0E+00, ... \n 2.0E+00, ... \n 3.0E+00, ... \n 4.0E+00, ... \n 5.0E+00, ... \n 6.0E+00, ... \n 7.0E+00, ... \n 8.0E+00, ... \n 9.0E+00, ... \n 10.0E+00, ... \n 11.0E+00, ... \n 12.0E+00, ... \n 13.0E+00, ... \n 14.0E+00, ... \n 15.0E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/bessel_y1_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6289918535025149}} {"text": "function linpack_d_test18 ( )\n\n%*****************************************************************************80\n%\n%% TEST18 tests DPOFA and DPOSL.\n%\n% Discussion:\n%\n% DPOFA factors a positive definite symmetric matrix,\n% and DPOSL can solve a factored linear system.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 20;\n lda = n;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST18\\n' );\n fprintf ( 1, ' For a positive definite symmetric matrix,\\n' );\n fprintf ( 1, ' DPOFA computes the LU factors.\\n' );\n fprintf ( 1, ' DPOSL solves a factored linear system.\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Set the matrix A.\n%\n a(1:n,1:n) = 0.0;\n\n for i = 1 : n\n a(i,i) = 2.0;\n if ( 1 < i )\n a(i,i-1) = -1.0;\n end\n if ( i < n )\n a(i,i+1) = -1.0;\n end\n end\n%\n% Set the right hand side.\n%\n x = zeros ( n, 1 );\n\n for i = 1 : n\n x(i) = i;\n end\n \n b(1:n) = a(1:n,1:n) * x(1:n);\n%\n% Factor the matrix.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Factor the matrix.\\n' );\n\n [ a, info ] = dpofa ( a, lda, n );\n \n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Error, DPOFA returns INFO = %d\\n', info );\n return\n end\n%\n% Solve the linear system.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the linear system.\\n' );\n\n b = dposl ( a, lda, n, b );\n%\n% Print the result.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The first and last five entries of the solution:\\n' );\n fprintf ( 1, ' (Should be 1,2,3,4,5,...,n-1,n.)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n if ( i <= 5 | n-5 < i )\n fprintf ( 1, ' %6d %14f\\n', i, b(i) );\n end\n if ( i == 5 )\n fprintf ( 1, ' ...... ..............\\n' );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/linpack_d_test18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6289162700804103}} {"text": "function th_img = mmse7(inp,inp_map,s,n)\n[row col]=size(inp);\nth_img=zeros(row,col);\nth_img(1:(row/2^n),1:(col/2^n))=inp(1:(row/2^n),1:(col/2^n));\nfor i=n:-1:1\n a=inp((row/2^i)+1:(row/2^(i-1)),(col/2^i)+1:(col/2^(i-1))); %diagonal coefficients\n b=inp_map((row/2^i)+1:(row/2^(i-1)),(col/2^i)+1:(col/2^(i-1)));\n th_img((row/2^i)+1:(row/2^(i-1)),(col/2^i)+1:(col/2^(i-1)))=th(a,b,s);\n a=inp(1:(row/2^(i)),(col/2^i)+1:(col/2^(i-1))); %horizontal coefficients\n b=inp(1:(row/2^(i)),(col/2^i)+1:(col/2^(i-1)));\n th_img(1:(row/2^(i)),(col/2^i)+1:(col/2^(i-1)))=th(a,b,s);\n a=inp((row/2^i)+1:(row/2^(i-1)),1:(col/2^(i))); %vertical coefficients\n b=inp((row/2^i)+1:(row/2^(i-1)),1:(col/2^(i)));\n th_img((row/2^i)+1:(row/2^(i-1)),1:(col/2^(i)))=th(a,b,s);\nend\nend\nfunction y=th(inp,inp1,s)\n[row col]=size(inp);\nlambda=1/var(inp1(:));\ntest1=zeros(row+6,col+6);\ntest2=zeros(size(test1));\ntest1(4:end-3,4:end-3)=inp;\n[row col]=size(test1);\nfor i=4:row-3\n for j=4:col-3\n b=test1(i-3:i+3,j-3:j+3);\n% sigsq=max(0,((1/numel(b))*sum(sum(b.^2))-s));\n% lambda=1/sqrt(sigsq);\n A=numel(b)*(-1+sqrt(1+(8*lambda/numel(b)^2)*sum(sum(b.^2))));\n sig_cap_sq=max(0,(A/(4*lambda)-s));\n %test2(i,j)=(sqrt(2)*s)./sqrt(sigsq);\n test2(i,j)=(sig_cap_sq.*test1(i,j))./(sig_cap_sq+s);\n end\nend\ny=test2(4:row-3,4:col-3);\n% % c=(abs(inp)-test2(4:row-3,4:col-3));\n% % c(c<0)=0;\n% % y=sign(inp).*c;\n% [row col]=size(inp);\n% y(1:row/2^n,1:col/2^n)=inp(1:row/2^n,1:col/2^n);\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/VideoDenoising-master/matlab files/mmse7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6288388612502575}} {"text": "% [INPUT]\n% data = A float t-by-n matrix (-Inf,Inf) representing the model input.\n% tail = A string representing the target tail:\n% - 'L' for lower tail;\n% - 'U' for upper tail.\n% bw = An integer [21,252] representing the dimension of each rolling window (optional, default=252).\n% f = A float [0.05,0.20] representing the percentage of observations to be included in tails (optional, default=0.10).\n% pt = A float [0,1) representing the initial penantly term for underrepresented samples with respect to the bandwidth (optional, default=0.5).\n%\n% [OUTPUT]\n% chi = A float n-by-n-by-t matrix [0,1] representing the Chi coefficients.\n% chi_bar = A float n-by-n-by-t matrix [-1,1] representing the Chi Bar coefficients.\n%\n% [NOTES]\n% The bandwidth is automatically expanded as much as possible following an optimality criteria.\n\nfunction [chi,chi_bar] = asymptotic_tail_dependence(varargin)\n\n persistent ip;\n\n if (isempty(ip))\n ip = inputParser();\n ip.addRequired('data',@(x)validateattributes(x,{'double'},{'real' '2d' 'nonempty'}));\n ip.addRequired('tail',@(x)any(validatestring(x,{'L' 'U'})));\n ip.addOptional('bw',252,@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 21 '<=' 252 'scalar'}));\n ip.addOptional('f',0.10,@(x)validateattributes(x,{'double'},{'real' 'finite' '>=' 0.05 '<=' 0.2 'scalar'}));\n ip.addOptional('pt',0.5,@(x)validateattributes(x,{'double'},{'real' 'finite' '>=' 0 '<' 1 'scalar'}));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n [data,bw] = validate_input(ipr.data,ipr.bw);\n tail = ipr.tail;\n f = ipr.f;\n pt = ipr.pt;\n\n nargoutchk(1,2);\n\n [chi,chi_bar] = asymptotic_tail_dependence_internal(data,bw,tail,f,pt);\n\nend\n\nfunction [chi,chi_bar] = asymptotic_tail_dependence_internal(data,bw,tail,f,pt)\n\n up = isempty(getCurrentTask());\n\n [t,n] = size(data);\n\n c = nchoosek(1:n,2);\n c_len = size(c,1);\n\n dc = cell(c_len,2);\n\n for i = 1:c_len\n c_i = c(i,:);\n dc(i,:) = {c_i data(:,c_i)};\n end\n\n pt = [linspace(pt,1,bw).'; ones(t-bw,1)];\n\n dc_results = cell(c_len,2);\n\n if (up)\n parfor k = 1:c_len\n windows = extract_rolling_windows(dc{k,2},bw);\n\n chi_k = zeros(t,1);\n chibar_k = zeros(t,1);\n\n for w = 1:t\n dc_kw = windows{w};\n\n [chi_kw,chibar_kw] = calculate_coefficients(dc_kw,tail,f);\n chi_k(w) = chi_kw;\n chibar_k(w) = chibar_kw;\n end\n\n dc_results(k,:) = {(chi_k .* pt) (chibar_k .* pt)};\n end\n else\n for k = 1:c_len\n windows = extract_rolling_windows(dc{k,2},bw);\n\n chi_k = zeros(t,1);\n chibar_k = zeros(t,1);\n\n for w = 1:t\n dc_kw = windows{w};\n\n [chi_kw,chibar_kw] = calculate_coefficients(dc_kw,tail,f);\n chi_k(w) = chi_kw;\n chibar_k(w) = chibar_kw;\n end\n\n dc_results(k,:) = {(chi_k .* pt) (chibar_k .* pt)};\n end\n end\n\n en = eye(n);\n chi = repmat(en,1,1,t);\n chi_bar = repmat(en,1,1,t);\n\n for k = 1:c_len\n dc_k = dc{k,1};\n i = dc_k(1);\n j = dc_k(2);\n\n [chi_k,chibar_k] = deal(dc_results{k,:});\n chi(i,j,:) = chi_k;\n chi(j,i,:) = chi_k;\n chi_bar(i,j,:) = chibar_k;\n chi_bar(j,i,:) = chibar_k;\n end\n\n for i = 1:t\n nan_indices = isnan(data(i,:));\n\n if (any(nan_indices))\n chi(nan_indices,:) = NaN;\n chi(:,nan_indices) = NaN;\n\n chi_bar(nan_indices,:) = NaN;\n chi_bar(:,nan_indices) = NaN;\n end\n end\n\nend\n\nfunction [chi,chi_bar] = calculate_coefficients(data,tail,f)\n\n if (any(any(isnan(data),1)))\n chi = NaN;\n chi_bar = NaN;\n return;\n end\n\n t = size(data,1);\n t1 = t + 1;\n\n nu = max(round(t * f),1);\n nu1 = nu + 1;\n\n if (strcmp(tail,'L'))\n u1 = 1 - (tiedrank(data(:,1)) ./ t1);\n u2 = 1 - (tiedrank(data(:,2)) ./ t1);\n else\n u1 = tiedrank(data(:,1)) ./ t1;\n u2 = tiedrank(data(:,2)) ./ t1;\n end\n\n zs = -1 ./ log(u1);\n zt = -1 ./ log(u2);\n z = sort(min(zs,zt),'descend');\n\n if (nu == 1)\n eta = 0;\n else\n eta = sum(log(z(1:nu) ./ z(nu1)));\n end\n\n chi_bar = ((2 / nu1) * eta) - 1;\n sigma = (chi_bar + 1)^2 / nu1;\n ci = chi_bar + (norminv(0.975) * sigma^0.5);\n\n if (ci >= 1)\n chi = z(nu1) * (nu1 / t);\n else\n chi = 0;\n end\n\nend\n\nfunction [data,bw] = validate_input(data,bw)\n\n [t,n] = size(data);\n\n if (n < 2)\n error('The value of ''data'' is invalid. Expected input to be a matrix with at least 2 columns.');\n end\n\n nan_counts = sum(isnan(data),1);\n nan_threshold = round(t * 0.70,0);\n\n if (any(nan_counts > nan_threshold))\n error(['The value of ''data'' is invalid. Expected input to contain no more than 70% of NaN values (' num2str(nan_threshold) ') for each time series.']);\n end\n\n for i = 2:ceil(t / bw)\n bw_i = bw * i;\n\n if ((bw_i / t) >= 0.3)\n bw = bw_i;\n break;\n end\n end\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/asymptotic_tail_dependence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6286773728930908}} {"text": "function [C, Q] = procCosp(DATA, WINDOW_TYPE, WINDOW_SIZE, OVERLAP, FREQUENCY_RANGE, PHASE_CORRECTION)\n% [C, Q] = procCosp(DATA, WINDOW_TYPE, WINDOW_SIZE, OVERLAP, FREQUENCY_RANGE)\n%\n% This function computes cospectra and quadrature spectra on multivariate \n% data using Welch's method. For a better estimation, each tappering window \n% can be phase corrected according to its length and its position in data. \n%\n% Inputs:\n% - DATA --> matrix with the data (M samples by N channels matrix)\n% - WINDOW_TYPE --> (optionnal) string with the type of the window\n% - WINDOW_SIZE --> (optionnal) size of the window in number of samples \n% - OVERLAP --> (optionnal) percentage of the overlapping window (from 0 to 0.99)\n% - FREQUENCY_RANGE --> (optionnal) range of interesting frequencies to keep, \n% format must be [sample_rate min_frec max_frec]\n% - PHASE_CORRECTION--> (optionnal) correction of phase shift intrinsic to Welch's windows. \n% (1: correction, 0: no correction)\n%\n% Outputs:\n% - C --> cospectral matrix [N x N x f]\n% - Q --> quadrature matrix [N x N x f]\n%\n% History\n% First version: Jonas Chatel-Goldman @ GIPSA-Lab, 01/12/2011\n\n\n% default UI display\nif(nargin < 9) UIdisplay = 0; end\n% default correction\nif(nargin < 6) PHASE_CORRECTION = 0; end\n% default frequency range\nif(nargin < 5) FREQUENCY_RANGE = []; end\n% default overlapping\nif(nargin < 4) OVERLAP = .75; end\n% default windows size\nif(nargin < 3) WINDOW_SIZE = 128; end\n% default windows type\nif(nargin < 2) WINDOW_TYPE = 'hanning'; end\n\n% Adjust the window to the next pow of 2 (for the FFT)\nWINDOW_SIZE = 2 ^ nextpow2(WINDOW_SIZE);\n% Calculate the number of frequencies\nnumber_freqs = (WINDOW_SIZE / 2); % +1;\n\ns_data = size(DATA);\n\n\n% UI DISPLAY\nif(UIdisplay) h= waitbar(0,'Processing cospectrum...'); end\n\n%% Create the window from the inputs and preallocates memory\nswitch lower(WINDOW_TYPE)\n case 'hamming'\n win = hamming(WINDOW_SIZE);\n case 'hann'\n win = hann(WINDOW_SIZE);\n case 'hanning'\n win = hanning(WINDOW_SIZE);\n case 'blackman'\n win = blackman(WINDOW_SIZE);\n case 'barthannwin'\n win = barthannwin(WINDOW_SIZE);\n case 'blackmanharris'\n win = blackmanharris(WINDOW_SIZE);\n case 'bohmanwin'\n win = bohmanwin(WINDOW_SIZE);\n case 'chebwin'\n win = chebwin(WINDOW_SIZE);\n case 'gausswin'\n win = gausswin(WINDOW_SIZE);\n case 'kaiser'\n win = kaiser(WINDOW_SIZE);\n case 'nuttallwin'\n win = nuttallwin(WINDOW_SIZE);\n case 'parzenwin'\n win = parzenwin(WINDOW_SIZE);\n case 'tukeywin'\n win = tukeywin(WINDOW_SIZE);\n case 'rectangular'\n win = ones(WINDOW_SIZE,1);\n case 'flattopwin'\n win = flattopwin(WINDOW_SIZE);\n case 'welch'\n %win = welchwin(WINDOW_SIZE, 0);\n Nd2=(WINDOW_SIZE-1)/2;\n for i=1 : WINDOW_SIZE\n win(i)=1-((i-Nd2)/Nd2)^2;\n end\n win = win';\n otherwise\n disp('WARNING - Unknown window type!');\n disp('Switching to default window type : Hamming Window');\n win = hamming(WINDOW_SIZE);\nend\n\nif s_data(1) < WINDOW_SIZE\n error('Cospectra computation: data segment too short for this window length, consider changing frequency resolution');\nend\n\n\n% Calculate the number of windows because of the overlapping\nif(OVERLAP == 0)\n number_windows = floor(s_data(1) / WINDOW_SIZE);\nelse\n nbFullWin = floor(s_data(1)/WINDOW_SIZE); \n number_windows = 1 + (nbFullWin-1)/(1-OVERLAP) + floor((s_data(1)-((nbFullWin)*WINDOW_SIZE))/((1-OVERLAP)*WINDOW_SIZE));\nend\n\n\n% pre-allocation of memory \nS = zeros(s_data(2), s_data(2), number_freqs);\n\n%% Loop on all frequencies\nfor window_ix = 1 : number_windows\n \n % UI display\n if(UIdisplay) waitbar(window_ix/number_windows,h); end\n \n % time markers to select the data\n t1 = floor((window_ix-1) * (1-OVERLAP) * WINDOW_SIZE) +1; % marker of the beginning of the time window\n t2 = t1 + WINDOW_SIZE -1; % marker of the end of the time window\n \n % select current window and apodize it \n cdata = DATA(t1:t2, :) .* (win*ones(1,s_data(2)));\n\n % FFT calculation\n fdata = fft(cdata,WINDOW_SIZE) ./ number_windows; % complex data\n if(PHASE_CORRECTION == 1)\n fdata = fdata.*(exp(-sqrt(-1)*t1*( 0:(WINDOW_SIZE-1) )'/WINDOW_SIZE*2*pi)*ones(1,s_data(2)));\n end\n \n % Complexe cospectrum averaging over windows\n for f = 1 : number_freqs\n S(:,:,f) = S(:,:,f) + (fdata(f,:)' * fdata(f,:));\n end\nend\n\nC = real(S);\nQ = imag(S);\n\n\n% Adjust Frequency range to specified range (in case it is a parameter)\nif ~isempty(FREQUENCY_RANGE) \n if FREQUENCY_RANGE(3) <= (FREQUENCY_RANGE(1) / 2) \n Faxis = [0:(1/number_freqs):1-(1/number_freqs)];\n FindexMin = find(Faxis >= FREQUENCY_RANGE(2)/(FREQUENCY_RANGE(1)/2), 1);\n FindexMax = find(Faxis >= FREQUENCY_RANGE(3)/(FREQUENCY_RANGE(1)/2), 1);\n C = C(:, :, FindexMin:FindexMax);\n Q = Q(:, :, FindexMin:FindexMax);\n\n else \n % Assertion on frequency, to comply with Nyquist Theorem\n error('Frequency range exceeds data sampling rate in consideration of Shannon''s limitation.')\n end\nend\n\n% UI display\nif(UIdisplay) close(h); end", "meta": {"author": "alexandrebarachant", "repo": "covariancetoolbox", "sha": "f1c088566eda2b2b63857b6563d7be5525ea4768", "save_path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox", "path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox/covariancetoolbox-f1c088566eda2b2b63857b6563d7be5525ea4768/lib/estimation/procCosp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6286773469113257}} {"text": "function ll = composite_likelihood(S,data,indices)\n% Computes the negative of the composite normal loglikelihood (bivariate) for a K-dimensional array\n%\n% USAGE:\n% [LL] = composite_likelihood(S,DATA,INDICES)\n%\n% INPUTS:\n% S - K by K covariance matrix\n% DATA - Either a K by K matrix (e.g. outer-produces) or a 1 by K vector (e.g. returns)\n% INDICES - Q by 2 array of indices to use when computing the composite likleihood\n%\n% OUTPUTS:\n% LL - Composite likelihood\n% \n% COMMENTS:\n% This is a helper function for various multivariate GARCH models. A MEX file version of this file \n% is available which provides a large speed-up.\n%\n% See also DCC, SCALAR_VEC_VECH, BEKK, RARCH\n\nq = size(indices,1);\n[m,n] = size(data);\nlikConst = 3.67575413281869;\nll = 0;\nif m==n\n for k=1:q\n i = indices(k,1);\n j = indices(k,2);\n s11 = S(i,i);\n s12 = S(i,j);\n s22 = S(j,j);\n det = s11*s22-s12*s12;\n x11 = data(i,i);\n x12 = data(i,j);\n x22 = data(j,j);\n ll = ll + 0.5*(likConst + log(det) + (s22*x11 - 2*s12*x12 + s11*x22)/det)/q;\n end\nelse\n for k=1:q\n i = indices(k,1);\n j = indices(k,2);\n s11 = S(i,i);\n s12 = S(i,j);\n s22 = S(j,j);\n det = s11*s22-s12*s12;\n x11 = data(i)*data(i);\n x12 = data(i)*data(j);\n x22 = data(j)*data(j);\n ll = ll + 0.5*(likConst + log(det) + (s22*x11 - 2*s12*x12 + s11*x22)/det)/q;\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/distributions/composite_likelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6286164985794764}} {"text": "function [fx,dfdx,dfdp] = f_gen(Xt,Theta,ut,inF)\n\n% Generic evolution function (up to quadratic terms)\n\n% [fx,dfdx,dfdp] = f_gen(Xt,Theta,ut,inF)\n\ndeltat = inF.deltat;\nn = size(Xt,1);\nnc = factorial(n)./(factorial(2)*factorial(n-2));\nA = reshape(Theta(1:n^2),n,n);\nB = reshape(Theta(n^2+1:n*(2*n+nc)),n,n+nc);\n\nxij = zeros(n+nc,1);\nind = cell(n,1);\nind2 = zeros(n,1);\nk = 0;\nfor i=1:n\n for j=1:n\n if j >= i\n k = k+1;\n xij(k) = Xt(i).*Xt(j);\n if i == j\n ind2(i) = k;\n else\n ind{i} = [ind{i},k];\n ind{j} = [ind{j},k];\n end\n end\n end\nend\ndbxdx = zeros(n,n);\nfor i=1:n\n for j=1:n\n dbxdx(i,j) = 2*B(i,ind2(j)).*Xt(j) ...\n + B(i,ind{j})*Xt(setdiff(1:n,j));\n end\nend\n\nf = A*Xt + B*xij;\nfx = Xt + deltat.*f;\ndfdx = eye(n) + deltat*(A + dbxdx)';\n\ndfdp = zeros(n,n*(2*n+nc));\ndfdp(:,1:n^2) = kron(Xt',eye(n));\ndfdp(:,n^2+1:n*(2*n+nc)) = kron(xij',eye(n));\ndfdp = deltat*dfdp';\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/f_gen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6286164930066056}} {"text": "% Two-input NAND gate sizing (GP)\n% Boyd, Kim, Patil, and Horowitz, \"Digital circuit optimization\n% via geometric programming\"\n% Written for CVX by Almir Mutapcic 02/08/06\n% (a figure is generated)\n%\n% This is an example taken directly from the paper:\n%\n% Digital circuit optimization via geometrical programming\n% by Boyd, Kim, Patil, and Horowitz\n% Operations Research 53(6): 899-932, 2005.\n%\n% Solves the problem of choosing device widths w_i for the given\n% NAND2 gate in order to achive minimum Elmore delay for different\n% gate transitions, subject to limits on the device widths,\n% gate area, power, and so on. The problem is a GP:\n%\n% minimize D = max( D_1, ..., D_k ) for k transitions\n% s.t. w_min <= w <= w_max\n% A <= Amax, etc.\n%\n% where variables are widths w.\n%\n% This code is specific to the NAND2 gate shown in figure 19\n% (page 926) of the paper. All the constraints and the objective\n% are hard-coded for this particular circuit.\n\n%********************************************************************\n% problem data and hard-coded GP specs (evaluate all transitions)\n%********************************************************************\nN = 4; % number of devices\nCload = 12; % load capacitance\nVdd = 1.5; % voltage\n\n% device specs\nNMOS = struct('R',0.4831, 'Cdb',0.6, 'Csb',0.6, 'Cgb',1, 'Cgs',1);\nPMOS = struct('R',2*0.4831, 'Cdb',0.6, 'Csb',0.6, 'Cgb',1, 'Cgs',1);\n\n% maximum area and power specification\nwmin = 1;\n\n% varying parameters for the tradeoff curve\nNpoints = 25;\nAmax = linspace(5,45,Npoints);\nDopt = [];\n\ndisp('Generating the optimal tradeoff curve...')\nfor k = 1:Npoints\n fprintf(1,' Amax = %5.2f:', Amax(k));\n cvx_begin gp quiet\n % device width variables\n variable w(N)\n\n % device specs\n device(1:2) = PMOS; device(3:4) = NMOS;\n\n for num = 1:N\n device(num).R = device(num).R/w(num); %#ok\n device(num).Cdb = device(num).Cdb*w(num); %#ok\n device(num).Csb = device(num).Csb*w(num); %#ok\n device(num).Cgb = device(num).Cgb*w(num); %#ok\n device(num).Cgs = device(num).Cgs*w(num); %#ok\n end\n\n % capacitances\n C1 = sum([device(1:3).Cdb]) + Cload;\n C2 = device(3).Csb + device(4).Cdb;\n\n % input capacitances\n Cin_A = sum([ device([2 3]).Cgb ]) + sum([ device([2 3]).Cgs ]);\n Cin_B = sum([ device([1 4]).Cgb ]) + sum([ device([1 4]).Cgs ]);\n\n % resistances\n R = [device.R]';\n\n % area definition\n area = sum(w);\n\n % delays and dissipated energies for all six possible transitions\n % transition 1 is A: 1->1, B: 1->0, Z: 0->1\n D1 = R(1)*(C1 + C2);\n E1 = (C1 + C2)*Vdd^2/2;\n % transition 2 is A: 1->0, B: 1->1, Z: 0->1\n D2 = R(2)*C1;\n E2 = C1*Vdd^2/2;\n % transition 3 is A: 1->0, B: 1->0, Z: 0->1\n % D3 = C1*R(1)*R(2)/(R(1) + R(2)); % not a posynomial\n E3 = C1*Vdd^2/2;\n % transition 4 is A: 1->1, B: 0->1, Z: 1->0\n D4 = C1*R(3) + R(4)*(C1 + C2);\n E4 = (C1 + C2)*Vdd^2/2;\n % transition 5 is A: 0->1, B: 1->1, Z: 1->0\n D5 = C1*(R(3) + R(4));\n E5 = (C1 + C2)*Vdd^2/2;\n % transition 6 is A: 0->1, B: 0->1, Z: 1->0\n D6 = C1*R(3) + R(4)*(C1 + C2);\n E6 = (C1 + C2)*Vdd^2/2;\n\n % objective is the worst-case delay\n minimize( max( [D1 D2 D4] ) )\n subject to\n area <= Amax(k); %#ok\n w >= wmin; %#ok\n cvx_end\n % display and store computed values\n fprintf(1,' delay = %3.2f\\n',cvx_optval);\n Dopt = [Dopt cvx_optval]; %#ok\nend\n\n% plot the tradeoff curve\nplot(Dopt,Amax);\nxlabel('Dmin'); ylabel('Amax');\ndisp('Optimal tradeoff curve plotted.')\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/circuit_design/simple_NAND2_gate_design.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.628616485802941}} {"text": "%% Analyzing Neural Time Series Data\n% Matlab code for Chapter 2\n% Mike X Cohen\n% \n% This code accompanies the book, titled \"Analyzing Neural Time Series Data\" \n% (MIT Press). Using the code without following the book may lead to confusion, \n% incorrect data analyses, and misinterpretations of results. \n% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code.\n\n%% Figure 2.1\n\nload sampleEEGdata.mat\n\nnTrials = 6; % modifiable\n\nfigure\ndata = zeros(nTrials,EEG.pnts);\n\n% wavelet... more on this in Chapters 13 and 14\nwavetime = -1:1/EEG.srate:1;\nn_conv = length(wavetime)+EEG.pnts-1;\nwaveletfft = fft(exp(2*1i*pi*10.*wavetime) .* exp(-wavetime.^2./(2*(5/(2*pi*10))^2))/10,n_conv);\ndata10hz = zeros(nTrials,EEG.pnts);\n\nfor triali=1:nTrials\n \n % create single trial \"ERP\"\n data(triali,:) = .5*sin(2*pi*6.*EEG.times/1000 + 2*pi*triali/nTrials-pi) + randn(1,EEG.pnts)/6;\n % add non-phase-locked stimulus potential (note distributed phases in sine wave)\n data(triali,260:360) = data(triali,260:360) + sin(2*pi*10.*EEG.times(260:360)/1000 + 2*pi*triali/nTrials-pi) + randn(1,101)/5;\n \n \n % plot data from this trial\n subplot(nTrials,3,(triali-1)*3+1)\n plot(EEG.times,data(triali,:))\n set(gca,'xlim',[-250 850],'ylim',[-2.2 2.2])\n \n % plot ERP from trial 1 to current\n subplot(nTrials,3,(triali-1)*3+2)\n plot(EEG.times,mean(data(1:triali,:),1))\n set(gca,'xlim',[-250 850],'ylim',[-2.2 2.2])\n \n % convolve with 10 Hz wavelet (more on convolution in a few chapters...)\n convolution_result_fft = ifft(waveletfft.*fft(data(triali,:),n_conv)) * sqrt(5/(2*pi*10));\n convolution_result_fft = convolution_result_fft(floor(length(wavetime)/2)+1:end-floor(length(wavetime)/2));\n data10hz(triali,:) = abs(convolution_result_fft).^2;\n \n % plot 10 Hz power\n subplot(nTrials,3,(triali-1)*3+3)\n plot(EEG.times,mean(data10hz(1:triali,:),1))\n set(gca,'xlim',[-250 850],'ylim',[-.1 .8])\nend\n\n%% Figure 2.2\n% (This code involves performing convolution with a complex Morlet wavelet,\n% which you will learn about in Chapters 10-13.)\n\nsrate=1000;\n\ntime=(0:1/srate:10);\n\nDCoffset=-.5;\n\n% create multi-frequency signal\na = sin(2*pi*10.*time); % part 1 of signal (high frequency)\nb = .1*sin(2*pi*.3*time)+DCoffset; % part 2 of signal (low frequency)\n\ndata = a.*b; % combined signal\ndata = data + (2*sin(2*pi*3*time) .* sin(2*pi*.07*time)*.1+DCoffset);\n\n% morlet wavelet convolution (more on this in later chapters)\nnum_frex = 40;\nmin_freq = 2;\nmax_freq = 20;\n\nLdata = length(data);\nLtapr = length(data);\nLconv1 = Ldata+Ltapr-1;\nLconv = pow2(nextpow2(Lconv1));\n\nfrex=logspace(log10(min_freq),log10(max_freq),num_frex);\n\n% initialize\ntf=zeros(num_frex,length(data));\ndatspctra = fft(data,Lconv);\n\ns=4./(2*pi.*frex);\nt=-((length(data)-1)/2)/srate:1/srate:((length(data)-2)/2)/srate+1/srate;\n\nfor fi=1:length(frex)\n \n wavelet=exp(2*1i*pi*frex(fi).*t).*exp(-t.^2./(2*s(fi)^2));\n \n m = ifft(datspctra.*fft(wavelet,Lconv),Lconv);\n m = m(1:Lconv1);\n m = m(floor((Ltapr-1)/2):end-1-ceil((Ltapr-1)/2));\n \n tf(fi,:) = abs(m).^2;\nend\n\n\nfigure\n\nsubplot(221)\nplot(a)\nset(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);\ntitle('10 Hz signal, DC=0')\n\nsubplot(222)\nplot(b)\nset(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);\ntitle([ '.3 Hz signal, DC=' num2str(DCoffset) ])\n\nsubplot(223)\nplot(data)\nset(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);\ntitle('Time-domain signal')\n\nsubplot(224)\nimagesc(1:length(data),[],tf);\nset(gca,'xlim',[1 8]*1000,'ydir','normal','ytick',1:8:num_frex,'yticklabel',round(frex(1:8:end)),'xtick',0:1000:10000,'xticklabel',0:10)\ntitle('Time-frequency representation')\n\n\n%% Figure 2.3\n\nchan2plot = 'pz'; % you can pick any electrode (type {EEG.chanlocs.labels} for all electrodes)\n\n% compute ERP (time-domain trial average from selected electrode)\nerp = squeeze(mean(EEG.data(strcmpi(chan2plot,{EEG.chanlocs.labels}),:,:),3));\n\n\n% low-pass filter data (uses signal processing toolbox; you'll learn about\n% how filtering works in chapter 14. If you don't have the signal processing \n% toolbox, just comment out the next eight lines; they are not necessary.)\nnyquist = EEG.srate/2;\nfilter_cutoff = 40; % Hz\ntrans_width = 0.1; % transition width, in fraction of 1\n\nffrequencies = [ 0 filter_cutoff filter_cutoff*(1+trans_width) nyquist ]/nyquist;\nidealresponse = [ 1 1 0 0 ];\nfilterweights = firls(100,ffrequencies,idealresponse);\nfiltered_erp = filtfilt(filterweights,1,double(erp));\n\n\nfigure\n% plot ERP\nplot(EEG.times,filtered_erp,'k.-')\n\n% now down-sample and plot\ntimes2plot = dsearchn(EEG.times',(-200:40:1000)');\nhold on\nplot(EEG.times(1:5:end),filtered_erp(1:5:end),'mo-')\n\nset(gca,'xlim',[-200 1000],'ydir','r')\nxlabel('Time (ms)'), ylabel('Voltage (\\muV)')\ntitle([ 'ERP from electrode ' chan2plot ])\nlegend({'256 Hz';'50 Hz'})\n\n%%\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/chapter02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6285278948746498}} {"text": "function [pnt,jac] = nrbdeval(nurbs, dnurbs, tt) \n% Evaluation of the derivative NURBS curve or surface. \n% \n% [pnt, jac] = nrbdeval(crv, dcrv, tt) \n% [pnt, jac] = nrbdeval(srf, dsrf, {tu tv}) \n% \n% INPUTS: \n% \n% crv - original NURBS curve. \n% \n% srf - original NUBRS surface \n% \n% dcrv - NURBS derivative represention of crv \n% \n% dsrf - NURBS derivative represention of surface \n% \n% tt - parametric evaluation points \n% If the nurbs is a surface then tt is a cell \n% {tu, tv} are the parametric coordinates \n% \n% pnt - evaluated points. \n% jac - evaluated first derivatives (Jacobian). \n% \n% Examples: \n% \n% // Determine the first derivatives a NURBS curve at 9 points for 0.0 to \n% // 1.0 \n% tt = linspace(0.0, 1.0, 9); \n% dcrv = nrbderiv(crv); \n% [pnts,jac] = nrbdeval(crv, dcrv, tt); \n \n% D.M. Spink \n% Copyright (c) 2000. \n \nif ~isstruct(nurbs) \n error('NURBS representation is not structure!'); \nend \n \nif ~strcmp(nurbs.form,'B-NURBS') \n error('Not a recognised NURBS representation'); \nend \n \n[cp,cw] = nrbeval(nurbs, tt); \n \nif iscell(nurbs.knots) \n \n % NURBS structure represents a surface \n temp = cw(ones(3,1),:,:); \n pnt = cp./temp; \n \n [cup,cuw] = nrbeval(dnurbs{1}, tt); \n tempu = cuw(ones(3,1),:,:); \n jac{1} = (cup-tempu.*pnt)./temp; \n \n [cvp,cvw] = nrbeval(dnurbs{2}, tt); \n tempv = cvw(ones(3,1),:,:); \n jac{2} = (cvp-tempv.*pnt)./temp; \n \nelse \n \n % NURBS is a curve \n temp = cw(ones(3,1),:); \n pnt = cp./temp; \n \n % first derivative \n [cup,cuw] = nrbeval(dnurbs,tt); \n temp1 = cuw(ones(3,1),:); \n jac = (cup-temp1.*pnt)./temp; \n \nend \n \n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/nrbdeval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6284935245560033}} {"text": "function [jj,tx,j,a,v,p,tt]=profile3(t,j,acc,plt)\n\n% function [jj,tx,j,a,v,p,tt]=profile3(t,j,acc)\n%\n% Calculate symmetrical third order profiles from times: \n%\n% Inputs:\n%\n% t(1) = constant jerk phase duration\n% t(2) = constant acceleration phase duration (default 0)\n% t(3) = constant velocity phase duration (default 0)\n% \n% j = bound on jerk\n% acc = continuous time: accuracy for profiles: t(1)*acc = minimal timestep\n% discrete time: sample time\n%\n% Outputs:\n%\n% jj = derivative of jerk profile suitable for simulink \n%\n% tx = time sequence for plotting profiles\n% j = jerk profile\n% a = acceleration profile\n% v = velocity profile\n% p = position profile\n%\n% tt = 8 switching times for profile:\n%\n% 0 1 6 7 \n% .-. .-. \n% | | | | \n% | | 2 3 4 5 | | \n% '-'--.-.----.-.--' '--\n% | | | | \n% | | | | \n% '-' '-' \n%\n% Note: coinciding switching times are not removed \n\n%\n% Copyright 2004, Paul Lambrechts, The MathWorks, Inc.\n%\n\nif nargin < 3 || nargin > 4\n help profile3\n return\nend\nif nargin==3\n plt=1;\nend\n\nif length(t)==1 % min distance with max jerk\n tt= [0 1 1 2 2 3 3 4 ]*t;\n \nelseif length(t)==2 % constant acceleration phase\n tt= [0 1 1 2 2 3 3 4 ]*t(1) ...\n + [0 0 1 1 1 1 2 2 ]*t(2);\n \nelseif length(t)==3 % constant velocity phase\n tt= [0 1 1 2 2 3 3 4 ]*t(1) ...\n + [0 0 1 1 1 1 2 2 ]*t(2) ...\n + [0 0 0 0 1 1 1 1 ]*t(3) ;\nelse\n return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Generate Simulink look-up table\njt=[];\nfor i=1:8\n jt = [jt [1 1] * tt(i) ] ;\nend\njt = [jt 1.5*tt(8)];\n\njj = [jt ; [ 0 j j 0 0 -j -j 0 0 -j -j 0 0 j j 0 0 ] ];\n\nif plt==0 % no plot required\n tx=[];j=[];a=[];v=[];p=[]; % dummy outputs\n return\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Generate profiles for plotting\n\n% Determine continuous or discrete\nif max(abs( round(t/acc)-t/acc )) > 1e-12 % continuous\n\n disp('Calculating continuous time profiles')\n step = t(1)*acc;\n tx=0:step:1.2*tt(8);\n x=[];\n for i=0:step:1.2*tt(8)\n j=find(i<=jj(1,:));\n x=[x ; jj(2,j(1))];\n end\n j=x;\n a=cumsum(j)*step; \n v=cumsum(a)*step;\n p=cumsum(v)*step;\n\nelse % discrete\n \n disp('Calculating discrete time profiles')\n Ts=acc;\n ttest=[tt 1.5*tt(8)];\n len = round(1.2*tt(8)/Ts + 1); % length of profiles\n xj = zeros(len,1);\n xa = xj;\n xv = xj;\n xp = xj;\n xj(1) = j;\n tx=0:Ts:1.2*tt(8)+Ts/2;\n for time=Ts:Ts:(1.2*tt(8)+Ts/2)\n i = find( (time + Ts/2) <= ttest ); i = i(1)-1;\n k = round(time/Ts);\n if i==1 || i==7 \n xj(k+1) = j;\n elseif i==3 || i==5 \n xj(k+1) = -j;\n else\n xj(k+1) = 0;\n end\n xa(k+1) = xa(k) + xj(k)*Ts;\n xv(k+1) = xv(k) + xa(k)*Ts;\n xp(k+1) = xp(k) + xv(k)*Ts;\n end\n j=xj;a=xa;v=xv;p=xp;\n\nend\n\n%close all\n%figure\nsubplot(411);plot(tx,j,'k','LineWidth',1.5);hold on;plot([0 0],[-1 1]*max(j),'k--',[1 1]*max(tt),[-1 1]*max(j),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-1.1 1.1]*max(j)]);\ntitle('Third order trajectory profiles');ylabel('j [m/s3]');\nsubplot(412);plot(tx,a,'k','LineWidth',1.5);hold on;plot([0 0],[-1 1]*max(a),'k--',[1 1]*max(tt),[-1 1]*max(a),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-1.1 1.1]*max(a)]);\nylabel('a [m/s2]');\nsubplot(413);plot(tx,v,'k','LineWidth',1.5);hold on;plot([0 0],[0 1]*max(v),'k--',[1 1]*max(tt),[0 1]*max(v),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-0.1 1.1]*max(v)]);\nylabel('v [m/s]');\nsubplot(414);plot(tx,p,'k','LineWidth',1.5);hold on;plot([0 0],[0 1]*max(p),'k--',[1 1]*max(tt),[0 1]*max(p),'k--','LineWidth',1.5);grid on; axis([ [-0.01 1]*max(tx) [-0.1 1.1]*max(p)]);\nxlabel('time [s]');ylabel('x [m]');\nset(1,'position',[700 200 500 680])\nset(1,'paperposition',[0 0 5 6.8])\n\nsubplot(411);\ntext(tt(1)+tt(8)/200,max(j)/5,'t_0');\ntext(tt(2)+tt(8)/200,max(j)/5,'t_1');\ntext(tt(3) ,max(j)/5,'t_2');\ntext(tt(4) ,max(j)/5,'t_3');\ntext(tt(5) ,max(j)/5,'t_4');\ntext(tt(6) ,max(j)/5,'t_5');\ntext(tt(7)+tt(8)/200,max(j)/5,'t_6');\ntext(tt(8)+tt(8)/200,max(j)/5,'t_7');\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/16352-advanced-setpoints-for-motion-systems/profile3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.628488458479095}} {"text": "function markedElem = mark(elem,eta,theta,method)\n% MARK mark element.\n%\n% markedElem = mark(elem,eta,theta) mark a subset of elements by Dorfler\n% marking strategy. It returns an array of indices of marked elements\n% markedElem such that sum(eta(markedElem)^2) > theta*sum(eta^2).\n%\n% markedElem = mark(elem,eta,theta,'max') choose markedElem such that\n% eta(markedElem) > theta*max(eta).\n%\n% markedElem = mark(elem,eta,theta,'COARSEN') choose markedElem such that\n% eta(markedElem) < theta*max(eta).\n%\n% Copyright (C) 2008 Long Chen. See COPYRIGHT.txt for details.\n\nNT = size(elem,1); isMark = false(NT,1);\nif ~exist('method','var'), method = 'L2'; end % default marking is L2 based\nswitch upper(method)\n case 'MAX'\n isMark(eta>theta*max(eta))=1;\n case 'COARSEN'\n isMark(eta1 Evaluate values of derivatives\n% n_sdim scalar: 2 Number of space dimensions\n% n_vert scalar: 3 Number of vertices per cell\n% i_dof scalar: 1-21 Local basis function to evaluate\n% xi array [3,1] Local coordinates of evaluation point\n% aInvJac [n,6] Inverse of transformation Jacobian\n% vBase [n] Preallocated output vector\n% .\n% Output Value/[Size] Description\n% -----------------------------------------------------------------------------------\n% vBase [n] Evaluated function values\n% nLDof [4] Number of local degrees of freedom on\n% vertices, edges, faces, and cell interiors\n% xLDof [3,n_ldof] Local coordinates of local dofs\n% sfun string Function name of called shape function\n%\n% See also SF_TRI_P1\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\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\n\n\n\n\n\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/ellib/sf_tri_P5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6284425397975127}} {"text": "function [out] = evap_23(p1,p2,S,Smax,Ep,dt)\n% evap_23 combines evap_5 (evaporation) and evap_6 (transpiration)\n\n% Copyright (C) 2021 Clara Brandes, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Transpiration from vegetation at the potential rate if \n% storage is above field capacity and scaled by relative \n% storage if not (similar to evap_6), addition of \n% Evaporation from bare soil scaled by relative storage\n% (similar to evap_5)\n% Constraints: Ea <= Ep\n% Ea <= S/dt\n% @(Inputs): p1 - fraction vegetated area [-] (0...1)\n% p2 - field capacity coefficient[-]\n% S - current storage [mm]\n% Smax - maximum storage [mm]\n% Ep - potential evapotranspiration rate [mm/d]\n% dt - time step size [d]\n\nout = min([p1.*Ep+(1-p1).*S./Smax.*Ep, p1*Ep*S./(p2*Smax)+(1-p1).*S./Smax.*Ep,S/dt]);\n\nend\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/evap_23.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.628396480503305}} {"text": "function cc_levels_minmax_animate ( )\n\n%*****************************************************************************80\n%\n%% CC_LEVELS_MINMAX_ANIMATE displays the sequence of grids generated by CC_LEVELS_MINMAX.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_LEVELS_MINMAX_ANIMATE:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Display the sequence of nested 2D Clenshaw-Curtis grids\\n' );\n fprintf ( 1, ' generated by CC_LEVELS_MINMAX.\\n' );\n\n dim_num = 2;\n \n while ( 1 )\n%\n% Get user input.\n%\n fprintf ( 1, '\\n' );\n level_max = input ( 'Enter LEVEL_MAX or RETURN to exit;' );\n \n if ( isempty ( level_max ) )\n break\n end\n\n grid_points_old = [];\n grid_points_old_num = 0;\n\n grid_points = [];\n grid_points_num = 0;\n\n for level = 0 : level_max\n\n if ( 0 < grid_points_num )\n\n grid_points_old(1:2,grid_points_old_num+1:grid_points_old_num+grid_points_num) = ...\n grid_points(1:2,1:grid_points_num);\n\n grid_points_old_num = grid_points_old_num + grid_points_num;\n\n end\n%\n% Compute data.\n%\n [ grid_num, point_num ] = cc_levels_minmax_size ( dim_num, ...\n level, level );\n \n [ grid_level, grid_order, grid_points ] = cc_levels_minmax ( dim_num, ...\n level, level, grid_num, point_num );\n\n [ dim_num, grid_points_num ] = size ( grid_points );\n\n clf\n%\n% We have to name the axes in order to control the grid.\n%\n axes_handle = axes;\n%\n% Plot the points.\n%\n handle_new = scatter ( grid_points(1,:), grid_points(2,:), 'r', 'filled' );\n\n hold on\n\n if ( 0 < grid_points_old_num )\n handle_old = scatter ( grid_points_old(1,:), grid_points_old(2,:), 'b', 'filled' );\n end\n%\n% Force the plotting region to be square, not rectangular.\n%\n axis square\n%\n% Request grid lines.\n%\n grid on\n%\n% Specify the location of the grid lines, and suppress labeling.\n%\n set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'xticklabel', [] );\n set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'yticklabel', [] );\n%\n% Make the plotting region slightly bigger than the data.\n%\n axis ( [ -1.1, 1.1, -1.1, 1.1 ] )\n%\n% Title\n%\n s = sprintf ( '+LEVEL %d', level );\n title ( s );\n\n fprintf ( 1, '+LEVEL %d, Press return\\n', level );\n pause\n\n hold off\n\n end\n\n fprintf ( 1, 'Press return to CLEAR the grid!\\n' );\n pause\n clf\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_LEVELS_MINMAX_ANIMATE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cc_display/cc_levels_minmax_animate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6283873949015628}} {"text": "function [hrf,p] = spm_hrf(RT,P,T)\n% Haemodynamic response function\n% FORMAT [hrf,p] = spm_hrf(RT,p,T)\n% RT - scan repeat time\n% p - parameters of the response function (two Gamma functions)\n%\n% defaults\n% {seconds}\n% p(1) - delay of response (relative to onset) 6\n% p(2) - delay of undershoot (relative to onset) 16\n% p(3) - dispersion of response 1\n% p(4) - dispersion of undershoot 1\n% p(5) - ratio of response to undershoot 6\n% p(6) - onset {seconds} 0\n% p(7) - length of kernel {seconds} 32\n%\n% T - microtime resolution [Default: 16]\n%\n% hrf - haemodynamic response function\n% p - parameters of the response function\n%__________________________________________________________________________\n%\n% The parameters p(1:4) correspond to the shape and scale parameters of two\n% probability density functions of the Gamma distribution (see spm_Gpdf.m),\n% one corresponding to the main response and the other one to the\n% undershoot.\n% Note that the mean of the Gamma distribution is shape*scale and its mode\n% is (shape-1)*scale. This means that with the default values of the\n% parameters the peak of the heamodynamic response function will be around\n% 5 seconds.\n%__________________________________________________________________________\n% Copyright (C) 1996-2019 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_hrf.m 7721 2019-11-27 13:03:32Z guillaume $\n\n\n%-Parameters of the response function\n%--------------------------------------------------------------------------\ntry\n p = spm_get_defaults('stats.fmri.hrf');\ncatch\n p = [6 16 1 1 6 0 32];\nend\nif nargin > 1\n p(1:length(P)) = P;\nend\n\n%-Microtime resolution\n%--------------------------------------------------------------------------\nif nargin > 2\n fMRI_T = T;\nelse\n fMRI_T = spm_get_defaults('stats.fmri.t');\nend\n\n%-Modelled haemodynamic response function - {mixture of Gammas}\n%--------------------------------------------------------------------------\ndt = RT/fMRI_T;\nu = [0:ceil(p(7)/dt)] - p(6)/dt;\nhrf = spm_Gpdf(u,p(1)/p(3),dt/p(3)) - spm_Gpdf(u,p(2)/p(4),dt/p(4))/p(5);\nhrf = hrf([0:floor(p(7)/RT)]*fMRI_T + 1);\nhrf = hrf'/sum(hrf);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_hrf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6283563310578612}} {"text": "% kaiserbeta() - Estimate Kaiser window beta\n%\n% Usage:\n% >> beta = pop_kaiserbeta(dev);\n%\n% Inputs:\n% dev - scalar maximum passband deviation/ripple\n%\n% Output:\n% beta - scalar Kaiser window beta\n%\n% References:\n% [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal\n% Processing: Principles, Algorithms, and Applications (3rd ed.).\n% Englewood Cliffs, NJ: Prentice-Hall\n%\n% Author: Andreas Widmann, University of Leipzig, 2005\n\n%123456789012345678901234567890123456789012345678901234567890123456789012\n\n% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, widmann@uni-leipzig.de\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n% $Id$\n\nfunction [ beta ] = kaiserbeta(dev)\n\ndevdb = -20 * log10(dev);\n\nif devdb > 50\n beta = 0.1102 * (devdb - 8.7);\nelseif devdb >= 21\n beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21);\nelse\n beta = 0;\nend\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/preproc/private/kaiserbeta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6283563269490554}} {"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 pathS = MC_VGCIR(S0,r,d,T,C,G,M,kappa,eta,...\n lambda,NTime,NSim,NBatches)\nintNt = 20; % steps in between orginial grid points\nallsteps = intNt * NTime; % grid containing all necessary steps\ndT = T / NTime; % time step\ndaT = T/allsteps; % time step\ntime = 0 : T/NTime : T; % time for martingale correction\n\npathS = zeros(NSim,NTime+1,NBatches);% output\nlnS = ones(NSim,NTime+1); % used for each batch\nlnS(:,1) = log(S0*exp(-d*T)); % set S(0) dividend adjusted\n\n% precompute constants\npsiVG = (-1i)*C*log(G*M/(G*M+(M-G)-1)); % char exp\ngamma = sqrt(kappa^2-2*lambda^2*1i*psiVG);% CIR par\ndenom = ( cosh(0.5*gamma*time) ... % denom\n + kappa*sinh(0.5*gamma*time)./gamma ).^(2*kappa*eta*lambda^(-2)); \n% coth is inf at 0\nphiCIR(time>0) = kappa^2*eta*time(time>0)*lambda^(-2) ...\n + 2*1i*psiVG./(kappa+gamma.*coth(gamma*time(time>0)/2)) ...\n - log(denom(time>0)); % char func\nphiCIR(1) = log(denom(1)); % char func start\nomegaT = -phiCIR; % martingale correction \nomegaT(1) = 0; % maringale correction in 0\n\n\ndeg = 4*eta*kappa/lambda^2; \nfac1 = 4*kappa*exp(-kappa*daT)/lambda^2/(1-exp(-kappa*daT));\nfac2 = lambda^2*(1-exp(-kappa*daT))/4/kappa;\n\nY = zeros(NSim,NTime); % Integrated clock\n\n\nfor l = 1 : NBatches % batch loop \n % Generating time change\n yy = ones(NSim,allsteps+1); % stochastic clock\n for n = 1 : allsteps \n Nvec = poissrnd(0.5 * fac1 * yy(:,n)); % Poissonians \n yy(:,n+1) = fac2 * chi2rnd(deg+2*Nvec); % stochastic time \n end\n \n for m=1:NTime\n Y(:,m+1) = Y(:,m) + daT * sum(yy(:,1+(m-1)*intNt:m*intNt),2);\n end\n \n Intensity = C * (Y(:,2:end)-Y(:,1:end-1)); % intensity\n DGam = gamrnd(Intensity,1/M) - gamrnd(Intensity,1/G);% diff gamma proc\n diffomegaT = omegaT(2:end) - omegaT(1:end-1); % Martingale correction\n \n for m=2:NTime+1 % time loop\n lnS(:,m) = lnS(:,m-1) + (r-d)*dT + diffomegaT(m-1) + DGam(:,m-1); \n end\n pathS(:,:,1) = exp(lnS);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/MC_VGCIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6282970449266303}} {"text": " function xs = l1_tv_restore1_fun(yi, A, varargin)\n%function xs = l1_tv_restore1_fun(yi, A, varargin)\n%|\n%| Robust image restoration using a l1 data fit term and a TV-like regularizer.\n%|\n%| see l1_tv_restore1.m\n%| min_x |yi - A(ti) * x|_1 + beta (|Cx x|_1 + |Cy x|_1)\n%| where |.|_1 is approximated by a hyperbola\n%|\n%|\n%| in\n%|\tyi\tdata\n%|\tA\tsystem matrix\n%|\n%| option\n%|\tseveral - see code ...\n%|\n%| out\n%|\txs\testimate(s)\n%|\n%| Copyright 2010-05-24, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(yi, 'test')\n\tl1_tv_restore1\n\tclear xs\nreturn\nend\n\nif nargin < 2, help(mfilename), error(mfilename), end\n\narg.niter = 20;\narg.delta1 = 0.2; % round corner of |t| in data fit to approximate by hyperbola\narg.delta2 = 0.2; % round corner of |t| in penalty\narg.xinit = [];\narg.mask = [];\narg.l2b = -6;\narg.curvtype = 'oc';\narg.args = {};\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.xinit)\n\targ.xinit = yi; % assume restoration\nend\n\nif isempty(arg.mask)\n\targ.mask = true(size(yi));\nend\n\n% R = R_null; % null regularizer \nR = Reg1(arg.mask, 'type_denom', 'matlab', ...\n\t'beta', 2^arg.l2b, 'pot_arg', {'hyper2', arg.delta2});\n\ndata = {yi(:), arg.delta1};\nxs = pl_pcg_qs_ls(arg.xinit(:), A, data, ...\n\t@l1_tv_dercurv, R, 'niter', arg.niter, ...\n\t'curvtype', arg.curvtype, ...\n\targ.args{:});\n\n\n% l1_tv_dercurv()\nfunction [deriv curv] = l1_tv_dercurv(data, yp, curvtype)\nyi = data{1};\ndelta = data{2};\npot = potential_fun('hyper2', delta);\nt = yp - yi;\nswitch curvtype\ncase 'pc'\n\tcurv = 1;\n\tderiv = pot.dpot(t);\ncase 'oc'\n\tcurv = pot.wpot(t);\n\tderiv = curv .* t;\notherwise\n\tfail('curvtype %s', curvtype)\nend\n\n\n% R_null()\nfunction R = R_null;\nR.dercurv = @R_null_dercurv;\nR.C1 = 0;\n\n% R_null_dercurv()\nfunction [a b] = R_null_dercurv(arg1, arg2);\na = 0;\nb = 0;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/l1_tv_restore1_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6282970445068747}} {"text": "function [I,V,N]=integrateStochCubAdaptive(func,mu,SR,algorithm,epsVal2,NMax)\n%%INTEGRATESTOCHCUBADAPTIVE Perform approximate Monte Carlo numerical\n% integration of a function times a Gaussian PDF using a\n% method that can be compared to importance sampling in that\n% random sets of approximate cubature points are generated\n% rather than more traditional Monte Carlo appraoches.\n%\n%INPUTS: func The handle to the function that is multiplies by a Gaussian\n% PDF before integration is performed. The function can take a\n% multidimensional input, but must produce a real univariate\n% output.\n% mu The numDimX1 mean of the Gaussian PDF.\n% SR The numDimXnumDim lower-triangular square root of the\n% covariance matrix of the Gaussian PDF.\n% algorithm An optional parameter specifying the algorithm to use.\n% Possible values are:\n% 0 Use the first-order method of [1].\n% 1 Use the third-order method of [1].\n% 2 (The default if omitted or an empty matrix is passed) Use\n% the fifth-order method of [1].\n% epsVal2 An optional convergence bound based on the approximate\n% variance of the estimate. The default if this parameter is\n% omitted or an empty matrix is passed is 1e-2.\n% NMax The maximum number of iterations to perform. The default\n% value if this parameter is omitted or an empty matrix is\n% passed is 10e3.\n%\n%OUTPUTS: I The approximate scalar value of the integral.\n% V The approximate variance of the estimate.\n% N The number of iterations performed.\n%\n%All three algorithms arise from similar derivations in [1].\n%\n%EXAMPLE:\n%Here, we choose a function whose true integral with a normal weighting\n%function can be easily found. In this instance, we just choose a bivariate\n%polynomial. \n% f=@(x)(x(2)^4*(x(1)+1)^3-(x(1)+2)^2-(x(2)-4)^3);\n% mu=[0;1/2];\n% R=[2,-1;\n% -1, 2];\n% SR=chol(R,'lower');\n% algorithm=2;\n% %The exact solution to the problem is known to be \n% exactSol=1917/16\n% [I,V,N]=integrateStochCubAdaptive(f,mu,SR,algorithm)\n%One will find the result is relatively close, but not equal to the exact\n%solution.\n%\n%REFERENCES:\n%[1] A. Genz and J. Monahan, \"Stochastic integration rules for infinite\n% regions,\" SIAM Journal on Scientific Computing, vol. 19, no. 2, pp.\n% 426-439, Mar. 1998.\n%\n%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(NMax))\n NMax=10e3; \nend\n\nif(nargin<5||isempty(epsVal2))\n epsVal2=1e-2; \nend\n\nif(nargin<4||isempty(algorithm))\n algorithm=2;\nend\n\nnumDim=length(mu);\n\n%Deal with the distribution not being a standard normal distribution.\nf=@(x)func(SR*x+mu);\n\nswitch(algorithm)\n case 0 %Degree 1 spherical-radial integration rule \n %Step 2\n N=0;\n I=0;\n V=0;\n while(1)\n %Step 3a\n N=N+1;\n\n %Step3b\n x=randn(numDim,1);\n\n %Step 3c\n SR=(f(-x)+f(x))/2;\n D=(SR-I)/N;\n I=I+D;\n V=(N-2)*V/N+D^2;\n\n if(V= yr1(1)) .* (t <= yr1(2)));\nt1 = t(indt1);\n\nyr2 = [1850, 1870];\n% yr2 = [1845, 1934]; one observation\nindt2 = ~logical((t >= yr2(1)) .* (t <= yr2(2)));\nt2 = t(indt2);\n\n% hare (thousands)\ny1 = round(data.data(indt1, 2));\n\n% lynx (thousands)\ny2 = round(data.data(indt2, 3));\n\n% predator-prey data;\ny = [y1; y2];\n\n% create species markers\nc = [ones(size(t1)); 2*ones(size(t2))];\n\n% data gp-format - species markers in the last column\nx = [[t1; t2] c];\nz = [ones(size(x, 1), 1) c];\n\n% likelihood structure for each species (the likelihood can also be distinct)\nlik1 = lik_negbin;\nlik2 = lik_negbin;\nlikS = {lik1 lik2};\nlik = lik_liks('likelihoods', likS, 'classVariables', 2);\n\n% correlation function for each species (the correlation functions can also be distinct)\nk1 = gpcf_sexp('magnSigma2', 1, 'magnSigma2_prior', prior_fixed, 'selectedVariables', 1);\nk2 = gpcf_sexp('magnSigma2', 1, 'magnSigma2_prior', prior_fixed, 'selectedVariables', 1);\n\n% the linear model of coregionalization (multivariate Gaussian process model)\nk = gpcf_covar('numberClass', 2, 'classVariables', 2, ...\n 'R_prior', prior_corrunif('nu', 3), 'corrFun', {k1 k2});\n\n% set gp structure\n% for the EP approximation\ngp = gp_set('lik', lik, 'cf', k, 'latent_method', 'EP');\n\n% For the Laplace approximation\n%gp = gp_set('lik', lik, 'cf', k, 'latent_method', 'Laplace'); \n \n% optimzation options\nopt = optimset('TolFun', 1e-3, 'TolX', 1e-5, 'Display', 'iter'); \n\n% random initialization (this is important ...)\n% wini = 2.* randn(size(gp_pak(gp))); gp = gp_unpak(gp, wini);\n\n% map ─ type-II maximum likelihood\ngp = gp_optim(gp, x, y, 'z', z, 'opt', opt);\n\n% check the gradient ...\n% gp_g(gp_pak(gp), gp, x, y, 'z', z)';\n\n% take the parameters, hyperparameters estimates\n[th ss] = gp_pak(gp);\n\n% correlation matrix estimate\n%rho = k.fh.RealToRho(th(end - 2 - 2), 1, [])\nCorr = gp.cf{1}.fh.sigma(gp.cf{1}, 'corr');\nCorr{1}\n\n% prediction\nnp = 200;\nxp = repmat(linspace(min(x(:, 1)), max(x(:, 1)), np)', 2, 1);\nxp = [xp repelem((1:2), np)'];\nzp = ones(size(xp, 1), 1);\n\n% leave-one-out\n[~, ~, lpyt] = gp_loopred(gp, x, y,'z', z); \n\n% prediction for new observations\n[Ef, Varf, ~, Ey, Vary] = gp_pred(gp, x, y, xp, 'z', z, 'zt', [zp xp(:, 2)]); \n\n% --- visualize predictions\n\nfigure; hold on;\n\nsubplt = subplot(2, 1, 1); hold on\nsubplt.XLim = [min(xp(:, 1)), max(xp(:, 1))];\npsubplt = get(subplt, 'pos');\npsubplt(4) = psubplt(4) + 0.03;\npsubplt(3) = psubplt(3) + 0.04;\npsubplt(1) = psubplt(1) - 0.04;\nset(subplt, 'pos', psubplt);\n\nfor j = 1:2\n indj = xp(:, 2) == j; \n indX = xp(indj, 1);\n \n pl(j) = plot(xp(indj, 1), Ey(indj), 'color', col(j, :), 'LineWidth', 2);\n end\n\n% visualize observed (training) predator-pray data\npl(3) = plot(t1(t1 <= yr1(1)), y1(t1 <= yr1(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :)); \nplot(t1(t1 >= yr1(2)), y1(t1 >= yr1(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :)); \npl(4) = plot(t2(t2 <= yr2(1)), y2(t2 <= yr2(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :)); \nplot(t2(t2 >= yr2(2)), y2(t2 >= yr2(2)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :)); \n\nxlabel('years'); ylabel('Population size'); \ntitle('multivariate Gaussian process model');\n\nlegend(pl, 'E[N_1(t_*)|N_1 = n_1, N_2 = n_2]', 'E[N_2(t_*)|N_1 = n_1, N_2 = n_2]', ...\n 'hare-data', 'lynx-data', 'Location', 'northeast'); \n\n%%\n% -------- data analysis with independent Gaussian process model\n\nEfI = {}; VarfI = {}; EyI = {}; VaryI = {};\ngpI = {};\n\nsubplt = subplot(2, 1, 2); hold on\nsubplt.XLim = [min(xp(:, 1)), max(xp(:, 1))];\npsubplt = get(subplt, 'pos');\npsubplt(4) = psubplt(4) + 0.05;\npsubplt(3) = psubplt(3) + 0.04;\npsubplt(1) = psubplt(1) - 0.03;\nset(subplt, 'pos', psubplt);\n\nfor j = 1:2\n inddj = x(:, 2) == j; \n cf = gpcf_sexp('selectedVariables', 1);\n \n gpI{j} = gp_set('lik', likS{j}, 'cf', cf);\n gpI{j} = gp_optim(gpI{j}, x(inddj, :), y(inddj), 'opt', opt);\n \n indj = xp(:, 2) == j; \n indX = xp(indj, 1);\n \n [EfI{j}, VarfI{j}, lpyt, EyI{j}, VaryI{j}] = ...\n gp_pred(gpI{j}, x(inddj, :), y(inddj), xp(indj, :));\n \n pl(j) = plot(xp(indj, 1), EyI{j}, 'color', col(j, :), 'LineWidth', 1.7); \nend\n\n% visualize observed (training) predator-pray data\npl(3) = plot(t1(t1 <= yr1(1)), y1(t1 <= yr1(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :)); \nplot(t1(t1 >= yr1(2)), y1(t1 >= yr1(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(1, :)); \npl(4) = plot(t2(t2 <= yr2(1)), y2(t2 <= yr2(1)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :)); \nplot(t2(t2 >= yr2(2)), y2(t2 >= yr2(2)), '.', ...\n 'MarkerSize', 23, 'lineWidth', 2, 'color', col(2, :)); \n\nxlabel('years'); ylabel('Population size'); \ntitle('independent Gaussian process models');\n\nlegend(pl, 'E[N1(t)|Y1 = y1, Y2 = y2]', 'E[N2(t)|Y1 = y1, Y2 = y2]', ...\n 'hare-data', 'lynx-data', 'Location', 'northeast'); \n\n%%\n% ------ all measurements (compare the difference ...)\n\nfigure; hold on;\n\nfor j = 1:2\n indj = x(:, 2) == j;\n plot(x(indj, 1), y(indj), '.', 'MarkerSize', 13, 'color', col(j, :))\n pd(j) = plot(t, yy((j - 1) * 91 + [1:91]), '.-', ... \n 'color', col(j, :), 'MarkerSize', 23, 'LineWidth', 2);\nend \n\nxlabel('years'); ylabel('Population size'); \ntitle('full data');\n\nlegend(pd, 'hare-data', 'lynx-data', 'Location', 'northeast'); \n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/demo_multivariategp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6282970260326115}} {"text": "function [y, dzdg, dzdb] = vl_nngnorm(x, g, b, varargin)\n%VL_NNGNORM CNN group normalization.\n% Y = VL_NNGNORM(X,G,B) applies group normalization\n% to the input X with shape HxWxCxN. Group normalization is defined as:\n%\n% Y(i,j,k,t) = G(k',t) * X_HAT(i,j,k,t) + B(k',t)\n%\n% where\n% k' = group_idx(k,C,G), where N_G is the number of groups and\n% group_idx(k,C,G) := floor(k / (C/N_G)).\n% X_HAT(i,j,k,t) = (X_HAT(i,j,k,t) - mu(k',t)) / sigma(k',t)\n% mu(k',t) = mean_ijk'' X(i,j,k'',t),\n% sigma2(k',t) = mean_ijk'' (X(i,j,k'',t) - mu(k'',t))^2,\n% sigma(k',t) = sqrt(sigma2(k) + EPSILON)\n% where k'' takes values such that group_idx(k'',C,G) == group_idx(k,C,G)\n%\n% VL_NNGNORM(..., 'option', value, ...) takes the following option:\n%\n% `numGroups`:: 32\n% The number of groups used to split the channels when computing\n% normalization statistics.\n%\n% `epsilon`:: 1e-4\n% A parameter to add stability to the normalization operation.\n%\n% Notes: GroupNorm is introduced in the paper:\n% `Group Normalization, Yuxin Wu, Kaiming He,\n% arXiv preprint arXiv:1803.08494 (2018)\n%\n% Copyright (C) 2018 Samuel Albanie\n% All rights reserved.\n\n opts.numGroups = 32 ;\n opts.epsilon = 1e-4 ;\n [opts,dzdy] = vl_argparsepos(opts, varargin) ;\n\n bsize = size(x, 4) ;\n expectedSz = [1 1 size(x,3) 1] ;\n sg = size(g) ; sb = size(b) ;\n assert(all(expectedSz(1:numel(sg)) == sg), 'GAINS have unexpected size') ;\n assert(all(expectedSz(1:numel(sb)) == sb), 'BIASES have unexpected size') ;\n\n szX = size(x) ; % store original shape\n\n % compute statistics per group for current minibatch and normalize\n x = reshape(x, size(x,1), size(x,2), [], opts.numGroups, bsize) ;\n\n mu = groupAvg(x) ;\n sigma2 = groupAvg(bsxfun(@minus, x, mu).^ 2) ;\n sigma = sqrt(sigma2 + opts.epsilon) ;\n x_hat = bsxfun(@rdivide, bsxfun(@minus, x, mu), sigma) ;\n\n if isempty(dzdy)\n x_hat_ = reshape(x_hat, szX) ;\n y = bsxfun(@times, g, x_hat_) ; % apply gain\n y = bsxfun(@plus, y, b) ; % add bias\n else\n dzdy = dzdy{1} ;\n dzdb = chanSum(dzdy) ;\n x_hat_ = reshape(x_hat, szX) ; dzdg = chanSum(x_hat_ .* dzdy) ;\n dzdy = reshape(dzdy, size(x,1), size(x,2), [], opts.numGroups, bsize) ;\n\n g_ = reshape(g, 1, 1, size(dzdy, 3), []) ;\n dzdx_hat = bsxfun(@times, dzdy, g_) ;\n t1 = bsxfun(@minus, x, mu) ;\n m = prod([size(x,1) size(x,2) size(x,3)]) ;\n dzdsigma = groupSum((-1/2) * dzdx_hat .* bsxfun(@rdivide, t1, sigma.^3)) ;\n\n dzdmu = groupSum(bsxfun(@rdivide, dzdx_hat, -sigma)) + ...\n bsxfun(@times, dzdsigma, -2 * groupAvg(t1)) ;\n\n t4 = bsxfun(@rdivide, dzdx_hat, sigma) + ...\n bsxfun(@times, dzdsigma, (2 / m) * t1) ;\n dzdx = bsxfun(@plus, t4, dzdmu * (1/m)) ;\n y = reshape(dzdx, szX) ;\n end\n\n% ----------------------------------------\nfunction avg = groupAvg(x)\n% ----------------------------------------\n avg = mean(mean(mean(x, 1), 2), 3) ;\n\n% -----------------------\nfunction res = groupSum(x)\n% -----------------------\n res = sum(sum(sum(x, 1), 2), 3) ;\n\n% -----------------------\nfunction res = chanSum(x)\n% -----------------------\n res = sum(sum(sum(x, 1), 2), 4) ;\n", "meta": {"author": "ShuaiBai623", "repo": "MFT", "sha": "8762f8cdf494ce0b1a1c3d431660c5c8fd91744a", "save_path": "github-repos/MATLAB/ShuaiBai623-MFT", "path": "github-repos/MATLAB/ShuaiBai623-MFT/MFT-8762f8cdf494ce0b1a1c3d431660c5c8fd91744a/external_libs/matconvnet/contrib/mcnExtraLayers/matlab/vl_nngnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6282941219905857}} {"text": "function x = quasigeometric_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% QUASIGEOMETRIC_CDF_INV inverts the Quasigeometric CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0\n%\n% Input, real A, the probability of 0 successes.\n% 0.0 <= A <= 1.0.\n%\n% Input, real B, the depreciation constant.\n% 0.0 <= B < 1.0.\n%\n% Output, integer X, the corresponding value of X.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUASIGEOMETRIC_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'QUASIGEOMETRIC_CDF_INV - Fatal error!' );\n end\n\n if ( cdf < a )\n x = 0;\n elseif ( b == 0.0 )\n x = 1;\n else\n x = 1 + floor ( ( log ( 1.0 - cdf ) - log ( 1.0 - a ) ) / log ( b ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/quasigeometric_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6281651585427985}} {"text": "function ex5bvp\n%EX5BVP Example 5 of the BVP tutorial.\n% Falkner-Skan BVPs are discussed in T. Cebeci and H.B. Keller, \n% Shooting and parallel shooting methods for solving the Falkner-Skan\n% boundary-layer equation, J. Comp. Phy., 7 (1971) 289-300. This is \n% the positive wall shear case for which the parameter beta is known \n% and the problem is to be solved for a range of the parameter. This\n% is the hardest case of the table in the paper.\n%\n% The problem is posed on [0 infinity). As in the paper cited, the\n% boundary condition at infinity is imposed at a finite point, here\n% called 'infinity'. It is best to start with a relatively small value\n% and increase it until consistent results are obtained. A value of 6\n% appears to be satisfactory. Starting with a \"large\" value is tempting,\n% but not a good tactic because the code will fail with the crude guess\n% and default tolerances used here.\n\n% Copyright 1999, The MathWorks, Inc.\n\n% 'infinity' is a variable to facilitate experimentation.\ninfinity = 6;\n\n% The constant guess for the solution satisfies the boundary conditions.\nsolinit = bvpinit(linspace(0,infinity,5),[0 0 1]);\n\noptions = bvpset('stats','on');\n\nsol = bvp4c(@ex5ode,@ex5bc,solinit,options);\neta = sol.x;\nf = sol.y;\n\nfprintf('\\n');\nfprintf('Cebeci & Keller report f''''(0) = 0.92768.\\n')\nfprintf('Value computed here is f''''(0) = %7.5f.\\n',f(3,1))\n\nclf reset\nplot(eta,f(2,:));\naxis([0 infinity 0 1.4]);\ntitle('Falkner-Skan equation, positive wall shear, \\beta = 0.5.')\nxlabel('\\eta')\nylabel('df/d\\eta')\nshg\n\n% --------------------------------------------------------------------------\n\nfunction dfdeta = ex5ode(eta,f)\n%EX5ODE ODE function for Example 5 of the BVP tutorial. \nbeta = 0.5;\ndfdeta = [ f(2)\n f(3)\n -f(1)*f(3) - beta*(1 - f(2)^2) ];\n\n% --------------------------------------------------------------------------\n\nfunction res = ex5bc(f0,finf)\n%EX5BC Boundary conditions for Example 5 of the BVP tutorial.\nres = [f0(1)\n f0(2)\n finf(2) - 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/3819-tutorial-on-solving-bvps-with-bvp4c/BVP_tutorial/BVP_examples/ex5bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6281651585427985}} {"text": "function F=scarsplslda(X,y,A,K,method,num,OPT) \n%+++ This is the simplified version of CARS, only retaining the EDF element.\n%+++ num: the number of Monte Carlo Sampling.\n%+++ A: the maximal number of PLS components to extract.\n%+++ fold: number of folds for cross validation.\n%+++ method: pretreat method, 'center' or 'autoscaling'.\n%+++ OPT: 1: Plot. 0: No plot.\n%+++ Advisor: Yizeng Liang, yizeng_liang@263.net.\n%+++ Hongdong Li, Jan.3, 2009.\n%+++ Reference: Hongdong Li, Yizeng Liang, Qingsong Xu and Dongsheng Cao,\n% Key wavelengths screening using competitive adaptive reweighted sampling method\n% for multivariate calibration J?. Anal. Chim. Acta, 2009, 648 (1): 77-84 \n\n\n\n%+++ Initial settings.\nif nargin<7;OPT=1;end; %+++ OPT==1: then figure output.\nif nargin<6;num=50;end\nif nargin<5;method='autoscaling';end\nif nargin<4;K=5;end\nif nargin<3;A=2;end\n\n[Mx,Nx]=size(X);\nA=min([Mx Nx A]);\nindex=1:Nx;\n\n\nr0=1;\nr1=2/Nx;\nVsel=1:Nx;\n\nW=zeros(num,Nx);\nRatio=zeros(1,num);\n\n%+++ Parameter of exponentially decreasing function. \nb=log(r0/r1)/(num-1); a=r0*exp(b);\n\n%+++ Main Loop\nfor iter=1:num \n \n LDA=plslda(X(:,Vsel),y,A,method); %+++ PLS model\n w=zeros(Nx,1);coef=LDA.coef_lda_origin(1:end-1);\n w(Vsel)=coef;W(iter,:)=w; \n w=abs(w); %+++ weights\n [ws,indexw]=sort(-w); %+++ sort weights\n \n ratio=a*exp(-b*(iter+1)); %+++ Ratio of retained variables.\n Ratio(iter)=ratio;\n K=round(Nx*ratio); \n \n \n w(indexw(K+1:end))=0; %+++ Eliminate some variables with small coefficients. \n \n Vsel=find(w~=0); \n fprintf('The %dth variable sampling finished.\\n',iter); %+++ Screen output.\n end\n\n%+++ Cross-Validation to choose an optimal subset;\nRMSEP=zeros(1,num);\nRpc=zeros(1,num);\nfor i=1:num\n vsel=find(W(i,:)~=0);\n CV=plsldacv(X(:,vsel),y,A,10,method,0);\n RMSEP(i)=min(CV.cv);\n Rpc(i)=CV.optPC;\n fprintf('The %dth subset finished.\\n',i);\nend\nRmin=min(RMSEP);\nindexOPT=find(RMSEP==Rmin);\nindexOPT=indexOPT(end);\n\n%+++ output\nF.method=method;\nF.nPC=A;\nF.W=W;\nF.vim=sum(W,2);\nF.cv=RMSEP;\nF.minCV=Rmin;\nF.iterOPT=indexOPT;\nF.optPC=Rpc(indexOPT);\nF.ratio=Ratio;\nF.vsel=find(W(indexOPT,:)~=0)';\nF.vim=abs(sum(W));\n\n%+++ Plot\n if OPT==1;plotcars(F);end;\n%+++ END\n\n\n", "meta": {"author": "viggin", "repo": "domain-adaptation-toolbox", "sha": "2a991816a0ac39043b526c2b0cbe01bc844d8890", "save_path": "github-repos/MATLAB/viggin-domain-adaptation-toolbox", "path": "github-repos/MATLAB/viggin-domain-adaptation-toolbox/domain-adaptation-toolbox-2a991816a0ac39043b526c2b0cbe01bc844d8890/plslda/scarsplslda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6281189454998719}} {"text": "function [x, cost, info, options] = conjugategradient(problem, x, options)\n% Conjugate gradient minimization algorithm for Manopt.\n%\n% function [x, cost, info, options] = conjugategradient(problem)\n% function [x, cost, info, options] = conjugategradient(problem, x0)\n% function [x, cost, info, options] = conjugategradient(problem, x0, options)\n% function [x, cost, info, options] = conjugategradient(problem, [], options)\n%\n% Apply the conjugate gradient minimization algorithm to the problem\n% defined in the problem structure, starting at x0 if it is provided\n% (otherwise, at a random point on the manifold). To specify options whilst\n% not specifying an initial guess, give x0 as [] (the empty matrix).\n%\n% The outputs x and cost are the best reached point on the manifold and its\n% cost. The struct-array info contains information about the iterations:\n% iter : the iteration number (0 for the initial guess)\n% cost : cost value\n% time : elapsed time in seconds\n% gradnorm : Riemannian norm of the gradient\n% stepsize : norm of the last tangent vector retracted\n% beta : value of the beta parameter (see options.beta_type)\n% linesearch : information logged by options.linesearch\n% And possibly additional information logged by options.statsfun.\n% For example, type [info.gradnorm] to obtain a vector of the successive\n% gradient norms reached.\n%\n% The options structure is used to overwrite the default values. All\n% options have a default value and are hence optional. To force an option\n% value, pass an options structure with a field options.optionname, where\n% optionname is one of the following and the default value is indicated\n% between parentheses:\n%\n% tolgradnorm (1e-6)\n% The algorithm terminates if the norm of the gradient drops below this.\n% maxiter (1000)\n% The algorithm terminates if maxiter iterations have been executed.\n% maxtime (Inf)\n% The algorithm terminates if maxtime seconds elapsed.\n% minstepsize (1e-10)\n% The algorithm terminates if the linesearch returns a displacement\n% vector (to be retracted) smaller in norm than this value.\n% beta_type ('H-S')\n% Conjugate gradient beta rule used to construct the new search\n% direction, based on a linear combination of the previous search\n% direction and the new (preconditioned) gradient. Possible values\n% for this parameter are:\n% 'S-D', 'steep' for beta = 0 (preconditioned steepest descent)\n% 'F-R' for Fletcher-Reeves's rule\n% 'P-R' for Polak-Ribiere's modified rule\n% 'H-S' for Hestenes-Stiefel's modified rule\n% 'H-Z' for Hager-Zhang's modified rule\n% 'L-S' for Sato's Liu-Storey rule\n% See Hager and Zhang 2006, \"A survey of nonlinear conjugate gradient\n% methods\" for a description of these rules in the Euclidean case and\n% for an explanation of how to adapt them to the preconditioned case.\n% The adaption to the Riemannian case is straightforward: see in code\n% for details. Modified rules take the max between 0 and the computed\n% beta value, which provides automatic restart, except for H-Z and L-S \n% which use a different modification. Sato's Liu-Storey rule is \n% described in Sato 2021, \"Riemannian conjugate gradient methods: \n% General framework and specific algorithms with convergence analyses\"\n% orth_value (Inf)\n% Following Powell's restart strategy (Math. prog. 1977), restart CG\n% (that is, make a -preconditioned- gradient step) if two successive\n% -preconditioned- gradients are \"too\" parallel. See for example\n% Hager and Zhang 2006, \"A survey of nonlinear conjugate gradient\n% methods\", page 12. An infinite value disables this strategy. See in\n% code formula for the specific criterion used.\n% linesearch (@linesearch_adaptive or @linesearch_hint)\n% Function handle to a line search function. The options structure is\n% passed to the line search too, so you can pass it parameters. See\n% each line search's documentation for info. Another available line\n% search in manopt is @linesearch, in /manopt/linesearch/linesearch.m\n% If the problem structure includes a line search hint, then the\n% default line search used is @linesearch_hint.\n% statsfun (none)\n% Function handle to a function that will be called after each\n% iteration to provide the opportunity to log additional statistics.\n% They will be returned in the info struct. See the generic Manopt\n% documentation about solvers for further information.\n% stopfun (none)\n% Function handle to a function that will be called at each iteration\n% to provide the opportunity to specify additional stopping criteria.\n% See the generic Manopt documentation about solvers for further\n% information.\n% verbosity (3)\n% Integer number used to tune the amount of output the algorithm\n% generates during execution (mostly as text in the command window).\n% The higher, the more output. 0 means silent.\n% storedepth (2)\n% Maximum number of different points x of the manifold for which a\n% store structure will be kept in memory in the storedb. If the\n% caching features of Manopt are not used, this is irrelevant. For\n% the CG algorithm, a store depth of 2 should always be sufficient.\n%\n%\n% In most of the examples bundled with the toolbox (see link below), the\n% solver can be replaced by the present one if need be.\n%\n% See also: steepestdescent trustregions manopt/solvers/linesearch manopt/examples\n\n% An explicit, general listing of this algorithm, with preconditioning,\n% can be found in the following paper:\n% @Article{boumal2015lowrank,\n% Title = {Low-rank matrix completion via preconditioned optimization on the {G}rassmann manifold},\n% Author = {Boumal, N. and Absil, P.-A.},\n% Journal = {Linear Algebra and its Applications},\n% Year = {2015},\n% Pages = {200--239},\n% Volume = {475},\n% Doi = {10.1016/j.laa.2015.02.027},\n% }\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, Dec. 30, 2012.\n% Contributors: Nicolas Boumal, Nick Vannieuwenhoven\n% Change log: \n%\n% March 14, 2013, NB:\n% Added preconditioner support : see Section 8 in\n% https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf\n% \n% Sept. 13, 2013, NB:\n% Now logging beta parameter too.\n% \n% Nov. 7, 2013, NB:\n% The search direction is no longer normalized before it is passed\n% to the linesearch. This way, it is up to the designers of the\n% linesearch to decide whether they want to use the norm of the\n% search direction in their algorithm or not. There are reasons\n% against it, but practical evidence that it may help too, so we\n% allow it. The default linesearch_adaptive used does exploit the\n% norm information. The base linesearch does not. You may select it\n% by setting options.linesearch = @linesearch;\n%\n% Nov. 29, 2013, NB:\n% Documentation improved: options are now explicitly described.\n% Removed the Daniel rule for beta: it was not appropriate for\n% preconditioned CG and I could not find a proper reference for it.\n%\n% April 3, 2015 (NB):\n% Works with the new StoreDB class system.\n%\n% Aug. 2, 2018 (NB):\n% Now using storedb.remove() to keep the cache lean.\n%\n% Feb. 7, 2022 (NV):\n% Added support for Liu-Storey rule (L-S).\n\nM = problem.M;\n\n% Verify that the problem description is sufficient for the solver.\nif ~canGetCost(problem)\n warning('manopt:getCost', ...\n 'No cost provided. The algorithm will likely abort.');\nend\nif ~canGetGradient(problem) && ~canGetApproxGradient(problem)\n warning('manopt:getGradient:approx', ...\n ['No gradient provided. Using an FD approximation instead (slow).\\n' ...\n 'It may be necessary to increase options.tolgradnorm.\\n' ...\n 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']);\n problem.approxgrad = approxgradientFD(problem);\nend\n\n% Set local defaults here\nlocaldefaults.minstepsize = 1e-10;\nlocaldefaults.maxiter = 1000;\nlocaldefaults.tolgradnorm = 1e-6;\nlocaldefaults.storedepth = 20;\n% Changed by NB : H-S has the \"auto restart\" property.\n% See Hager-Zhang 2005/2006 survey about CG methods.\n% The auto restart comes from the 'max(0, ...)', not so much from the\n% reason stated in Hager-Zhang I think. P-R also has auto restart.\nlocaldefaults.beta_type = 'H-S';\nlocaldefaults.orth_value = Inf; % by BM as suggested in Nocedal and Wright\n\n \n% Depending on whether the problem structure specifies a hint for\n% line-search algorithms, choose a default line-search that works on\n% its own (typical) or that uses the hint.\nif ~canGetLinesearch(problem)\n localdefaults.linesearch = @linesearch_adaptive;\nelse\n localdefaults.linesearch = @linesearch_hint;\nend\n\n% Merge global and local defaults, then merge w/ user options, if any.\nlocaldefaults = mergeOptions(getGlobalDefaults(), localdefaults);\nif ~exist('options', 'var') || isempty(options)\n options = struct();\nend\noptions = mergeOptions(localdefaults, options);\n\ntimetic = tic();\n\n% If no initial point x is given by the user, generate one at random.\nif ~exist('x', 'var') || isempty(x)\n x = M.rand();\nend\n\n% Create a store database and generate a key for the current x\nstoredb = StoreDB(options.storedepth);\nkey = storedb.getNewKey();\n\n% Compute cost-related quantities for x\n[cost, grad] = getCostGrad(problem, x, storedb, key);\ngradnorm = M.norm(x, grad);\nPgrad = getPrecon(problem, x, grad, storedb, key);\ngradPgrad = M.inner(x, grad, Pgrad);\n\n% Iteration counter (at any point, iter is the number of fully executed\n% iterations so far)\niter = 0;\n\n% Save stats in a struct array info and preallocate.\nstats = savestats();\ninfo(1) = stats;\ninfo(min(10000, options.maxiter+1)).iter = [];\n\n\nif options.verbosity >= 2\n fprintf(' iter\\t cost val\\t grad. norm\\n');\nend\n\n% Compute a first descent direction (not normalized)\ndesc_dir = M.lincomb(x, -1, Pgrad);\n\n\n% Start iterating until stopping criterion triggers\nwhile true\n \n % Display iteration information\n if options.verbosity >= 2\n fprintf('%5d\\t%+.16e\\t%.8e\\n', iter, cost, gradnorm);\n end\n \n % Start timing this iteration\n timetic = tic();\n \n % Run standard stopping criterion checks\n [stop, reason] = stoppingcriterion(problem, x, options, info, iter+1);\n \n % Run specific stopping criterion check\n if ~stop && abs(stats.stepsize) < options.minstepsize\n stop = true;\n reason = sprintf(['Last stepsize smaller than minimum ' ...\n 'allowed; options.minstepsize = %g.'], ...\n options.minstepsize);\n end\n \n if stop\n if options.verbosity >= 1\n fprintf([reason '\\n']);\n end\n break;\n end\n \n \n % The line search algorithms require the directional derivative of the\n % cost at the current point x along the search direction.\n df0 = M.inner(x, grad, desc_dir);\n \n % If we didn't get a descent direction: restart, i.e., switch to the\n % negative gradient. Equivalent to resetting the CG direction to a\n % steepest descent step, which discards the past information.\n if df0 >= 0\n \n % Or we switch to the negative gradient direction.\n if options.verbosity >= 3\n fprintf(['Conjugate gradient info: got an ascent direction '...\n '(df0 = %2e), reset to the (preconditioned) '...\n 'steepest descent direction.\\n'], df0);\n end\n % Reset to negative gradient: this discards the CG memory.\n desc_dir = M.lincomb(x, -1, Pgrad);\n df0 = -gradPgrad;\n \n end\n \n \n % Execute line search\n [stepsize, newx, newkey, lsstats] = options.linesearch( ...\n problem, x, desc_dir, cost, df0, options, storedb, key);\n \n \n % Compute the new cost-related quantities for newx\n [newcost, newgrad] = getCostGrad(problem, newx, storedb, newkey);\n newgradnorm = M.norm(newx, newgrad);\n Pnewgrad = getPrecon(problem, newx, newgrad, storedb, newkey);\n newgradPnewgrad = M.inner(newx, newgrad, Pnewgrad);\n \n \n % Apply the CG scheme to compute the next search direction.\n %\n % This paper https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf\n % by Hager and Zhang lists many known beta rules. The rules defined\n % here can be found in that paper (or are provided with additional\n % references), adapted to the Riemannian setting.\n % \n if strcmpi(options.beta_type, 'steep') || ...\n strcmpi(options.beta_type, 'S-D') % Gradient Descent\n \n beta = 0;\n desc_dir = M.lincomb(newx, -1, Pnewgrad);\n \n else\n \n oldgrad = M.transp(x, newx, grad);\n orth_grads = M.inner(newx, oldgrad, Pnewgrad) / newgradPnewgrad;\n \n % Powell's restart strategy (see page 12 of Hager and Zhang's\n % survey on conjugate gradient methods, for example)\n if abs(orth_grads) >= options.orth_value\n beta = 0;\n desc_dir = M.lincomb(x, -1, Pnewgrad);\n \n else % Compute the CG modification\n \n desc_dir = M.transp(x, newx, desc_dir);\n \n switch upper(options.beta_type)\n \n case 'F-R' % Fletcher-Reeves\n beta = newgradPnewgrad / gradPgrad;\n \n case 'P-R' % Polak-Ribiere+\n % vector grad(new) - transported grad(current)\n diff = M.lincomb(newx, 1, newgrad, -1, oldgrad);\n ip_diff = M.inner(newx, Pnewgrad, diff);\n beta = ip_diff / gradPgrad;\n beta = max(0, beta);\n \n case 'H-S' % Hestenes-Stiefel+\n diff = M.lincomb(newx, 1, newgrad, -1, oldgrad);\n ip_diff = M.inner(newx, Pnewgrad, diff);\n beta = ip_diff / M.inner(newx, diff, desc_dir);\n beta = max(0, beta);\n\n case 'H-Z' % Hager-Zhang+\n diff = M.lincomb(newx, 1, newgrad, -1, oldgrad);\n Poldgrad = M.transp(x, newx, Pgrad);\n Pdiff = M.lincomb(newx, 1, Pnewgrad, -1, Poldgrad);\n deno = M.inner(newx, diff, desc_dir);\n numo = M.inner(newx, diff, Pnewgrad);\n numo = numo - 2*M.inner(newx, diff, Pdiff)*...\n M.inner(newx, desc_dir, newgrad) / deno;\n beta = numo / deno;\n\n % Robustness (see Hager-Zhang paper mentioned above)\n desc_dir_norm = M.norm(newx, desc_dir);\n eta_HZ = -1 / ( desc_dir_norm * min(0.01, gradnorm) );\n beta = max(beta, eta_HZ);\n \n case 'L-S' % Liu-Storey+ from Sato\n diff = M.lincomb(newx, 1, newgrad, -1, oldgrad);\n ip_diff = M.inner(newx, Pnewgrad, diff);\n denom = -1*M.inner(x, grad, desc_dir);\n betaLS = ip_diff / denom;\n betaCD = newgradPnewgrad / denom;\n beta = max(0, min(betaLS, betaCD));\n\n otherwise\n error(['Unknown options.beta_type. ' ...\n 'Should be steep, S-D, F-R, P-R, H-S, H-Z, or L-S.']);\n end\n \n desc_dir = M.lincomb(newx, -1, Pnewgrad, beta, desc_dir);\n \n end\n \n end\n \n % Transfer iterate info.\n storedb.removefirstifdifferent(key, newkey);\n x = newx;\n key = newkey;\n cost = newcost;\n grad = newgrad;\n Pgrad = Pnewgrad;\n gradnorm = newgradnorm;\n gradPgrad = newgradPnewgrad;\n \n % iter is the number of iterations we have accomplished.\n iter = iter + 1;\n \n % Make sure we don't use too much memory for the store database.\n storedb.purge();\n \n % Log statistics for freshly executed iteration.\n stats = savestats();\n info(iter+1) = stats;\n \nend\n\n\ninfo = info(1:iter+1);\n\nif options.verbosity >= 1\n fprintf('Total time is %f [s] (excludes statsfun)\\n', info(end).time);\nend\n\n\n% Routine in charge of collecting the current iteration stats\nfunction stats = savestats()\n stats.iter = iter;\n stats.cost = cost;\n stats.gradnorm = gradnorm;\n if iter == 0\n stats.stepsize = nan;\n stats.time = toc(timetic);\n stats.linesearch = [];\n stats.beta = 0;\n else\n stats.stepsize = stepsize;\n stats.time = info(iter).time + toc(timetic);\n stats.linesearch = lsstats;\n stats.beta = beta;\n end\n stats = applyStatsfun(problem, x, storedb, key, options, stats);\nend\n\nend\n\n\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/solvers/conjugategradient/conjugategradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6281189330346894}} {"text": "%% Alignment of the Crystal Axes\n%\n% Default is $\\vec c$ axis of highest symmetry.\n%\n% TODO: Explain the default setting in more detail.\n%\n%% Switching between different Alignment Options\n%\n% Since, especialy for lower symmetry groups, different conventions for\n% aligning the crystal axes are used it might be necessary to transform\n% data, e.g, orientations or tensors, from one convention into another. \n% This can be done using the command as it illustrated below.\n%\n% First we import the stiffness tensor Forsterite with respect to the axes\n% alignment\n\ncs = crystalSymmetry('mmm',[4.7646 10.2296 5.9942],'mineral','Olivin');\n\n% import some stiffness tensor\nfname = fullfile(mtexDataPath,'tensor','Olivine1997PC.GPa');\nC = stiffnessTensor.load(fname,cs)\n\nplot(C)\n\n%%\n% Let us now consider a different setup of the Forsterite symmetry, where\n% the $\\vec a$ axis is the longest and the $\\vec c$-axis is the shortest.\n\ncs_new = crystalSymmetry('mmm',[10.2296 5.9942 4.7646],'mineral','Olivin')\n\n%%\n% In order to represent the stiffness tensor |C| with respect to this\n% setupt we use the command .\n\nC_new = C.transformReferenceFrame(cs_new)\n\nnextAxis\nplot(C_new)\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/CrystalGeometry/SymmetryAlignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6281189289040272}} {"text": "function fx = circle ( n, x )\n\n%*****************************************************************************80\n%\n%% CIRCLE evaluates the circle function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N,2), the point coordinates.\n%\n% Output, real FX(N), the function values.\n%\n global c\n global r\n\n if ( isempty ( c ) )\n c = [ 0.0, 0.5 ];\n end\n\n if ( isempty ( r ) )\n r = 0.5;\n end\n\n nc = ones ( n, 1 ) * c;\n nr = ones ( n, 1 ) * r;\n\n fx = nr - sqrt ( sum ( ( x - nc ).^2, 2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/shoreline/circle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6281105376590786}} {"text": "function bound = AnglesLocalMaxMin(f,N)\n\n%================================================================\n% function bound = AnglesLocalMaxMin(f,N)\n%\n% This function segments f into a maximum of N supports by taking\n% the middle point between the N largest local maxima.\n% Note: the detected boundaries are given in term of indices\n%\n% Inputs:\n% -f: the function to segment\n% -N: maximal number of bands\n%\n% Outputs:\n% -bound: list of detected boundaries\n%\n% Author: Jerome Gilles\n% Institution: UCLA - Department of Mathematics\n% Year: 2013\n% Version: 1.0\n%===============================================================\n\nlocmax=zeros(size(f));\nlocmin=max(f)*ones(size(f));\n% We detect the local maxima\nfor i=2:length(f)-1\n if ((f(i-1)f(i+1)))\n locmax(i)=f(i);\n end\n \n if ((f(i-1)>f(i)) && (f(i)<=f(i+1)))\n locmin(i)=f(i);\n end\nend\n\n% We check if the endpoint are local maxima or minima (we work on the torus)\nif ((f(end)f(2)))\n locmax(1)=f(1);\nend\nif ((f(end)>f(1)) && (f(1)<=f(2)))\n locmin(1)=f(1);\nend\n\nif ((f(end-1)f(1)))\n locmax(end)=f(end);\nend\nif ((f(end-1)>f(end)) && (f(end)<=f(1)))\n locmin(end)=f(end);\nend\n\n% We keep the N-th highest maxima and their index\n[lmax,Imax]=sort(locmax,1,'descend');\nif length(lmax)>N\n Imax=sort(Imax(1:N));\nelse\n Imax=sort(Imax);\n N=length(lmax);\nend\n\n\n% We detect the lowest minima between two consecutive maxima\nbound=zeros(1,N);\nfor i=1:N\n if i==N\n [lmin,ind]=sort([locmin(Imax(i):end);locmin(1:Imax(1))]);\n tmp=lmin(1);\n n=1;\n if nlength(f)\n bound(i)=bound(i)-length(f);\n end\n else\n [lmin,ind]=sort(locmin(Imax(i):Imax(i+1)));\n tmp=lmin(1);\n n=1;\n if n 0\n Ex = -log(rand(Np(k,j),1))/b; % exponential law\n U = exp(-lambda * T / allsteps * rand(Np(k,j),1)); % Uniforms\n yy(k,j+1) = (1-lambda*T/allsteps)*yy(k,j) ...\n + sum(Ex .* U);\n else\n yy(k,j+1) = (1-lambda*T/allsteps)*yy(k,j);\n end\n end\n end\n\n ZZ = T*cumsum(yy,2)/allsteps; %Integrated Time\n Y = zeros(NSim,NTime+1);\n for m = 2:NTime+1\n Y(:,m) = ZZ(:,(m-1)*intNt);\n end\n \n Intensity = C * (Y(:,2:end)-Y(:,1:end-1)); % intensity\n DGam = gamrnd(Intensity,1/M) - gamrnd(Intensity,1/G);\n diffomegaT = omegaT(2:end) - omegaT(1:end-1); % maringale corr\n \n for m=2:NTime+1 % time loop\n lnS(:,m) = lnS(:,m-1) + (r-d)*dT ...\n + diffomegaT(m-1) + DGam(:,m-1);\n end\n pathS(:,:,l) = exp(lnS);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37618-monte-carlo-simulation-and-derivatives-pricing/StandardMonteCarlo/MC_VGGOU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6280239578481935}} {"text": "function value = he_double_product_integral ( i, j )\n\n%*****************************************************************************80\n%\n%% HE_DOUBLE_PRODUCT_INTEGRAL: integral of He(i,x)*He(j,x)*e^(-x^2/2).\n%\n% Discussion:\n%\n% VALUE = integral ( -oo < x < +oo ) He(i,x)*He(j,x) exp(-x^2/2) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, J, the polynomial indices.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( i ~= j )\n value = 0.0;\n else\n value = r8_factorial ( i );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pce_ode_hermite/he_double_product_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6280239572258198}} {"text": "clear all; close all; clc;\n\n% pull=[3 5 7 9 11];\n% start=1:20;\n% q=abs(start-pull(1));\n% [x,n2]=min(q);\n% \n% for j=1:4\n% q=abs(start-pull(j));\n% [x,n2]=min(q)\n% start=start([1:n2-1 n2+1:(20-j)]);\n% start'\n% end\n% \n% break\n\n\n\n%%\nL=10; x3=-L:0.1:L; n=length(x3)-1; % define domain\nx2=x3(1:n); k=(2*pi/(2*L))*[0:n/2-1 -n/2:-1]; % k-vector\nye=exp(-(x2.^2)); ye2=exp((x2.^2)/2); % define Gaussians\nfor j=0:9 % loop through 10 modes\n yd=real(ifft(((i*k).^j).*fft(ye))); % 2nd derivative \n mode=((-1)^(j))*(((2^j)*factorial(j)*sqrt(pi))^(-0.5))*ye2.*yd;\n y(:,j+1)=(mode).'; % store modes as columns\nend\n\nx=x2(n/2+1-40:n/2+1+40); % keep only -4n1\n jlook=[1:n1-1 n1+1:n2-1 n2+1:81];\nelse\n jlook=[1:n2-1 n2+1:n1-1 n1+1:81];\nend\n\njlook\nbreak\nfor jloop=jlook\n\ns=zeros(n,1); \ns(n1)=1; s(n2)=1;\ns(jloop)=1;\n\n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n%figure(3), subplot(2,2,3), pcolor(10:-1:1,1:10,(M2'));, colormap(hot)\n\n\nfor j=1:10 % reconstruction using gappy\n ftild(j,1)=trapz(x,s.*(f.*yharm(:,j)));\nend\natild=M2\\ftild; % compute error\nf3=yharm*atild;\nEr(3)=norm(f3-f);\n\n%con3(jloop)=cond(M2);\ncon3(jloop)=2*sum(diag(M2))-sum(M2(:));\n\nend\n%[s3,n3]=min(con3(jlook))\n[s3,n3]=max(con3(jlook))\n\n% sensor 4\njlook=[1:n1-1 n1+1:n2-1 n2+1:n3-1 n3+1:81];\nfor jloop=jlook\n\ns=zeros(n,1); \ns(n1)=1; s(n2)=1;\ns(jloop)=1;\n\n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n%figure(3), subplot(2,2,4),pcolor(10:-1:1,1:10,(M2'));, colormap(hot)\n\nfor j=1:10 % reconstruction using gappy\n ftild(j,1)=trapz(x,s.*(f.*yharm(:,j)));\nend\natild=M2\\ftild; % compute error\nf4=yharm*atild;\nEr(4)=norm(f4-f);\n\n%con4(jloop)=cond(M2);\ncon4(jloop)=2*sum(diag(M2))-sum(M2(:));\n\n\nend\n%[s4,n4]=min(con4(jlook))\n[s4,n4]=max(con4(jlook))\n\n\n\n\nfigure(1)\nsubplot(4,1,1), bar((con)), axis([1 81 0 1])\nsubplot(4,1,2), bar((con2)), axis([1 81 0 1])\nsubplot(4,1,3), bar((con3)), axis([1 81 0 1]) \nsubplot(4,1,4), bar((con4)), axis([1 81 0 1]) \n\n\n\nbreak\n\n%% Willcox: condition number\n\n% pull=[3 5 7 9 11];\n% start=1:20;\n% q=abs(start-pull(1));\n% [x,n2]=min(q);\n% \n% for j=1:4\n% q=abs(start-pull(j));\n% [x,n2]=min(q)\n% start=start([1:n2-1 n2+1:(20-j)]);\n% start'\n% end\n% \n% break\nclear f1\nclear f2\nclear ns\nns=[]; jlook=1:81; \n\ncount=1;\nfor jsense=1:20\n\nfor jloop=1:(82-jsense)\ns=zeros(n,1); s(ns)=1;\ns(jlook(jloop))=1; \n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\ncon(jloop)=cond(M2);\n\nend\n\nlength(con)\n[s1,n1]=min(con)\nkond(jsense)=s1;\nclear con\nns=[ns n1];\n\njlook=jlook([1:n1-1 n1+1:(81-count+1)]);\ncount=count+1;\n\n% reconstruct\ns=zeros(n,1); \ns(ns)=1;\n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n\nfor j=1:10 % reconstruction using gappy\n ftild(j,1)=trapz(x,s.*(f.*yharm(:,j)));\nend\natild=M2\\ftild; % compute error\nf1(:,jsense)=yharm*atild;\nErrr(jsense)=norm(f1(:,jsense)-f);\nscum(:,jsense)=s;\n\nend\n\nfigure(4)\nsubplot(2,1,2), bar(log(Errr+1))\nsubplot(2,1,1), bar(log(kond))\n\nsubplot(2,1,2), set(gca,'Xlim',[0 21],'Xtick',[1 5 10 15 20],'Xticklabel',{'','','','',''},'Ylim',[0 12],'Ytick',[0 4 8 12],'Yticklabel',{'','','',''})\nsubplot(2,1,1), set(gca,'Xlim',[0 21],'Xtick',[1 5 10 15 20],'Xticklabel',{'','','','',''},'Ylim',[0 42],'Ytick',[0 20 40],'Yticklabel',{'','',''})\n\n%figure(6), bar(s)\n\n\nfigure(7), \ntiter=[1:20 25]; f1=[f1 f]; titer2=[9:20 25], f2=[f1(:,9:20) f];\nsubplot(2,2,1), waterfall(x,titer,f1.'), colormap([0 0 0]), view(-150,50)\nsubplot(2,2,2), waterfall(x,titer2,f2.'), colormap([0 0 0]), view(-150,50)\n\n\nsubplot(2,2,1), set(gca,'Zlim',[-2 8],'Xlim',[-4 4],'Xtick',[-4 0 4],'Xticklabel',{'','',''}, ...\n 'Ylim',[0 25],'Ytick',[1 10 20],'Yticklabel',{'','',''},'Ztick',[-2 0 4 8],'Zticklabel',{'','','',''})\nsubplot(2,2,2), set(gca,'Zlim',[-.2 3],'Xlim',[-4 4],'Xtick',[-4 0 4],'Xticklabel',{'','',''}, ...\n 'Ylim',[0 25],'Ytick',[1 10 20],'Yticklabel',{'','',''},'Ztick',[0 1 2 3],'Zticklabel',{'','','',''})\n\n\nfigure(8)\n%bar3(scum)\naxes('position',[.05 .05 .9 .35])\nscum2=[scum(:,[1:11 13:19])];\npcolor(-scum2.'), colormap(hot), axis off\n\n%bar3(scum2)\n\n%caxis([0 1]), axis off\n\n\n\n%% Willcox: diagonal sum\n\n% pull=[3 5 7 9 11];\n% start=1:20;\n% q=abs(start-pull(1));\n% [x,n2]=min(q);\n% \n% for j=1:4\n% q=abs(start-pull(j));\n% [x,n2]=min(q)\n% start=start([1:n2-1 n2+1:(20-j)]);\n% start'\n% end\n% \n% break\nclear f1\nclear f2\nclear ns\nclear s\nns=[]; jlook=1:81; \n\ncount=1;\nfor jsense=1:20\n\nfor jloop=1:(82-jsense)\ns=zeros(n,1); s(ns)=1;\ns(jlook(jloop))=1; \n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n%con(jloop)=cond(M2);\ncon(jloop)=2*sum(diag(M2))-sum(M2(:));\n\nend\n\n%[s1,n1]=min(con)\n[s1,n1]=max(con)\nkond(jsense)=s1;\nclear con\nns=[ns n1];\n\njlook=jlook([1:n1-1 n1+1:(81-count+1)]);\ncount=count+1;\n\n% reconstruct\ns=zeros(n,1); \ns(ns)=1;\n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n\nfor j=1:10 % reconstruction using gappy\n ftild(j,1)=trapz(x,s.*(f.*yharm(:,j)));\nend\natild=M2\\ftild; % compute error\nf1(:,jsense)=yharm*atild;\nErrr(jsense)=norm(f1(:,jsense)-f);\nscum(:,jsense)=s;\n\nend\n\nfigure(4)\nsubplot(2,1,2), bar(Errr)\nsubplot(2,1,1), bar((kond))\n\nsubplot(2,1,2), set(gca,'Xlim',[0 21],'Xtick',[1 5 10 15 20],'Xticklabel',{'','','','',''},'Ylim',[0 12],'Ytick',[0 4 8 12],'Yticklabel',{'','','',''})\nsubplot(2,1,1), set(gca,'Xlim',[0 21],'Xtick',[1 5 10 15 20],'Xticklabel',{'','','','',''},'Ylim',[0 42],'Ytick',[0 20 40],'Yticklabel',{'','',''})\n\n%figure(6), bar(s)\n\n\nfigure(7), \ntiter=[1:20 25]; f1=[f1 f]; titer2=[9:20 25], f2=[f1(:,9:20) f];\nsubplot(2,2,1), waterfall(x,titer,f1.'), colormap([0 0 0]), view(-150,50)\nsubplot(2,2,2), waterfall(x,titer2,f2.'), colormap([0 0 0]), view(-150,50)\n\n\nsubplot(2,2,1), set(gca,'Zlim',[-2 8],'Xlim',[-4 4],'Xtick',[-4 0 4],'Xticklabel',{'','',''}, ...\n 'Ylim',[0 25],'Ytick',[1 10 20],'Yticklabel',{'','',''},'Ztick',[-2 0 4 8],'Zticklabel',{'','','',''})\nsubplot(2,2,2), set(gca,'Zlim',[-.2 3],'Xlim',[-4 4],'Xtick',[-4 0 4],'Xticklabel',{'','',''}, ...\n 'Ylim',[0 25],'Ytick',[1 10 20],'Yticklabel',{'','',''},'Ztick',[0 1 2 3],'Zticklabel',{'','','',''})\n\nfigure(8)\n%bar3(scum)\naxes('position',[.05 .05 .9 .35])\nscum2=[scum(:,[1:11 13:19])];\npcolor(-scum2.'), colormap(hot), axis off\n\n%bar3(scum2)\n\n%caxis([0 1]), axis off\n\n\n\n\n\n%% Test Random trials with P% of measurements\n% spectrum of mu\nbreak\nper=[20 40 60 81];\nfor thresh=1:4\n\n\nn2=randsample(n,per(thresh));\ns=zeros(n,1); s(n2)=1;\n\n\nfor j=1:10\n for jj=1:j\n Area=trapz(x,s.*(yharm(:,j).*yharm(:,jj)));\n M2(j,jj)=Area; M2(jj,j)=Area;\n end\nend\n\n[v,d]=eigs(M2);\nsubplot(2,2,thresh)\nplot(real(diag(d)),imag(diag(d)),'ko','Linewidth',[2])\naxis([0 2 -1 1])\nend\n\n\n\n\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH12/old_extra/deimPLOT/gappy4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6279296646999176}} {"text": "function linpack_d_test31 ( )\n\n%*****************************************************************************80\n%\n%% TEST31 tests DTRSL.\n%\n% Discussion:\n%\n% DTRSL solves triangular linear systems.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n lda = n;\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST31\\n' );\n fprintf ( 1, ' For a triangular matrix,\\n' );\n fprintf ( 1, ' DTRSL solves a linear system.\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Lower triangular matrix A.\n%\n [ a, seed ] = r8mat_uniform_01 ( n, n, seed );\n\n for i = 1 : n\n for j = i+1 : n\n a(i,j) = 0.0;\n end\n end\n \n for i = 1 : n\n x(i,1) = i;\n end\n\n b(1:n,1) = a(1:n,1:n) * x(1:n,1);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For a lower triangular matrix A,\\n' );\n fprintf ( 1, ' solve A * x = b\\n' );\n\n job = 00;\n\n [ b, info ] = dtrsl ( a, lda, n, b, job );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The solution (should be 1,2,3,4,5):\\n' );\n fprintf ( 1, '\\n' );\n \n for i = 1 : n\n fprintf ( 1, ' %6d %14f\\n', i, b(i,1) );\n end\n \n b(1:n,1) = a(1:n,1:n)' * x(1:n,1);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For a lower triangular matrix A,\\n' );\n fprintf ( 1, ' solve A'' * x = b\\n' );\n\n job = 10;\n\n [ b, info ] = dtrsl ( a, lda, n, b, job );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The solution (should be 1,2,3,4,5):\\n' );\n fprintf ( 1, '\\n' );\n \n for i = 1 : n\n fprintf ( 1, ' %6d %14f\\n', i, b(i,1) );\n end\n%\n% Upper triangular matrix A.\n%\n [ a, seed ] = r8mat_uniform_01 ( n, n, seed );\n\n for i = 1 : n\n for j = 1 : i - 1\n a(i,j) = 0.0;\n end\n end\n \n for i = 1 : n\n x(i,1) = i;\n end\n \n b(1:n,1) = a(1:n,1:n) * x(1:n,1);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For an upper triangular matrix A,\\n' );\n fprintf ( 1, ' solve A * x = b\\n' );\n\n job = 01;\n\n [ b, info ] = dtrsl ( a, lda, n, b, job );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The solution (should be 1,2,3,4,5):\\n' );\n fprintf ( 1, '\\n' );\n \n for i = 1 : n\n fprintf ( 1, ' %6d %14f\\n', i, b(i,1) );\n end\n\n b(1:n,1) = a(1:n,1:n)' * x(1:n,1);\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For an upper triangular matrix A,\\n' );\n fprintf ( 1, ' solve A'' * x = b\\n' );\n\n job = 11;\n\n [ b, info ] = dtrsl ( a, lda, n, b, job );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The solution (should be 1,2,3,4,5):\\n' );\n fprintf ( 1, '\\n' );\n \n for i = 1 : n\n fprintf ( 1, ' %6d %14f\\n', i, b(i,1) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/linpack_d_test31.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6277834887804977}} {"text": "function [ddCs, rhsCs] = electrodeConcentration(dCs,cs_barrato,T,jflux,param)\n% electrodeConcentration describes the ODE of the concentration of lithium ions within the\n% electrodes.\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\nif(param.SolidPhaseDiffusion==1 || param.SolidPhaseDiffusion==2)\n % Cathode\n rhsCs_p =((-3/param.Rp_p)*jflux(1:param.Np));\n ddCs_p = dCs(1:param.Np) - rhsCs_p;\n \n % Anode\n rhsCs_n = ((-3/param.Rp_n)*jflux(param.Np+1:end));\n ddCs_n = dCs(param.Np+1:end) - rhsCs_n;\nelse\n switch param.SolidPhaseDiffusionNumericalScheme\n % Use the FDM method for the solid phase diffusion\n case 1\n [rhsCs_p, rhsCs_n, ddCs_p, ddCs_n] = FDM9orderElectrodeDiffusion(T, cs_barrato, jflux, dCs, param);\n % Use the spectral method for the discretization of the solid phase\n % diffusion\n case 2\n [rhsCs_p, rhsCs_n, ddCs_p, ddCs_n] = spectralMethodElectrodeDiffusion(T, cs_barrato, jflux, dCs, param);\n end\nend\nrhsCs = [rhsCs_p;rhsCs_n];\nddCs = [ddCs_p;ddCs_n];\nend\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/P2D_equations/electrodeConcentration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6277679479547807}} {"text": "function x=stdtinv(p,v)\n% Inverse Cumulative Distribution Function (CDF) of the Standardized T\n% distribution; Maps [0,1] to a standardized Students-t with V degrees of freedom\n%\n% USAGE:\n% X = stdtinv(P,V)\n%\n% INPUTS:\n% P - Values to be inverted, P in [0,1]\n% V - Degree of freedom parameters, either scalar or size(X)\n%\n% OUTPUTS:\n% X - Standardized T distributed random variables corresponding to P\n%\n% COMMENTS:\n% V>2\n%\n% REFERENCES:\n% [1] Cassella and Berger (1990) 'Statistical Interence'\n%\n% See also STDTCDF, STDTINV, STDTRND, STDTLOGLIK, TPDF\n\n% Copyright:\n% Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\n\nif nargin~=2 \n error('2 inputs required')\nend\n\n[err, errtext, sizeOut, v] = iscompatible(1,v,size(p));\nif err\n error(errtext)\nend\n\nx=tinv(p,v);\n\nstdev=sqrt(v./(v-2));\nstdev(v<=2)=NaN;\nx=x./stdev;", "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/distributions/stdtinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6277679449229445}} {"text": "% The null space of a 3DOF robot when considered redundant.\n% if the task m=(vx, vy), then the robot is redundant in lambda=3\n%\n% Copyright (C) 2016, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction null_space_3dofplanar\n% link lengths\nrobot = load_robot('example', '3dofplanar');\nq = [pi/2 pi/2 pi/2]';\n\nqs = [];\nqds = [];\nmanips = [];\nfor i=1:300\n [qb, manip] = null_movement(robot, q);\n q = q + 0.1*qb;\n qs = [qs q];\n qds = [qds qb];\n manips = [manips manip];\nend\n\nanimate(robot, qs(:,1:15:end))\nfigure, plot(manips), legend('manipulability')\nfigure, plot(qs'), legend('q_1', 'q_2', 'q_3')\nfigure, plot(qds'), legend('qd_1', 'qd_2', 'qd_3')\n%q = q + 0.01*ns';\n \n\nfunction [ns, manip] = null_movement(robot, q)\nJ = manipulator_jacobian(robot, q);\n% consider only vx, vy\nJ = J(1:2, :);\niJm = moore_penrose(J);\nP = (eye(3)-iJm*J)\n% project to null space\nns = P*[1 0 0]';\nmanip = det(J*J')\n\n\nfunction iJm = moore_penrose(J)\niJm = J'*inv(J*J');\n\n \n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/book/null_space_3dofplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6277679388592716}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n% relationship of linear convolution with circular convolution\n\n\n% 4-point circular convolution \nx1=[1,2,3,4];\nx2=[3,2,5,1];\nN=length(x1);\nfor m=0:N-1\np(m+1)=mod(-m,N);\nx2s(1+m)=x2(1+p(m+1));\nend\nx2s\nfor n=0:N-1\n x2sn=circshift(x2s',n);\n y2(n+1)=x1*x2sn;\nend\ny2\n\n\n% 7-point circular convolution \nx11=[ x1 0 0 0];\nx22=[x2 0 0 0];\nN=length(x11);\nfor m=0:N-1\np(m+1)=mod(-m,N);\nend\nfor m=0:N-1\nx22s(1+m)=x22(1+p(m+1));\nend\nfor n=0:N-1\n x22sn=circshift(x22s',n);\n y22(n+1)=x11*x22sn;\nend\ny22\n\n\n%linear convolution \ny1=conv(x1,x2)\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/7/c78_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6277280472679364}} {"text": "% GP_PREDICT_PSEUDO - Computes the predictive distribution of a Gaussian\n% process using pseudo inputs.\n%\n% Usage:\n%\n% F_MEAN = GP_PREDICT_PSEUDO(Y, V, K_FP, K_PP, K_PH, K_H)\n% [F_MEAN, F_VAR] = GP_PREDICT_PSEUDO(...)\n%\n% The marginal of a conditional model\n%\n% Y|F ~ N(F, V)\n%\n% is approximated by\n%\n% Y ~ N(0, K_FP*INV(K_PP)*K_FP' + V)\n%\n% Y : Nx1 vector of observations\n% V : NxN diagonal matrix of noise covariance, or a function V(X) which\n% solves V\\X\n% K_FP : NxM covariance matrix of function values at observation inputs\n% and at pseudo inputs \n% K_PP : MxM covariance matrix of function values at pseudo inputs\n% K_PH : MxK covariance matrix of function values at pseudo inputs and at\n% inputs to be predicted\n% K_H : Kx1 vector of variances of function values at inputs to be\n% predicted\n%\n% See also GP_LEARN_PSEUDO, GP_PREDICT.\n\n% Last modified 2011-01-27\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction [f_mean, f_var] = gp_predict_pseudo(y, V, K_pf, K_pp, K_ph, k_h)\n\nif isnumeric(V)\n % Get a solver for V\\z\n inv_V = get_linsolve_cov(V);\nelse\n % A function handle which solves V\\z\n inv_V = V;\nend\n\n% TODO: \n%\n% - Take K_pf instead of K_fp\n%\n% - Take V as a vector?\n\n[L_p,p] = chol(K_pp, 'lower');\nif p~=0\n figure\n imagesc(K_pp);\n error('Matrix not positive definite');\nend\n\nZ_f = linsolve_tril(L_p, K_pf);\n\nLambda = speye(size(K_pp)) + Z_f*inv_V(Z_f');\ninv_Lambda = get_linsolve_cov(Lambda);\n\nf_mean = K_ph' * linsolve_triu(L_p, inv_Lambda(Z_f*inv_V(y)), true);\nif nargout >= 2\n Z_h = linsolve_tril(L_p, K_ph);\n f_var = k_h(:) - dot(Z_h, Z_h - inv_Lambda(Z_h),1)';\nend\n\n% $$$ Lambda = K_pp + K_fp' * inv_V(K_fp);\n% $$$ inv_Lambda = get_linsolve_cov(Lambda);\n% $$$ inv_Kpp = get_linsolve_cov(K_pp);\n% $$$ f_mean = K_ph' * inv_Lambda(K_fp' * inv_V(y));\n% $$$ f_var = k_h(:) - dot(K_ph, inv_Kpp(K_ph) - inv_Lambda(K_ph),1)';\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gp/gp_predict_pseudo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.6277174091943355}} {"text": "function K = spikernel( k, d1, d2, ind1, ind2, kerparam)\n\n% K = spikernel( k, d1, d2, ind1, ind2, kerparam)\n% computes the spikernel between two sequences of spiking activity\n%\n% kerparam{1} = N; max subsequence lengths (the kernel compares subsequences of lengths 1 to N and returns a sum of kernels)\n% kerparam{2} = lam; \\lambda parameter from article\n% kerparam{3} = mu; \\mu parameter from article\n% kerparam{4} = p; the q parameter in the article - the parameter that is used in the sum of kernels to weigh them differently\n% kerparam{5} = bins; the number of bins used; we need this to reshape the data correctly\n% kerparam{6} = nneurons; the number of neurons; we need this to reshape the data correctly\n%\n% This code uses the spikernel function, defined in:\n% Spikernels: Embedding Spiking Neurons in Inner-Product Spaces \n% Lavi Shpigelman, Yoram Singer, Rony Paz and Eilon Vaadia \n% Advances in Neural Information Processing Systems (NIPS) 15 \n% MIT Press, Cambridge, MA, 2003. \n%\n% for further details see Fspikernel.m\n\nbins = kerparam{5};\nnneurons = kerparam{6}; \n\nxx = get_x( d1, ind1);\nyy = get_x( d2, ind2);\nK = zeros( size( yy,1), size( xx,1));\n\nfor i = 1:size( xx, 1)\n for j = 1:size( yy,1)\n K( j, i) = Fspikernel( reshape( yy( j, :), bins, nneurons), reshape( xx( i,:), bins, nneurons), kerparam{1}, kerparam{2}, kerparam{3}, kerparam{4});\n% K( j, i) = K( i, j);\n% if bins >= 100 disp(sprintf('we''re at: (%d, %d)', i,j)); end %<-- if it takes longer, print out, where we are\n end\nend", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/spider/basic/@kernel/spikernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6277174017696959}} {"text": "function lik = lik_multinom(varargin)\n%LIK_MULTINOM Create a multinom likelihood structure \n%\n% Description\n% LIK = LIK_MULTINOM creates multinom likelihood for multi-class\n% count data. The observed numbers in each class with C classes is given\n% as 1xC vector.\n%\n% The likelihood is defined as follows:\n% __ n __ C \n% p(y|f^1, ..., f^C, z) = || i=1 [ gamma(N+1) || c=1 p_i^c^(y_i^c)/gamma(y_i^c+1)]\n%\n% where p_i^c = exp(f_i^c)/ (sum_c=1^C exp(f_i^c)) is the succes \n% probability for class c, which is a function of the latent variable \n% f_i^c for the corresponding class and N=sum(y) is the number of trials.\n%\n% See also\n% GP_SET, LIK_*\n\n% Copyright (c) 2010 Jaakko Riihim�ki, Pasi Jyl�nki\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2010 Jarno Vanhatalo\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'LIK_MULTINOM';\n ip.addOptional('lik', [], @isstruct);\n ip.parse(varargin{:});\n lik=ip.Results.lik;\n\n if isempty(lik)\n init=true;\n lik.type = 'Multinom';\n lik.nondiagW = true;\n else\n if ~isfield(lik,'type') || ~isequal(lik.type,'Multinom')\n error('First argument does not seem to be a valid likelihood function structure')\n end\n init=false;\n end\n\n if init\n % Set the function handles to the subfunctions\n lik.fh.pak = @lik_multinom_pak;\n lik.fh.unpak = @lik_multinom_unpak;\n lik.fh.ll = @lik_multinom_ll;\n lik.fh.llg = @lik_multinom_llg; \n lik.fh.llg2 = @lik_multinom_llg2;\n lik.fh.llg3 = @lik_multinom_llg3;\n lik.fh.predy = @lik_multinom_predy;\n lik.fh.invlink = @lik_multinom_invlink;\n lik.fh.recappend = @lik_multinom_recappend;\n end\n\nend \n\nfunction [w,s] = lik_multinom_pak(lik)\n%LIK_MULTINOM_PAK Combine likelihood parameters into one vector.\n%\n% Description \n% W = LIK_MULTINOM_PAK(LIK) takes a likelihood structure LIK and\n% returns an empty verctor W. If Multinom likelihood had\n% parameters this would combine them into a single row vector\n% W (see e.g. lik_negbin). This is a mandatory subfunction used \n% for example in energy and gradient computations.\n% \n%\n% See also\n% LIK_MULTINOM_UNPAK, GP_PAK\n \n w = []; s = {};\nend\n\n\nfunction [lik, w] = lik_multinom_unpak(lik, w)\n%LIK_MULTINOM_UNPAK Extract likelihood parameters from the vector.\n%\n% Description\n% W = LIK_MULTINOM_UNPAK(W, LIK) Doesn't do anything.\n% \n% If Multinom likelihood had parameters this would extracts them\n% parameters from the vector W to the LIK structure. This is a \n% mandatory subfunction used for example in energy and gradient \n% computations.\n% \n%\n% See also\n% LIK_MULTINOM_PAK, GP_UNPAK\n\n lik=lik;\n w=w;\nend\n\n\nfunction ll = lik_multinom_ll(lik, y, f, z)\n%LIK_MULTINOM_LL Log likelihood\n%\n% Description\n% LL = LIK_MULTINOM_LL(LIK, Y, F) takes a likelihood structure\n% LIK, class counts Y (NxC matrix), and latent values F (NxC\n% matrix). Returns the log likelihood, log p(y|f,z). This \n% subfunction is needed when using Laplace approximation or \n% MCMC for inference with non-Gaussian likelihoods. This \n% subfunction is also used in information criteria \n% (DIC, WAIC) computations.\n%\n% See also\n% LIK_MULTINOM_LLG, LIK_MULTINOM_LLG3, LIK_MULTINOM_LLG2, GPLA_E\n \n f=reshape(f,size(y));\n expf = exp(f);\n p = expf ./ repmat(sum(expf,2),1,size(expf,2));\n N = sum(y,2);\n \n ll = sum(gammaln(N+1) - sum(gammaln(y+1),2) + sum(y.*log(p),2) );\n \nend\n\n\nfunction llg = lik_multinom_llg(lik, y, f, param, z)\n%LIK_MULTINOM_LLG Gradient of the log likelihood\n%\n% Description\n% LLG = LIK_MULTINOM_LLG(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F. Returns\n% the gradient of the log likelihood with respect to PARAM. At\n% the moment PARAM can be 'param' or 'latent'. This subfunction \n% is needed when using Laplace approximation or MCMC for inference \n% with non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG2, LIK_MULTINOM_LLG3, GPLA_E\n \n f=reshape(f,size(y));\n C = size(y,2);\n expf2 = exp(f);\n N=sum(y, 2);\n pi2 = (N*ones(1,C)).*expf2./(sum(expf2, 2)*ones(1,C));\n pi_vec=pi2(:);\n llg = y(:)-pi_vec;\n \nend\n\n\nfunction [pi_vec, pi_mat] = lik_multinom_llg2(lik, y, f, param, z)\n%LIK_MULTINOM_LLG2 Second gradients of the log likelihood\n%\n% Description \n% LLG2 = LIK_MULTINOM_LLG2(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F. Returns\n% the Hessian of the log likelihood with respect to PARAM. At\n% the moment PARAM can be only 'latent'. LLG2 is a vector with\n% diagonal elements of the Hessian matrix (off diagonals are\n% zero). This subfunction is needed when using Laplace \n% approximation or EP for inference with non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG, LIK_MULTINOM_LLG3, GPLA_E\n \n% multinom:\n [n,nout]=size(y);\n N = sum(y,2)*ones(1,nout);\n f=reshape(f,n,nout);\n \n expf2 = exp(f);\n pi2 = expf2./(sum(expf2, 2)*ones(1,nout));\n pi_vec=pi2(:).*N(:);\n \n pi_mat=zeros(nout*n, n);\n for i1=1:nout\n pi_mat((1+(i1-1)*n):(nout*n+1):end)=pi2(:,i1).*sqrt(N(:,i1)); \n end\n % D = diag(pi_vec);\n % llg2 = -D + pi_mat*pi_mat';\n \nend \n\nfunction [dw_mat] = lik_multinom_llg3(lik, y, f, param, z)\n%LIK_MULTINOM_LLG3 Third gradients of the log likelihood\n%\n% Description\n% LLG3 = LIK_MULTINOM_LLG3(LIK, Y, F, PARAM) takes a likelihood\n% structure LIK, class labels Y, and latent values F and\n% returns the third gradients of the log likelihood with\n% respect to PARAM. At the moment PARAM can be only 'latent'. \n% LLG3 is a vector with third gradients. This subfunction is \n% needed when using Laplace approximation for inference with \n% non-Gaussian likelihoods.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_LLG, LIK_MULTINOM_LLG2, GPLA_E, GPLA_G\n \n [n,nout] = size(y);\n f2 = reshape(f,n,nout);\n \n N=sum(y, 2);\n expf2 = exp(f2);\n pi2 = expf2./(sum(expf2, 2)*ones(1,nout));\n pi_vec=pi2(:);\n \n dw_mat=zeros(nout,nout,nout,n);\n \n for cc3=1:nout\n for ii1=1:n\n \n pic=pi_vec(ii1:n:(nout*n));\n for cc1=1:nout\n for cc2=1:nout\n \n % multinom third derivatives\n cc_sum_tmp=0;\n if cc1==cc2 && cc1==cc3 && cc2==cc3\n cc_sum_tmp=cc_sum_tmp+pic(cc1);\n end\n if cc1==cc2\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc3);\n end\n if cc2==cc3\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc2);\n end\n if cc1==cc3\n cc_sum_tmp=cc_sum_tmp-pic(cc1)*pic(cc2);\n end\n cc_sum_tmp=cc_sum_tmp+2*pic(cc1)*pic(cc2)*pic(cc3);\n \n dw_mat(cc1,cc2,cc3,ii1)=cc_sum_tmp.*N(ii1);\n end\n end\n end\n end\n \n \nend\n\nfunction [lpy, Ey, Vary] = lik_multinom_predy(lik, Ef, Varf, yt, zt)\n%LIK_MULTINOM_PREDY Returns the predictive mean, variance and density of y\n%\n% Description\n% LPY = LIK_MULTINOM_PREDY(LIK, EF, VARF YT)\n% Returns logarithm of the predictive density PY of YT, that is\n% p(yt | y) = \\int p(yt | f) p(f|y) df.\n% This requires also the incedence counts YT. This subfunction \n% is needed when computing posterior predictive distributions for \n% future observations.\n%\n% [LPY, EY, VARY] = LIK_MULTINOM_PREDY(LIK, EF, VARF, YT) takes a\n% likelihood structure LIK, posterior mean EF and posterior\n% Variance VARF of the latent variable and returns the\n% posterior predictive mean EY and variance VARY of the\n% observations related to the latent variables. This subfunction\n% is needed when computing posterior predictive distributions for\n% future observations.\n%\n\n%\n% See also\n% GPLA_PRED, GPEP_PRED, GPMC_PRED\n \n N=sum(yt,2);\n S=10000;\n [ntest, nout]=size(yt);\n pi=zeros(ntest,nout);\n lpy=zeros(ntest,nout);\n Ey=zeros(ntest,nout);\n Vary=zeros(size(Varf));\n Ef=reshape(Ef(:),ntest,nout);\n [notused,notused,c] =size(Varf);\n if c>1\n mcmc=false;\n else\n mcmc=true;\n Varf=reshape(Varf(:), ntest, nout);\n end\n for i1=1:ntest\n if mcmc\n Sigm_tmp = (Varf(i1,:));\n f_star=bsxfun(@plus, Ef(i1,:), bsxfun(@times, sqrt(Sigm_tmp), ...\n randn(S,nout)));\n else\n Sigm_tmp=(Varf(:,:,i1)'+Varf(:,:,i1))./2;\n f_star=mvnrnd(Ef(i1,:), Sigm_tmp, S);\n end\n \n tmp = exp(f_star);\n tmp = tmp./(sum(tmp, 2)*ones(1,size(tmp,2)));\n \n if nargout > 1\n Ey(i1,:) = N(i1).*mean(tmp);\n for z1 = 1:nout;\n for z2 = 1:nout\n for z3=1:S\n Var_tmp(:,:,z3) = (diag(tmp(z3,:)) - tmp(z3,:)'*tmp(z3,:));\n end\n if mcmc\n Vary(i1+(0:nout-1)*ntest,:) = diag(N(i1).*mean(Var_tmp,3));\n else\n Vary(:,:,i1) = N(i1).*mean(Var_tmp,3);\n end\n end\n end\n end\n lpy=[];\n if ~isempty(yt)\n ytmp = repmat(yt(i1,:),S,1);\n lpy(i1,:) = log(mean( mnpdf(ytmp,tmp) ));\n end\n end\n lpy=lpy(:);\n Ey=Ey(:);\nend\n\nfunction p = lik_multinom_invlink(lik, f, z)\n%LIK_MULTINOM_INVLINK Returns values of inverse link function\n% \n% Description \n% P = LIK_MULTINOM_INVLINK(LIK, F) takes a likelihood structure LIK and\n% latent values F and returns the values of inverse link function P.\n% This subfunction is needed when using function gp_predprctmu.\n%\n% See also\n% LIK_MULTINOM_LL, LIK_MULTINOM_PREDY\np = multinominv(f).*z;\nend\n\nfunction reclik = lik_multinom_recappend(reclik, ri, lik)\n%RECAPPEND Append the parameters to the record\n%\n% Description \n% RECLIK = LIK_MULTINOM_RECAPPEND(RECLIK, RI, LIK) takes a\n% likelihood record structure RECLIK, record index RI and\n% likelihood structure LIK with the current MCMC samples of\n% the parameters. Returns RECLIK which contains all the old\n% samples and the current samples from LIK. This subfunction \n% is needed when using MCMC sampling (gp_mc).\n% \n% See also\n% GP_MC\n\n if nargin == 2\n reclik.type = 'Multinom';\n reclik.nondiagW = true;\n\n % Set the function handles\n reclik.fh.pak = @lik_multinom_pak;\n reclik.fh.unpak = @lik_multinom_unpak;\n reclik.fh.ll = @lik_multinom_ll;\n reclik.fh.llg = @lik_multinom_llg; \n reclik.fh.llg2 = @lik_multinom_llg2;\n reclik.fh.llg3 = @lik_multinom_llg3;\n reclik.fh.predy = @lik_multinom_predy;\n reclik.fh.invlink = @lik_multinom_invlink;\n reclik.fh.recappend = @lik_multinom_recappend;\n end\n \nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/lik_multinom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6277173961435172}} {"text": "% [x, Covx, Covx_x, entropy] = rts_smoother_step(x, Covx, x_s, Covx_s, A, Q)\n\n% Last modified 2011-10-19\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@aalto.fi)\n\nfunction [x, Covx, Covx_x, entropy] = rts_smoother_step(x, Covx, x_s, Covx_s, A, Q)\n% Perform the RTS smoothing step\n\nx_p = A*x;\nCovx_p = A*Covx*A' + Q;\n\nS = (Covx*A') / Covx_p;\nx = x + S*(x_s-x_p);\nif nargout >= 2\n Covx = Covx + S*(Covx_s-Covx_p)*S';\nend\nif nargout >= 3\n Covx_x = S*Covx_s;\nend\nif nargout >= 4\n % Compute entropy term:\n %\n % INT[ p(x_n, x_(n+1) | Y) log p(x_n | Y, x_(n+1)) dx_n dx_(n+1) ]\n Cov_joint = [Covx Covx_x\n Covx_x' Covx_s];\n entropy = gaussian_entropy(logdet_cov(Cov_joint), size(Cov_joint,1)) ...\n - gaussian_entropy(logdet_cov(Covx_s), size(Covx_s,1));\n \nend", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/signal_processing/rts_smoother_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6276992050018992}} {"text": "function output = relaxMtFitFuncLs(x, m, W_B, W_F, T2_B, R1, S0, t_m, t_s, t_r);\n% function output = relaxMtFitFuncLs(x, m, W_B, W_F, T2_B, R1, S0, t_m, t_s, t_r);\n% inputs:\n% x = [k, f] where k is the cross-relaxation rate constant defined\n% for the transition from free pool (F) to bound pool (B), f is the\n% fraction of bound spins expressed in terms of concentrations as f =\n% [B]/([B]+[F])\n% m: MT(:,ii) ??\n%\n% W_B: Effective saturation rate of the bound pool\n% W_B(ii) = pi*(w1rms^2)*lorentzian (delta(ii), T2_B);% eqtn (2)\n% W_F: 1/R1_F .* Effective saturation rate of the free pool \n% W_F = (w1rms./(2*pi*delta)).^2/.055; --> eqtn(3)./R1_F\n% w1rms = 2400; % omega-1 RMS --> ???? where does this number\n% come from???\n% T2_B: T2 relaxation time of Bound pool, units= seconds\n% T2_B = 11e-6; \"average-brain\" [YY (2004), pg 411, column2, paragraph 1]\n% R1: observed relaxation rate (measured in the independent\n% experiment) [YY(2004), pg 411, column 1, parag 2]\n% nz = T1>0;\n% R1 = zeros(size(T1)); \n% R1(nz) = 1./T1(nz);\n% S0: Synthetic reference image computed by equation (6) using PD(protein Density) and\n% R1 maps.\n% t_m: duration of an off-resonance RF pulse \n% t_m = 8e-3; %bese 8e-3\n% t_s: delay time BEFORE an exitation RF pulse\n% t_s = 5e-3; %bese 5e-3\n% t_r: delay time AFTER an exitation RF pulse\n% t_r = 19e-3; %bese 19e-3\n% Output:\n% output: ??? m/S0 - M_z(:,1)./m_norm(1);\n%\n% Example:\n% output=relaxMtFitFunc(x, MT(:,ii), W_B, W_F, T2_B, R1(ii),S0(ii), t_m, t_s, t_r)\n%\n\n% C : diagonal matrix = diag(cos(alpha),1) corresponding to instant\n% rotation of the magnetization Mz_F by an excitation pulse with a flip\n% angle alpha\n% cos(10*pi/180) = 0.984807753012\nC = [ 0.984807753012 0;\n 0 1 ];\n\nk = x(1); % the k-parameter is passed through x\nf = x(2); % the f-parameter is passed through x\n\nif(f<=0.01 || f>=0.5 || k<=0.1 || k>=5)\n output = Inf;\n return;\nend\n\n%T2_B = 11e-6; %bese 11e-6\n\nR1_B = 1; %bese 1\n% Compute this term just one to save some cycles\nkf = k*(1-f)/f;\nR1_F = R1 - k*(R1_B - R1)/(R1_B - R1 + kf); % eqtn (4)\n%W_F = R1_F*(w1rms./(2*pi*delta)).^2/.055; %bese .055\nW_F = R1_F*W_F;\n\nR = [ (-R1_F - k) (kf) ; \n (k) (-R1_B - kf) ];\n\nA = R1_F*R1_B + R1_F*kf + R1_B*k;\nE_s = expm(R*t_s); % relaxation during delays before (t_s) an exitation RF pulse\nE_r = expm(R*t_r); % relaxation during delays after (t_r) an exitation RF pulse\n\nI = eye(2); %identity matrix\n\nfor ii = 1:length(W_B);\n W = [-W_F(ii), 0;\n 0, -W_B(ii)];\n E_m = expm((R + W)*t_m);% off-resonance saturation by an RF pulse w/ duration t_m \n D = A + (R1_F + k)*W_B(ii) + (R1_B + kf)*W_F(ii) + W_B(ii)*W_F(ii);\n M_eq = [1-f f]';\n M_ss = 1/D*[(1-f)*(A + R1_F*W_B(ii)) f*(A + R1_B*W_F(ii))]';\n term_1 = inv(I - E_s*E_m*E_r*C);\n %if (rcond(term_1)<1e-4), output = +Inf; return; end;\n term_2 = (E_s*E_m*(I-E_r) + I-E_s)*M_eq;\n term_3 = E_s*(I-E_m)*M_ss;\n M_z(ii,:) = term_1*(term_2 + term_3);\nend\n\n% Ova mozebi e nepotrebno, zasto m_norm treba da se zameni so S0 \nE_m = expm((R)*t_m); \nD = A;\nM_eq = [1-f f]';\nM_ss = 1/D*[(1-f)*(A) f*(A)]';\nterm_1 = inv(I - E_s*E_m*E_r*C);\nterm_2 = (E_s*E_m*(I - E_r) + I-E_s)*M_eq;\nterm_3 = E_s*(I-E_m)*M_ss; %na pocetok treba E_s?\nm_norm = term_1*(term_2 + term_3);\nresult = m/S0 - M_z(:,1)./m_norm(1);\noutput = sum(result.^2);\n%output = result;\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/mrQuant/relaxometry/relaxMtFitFuncLs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.6276992035339337}} {"text": "clear; close all\n % Impunerea primei solutii initiale\nsol_init = bvpinit(linspace(0,4,5),[1 0]);\n % Gasirea primei solutii \nsol = bvp4c(@fbound,@ffront,sol_init);\n % Evaluarea primei solutii\nx = linspace(0,4);\ny1 = bvpval(sol,x);\n % Impunerea solutiei initiale a doua\nsol_init = bvpinit(linspace(0,4,5),[-1 0]);\n % Gasirea solutiei a doua\nsol = bvp4c(@fbound,@ffront,sol_init);\n % Evaluarea solutiei a doua\ny2 = bvpval(sol,x);\n % Reprezentarea grafica a celor doua solutii\nplot(x,y1(1,:),x,y2(1,:),'Linewidth',1.5);\nxlabel('x');\nylabel('y');\ngrid\nlegend('Prima solutie','A doua solutie')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8416-widely-used-programming-environments-in-electrical-engineering-matlab/9/Ex_9_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.627643993759463}} {"text": "function [xPred, PPred, F, B] = ExtendedKalmanFilterX_PredictState(x,P,f,Q,u,b,Qu)\n% EKALMANFILTERX_PREDICTSTATE Perform the discrete-time KF state prediction \n% step, under the assumption of additive process noise.\n%\n% Parameters\n% ----------\n% x: column vector\n% The (xDim x 1) state estimate at the previous time-step.\n% P: matrix\n% The (xDim x xDim) state covariance matrix at the previous\n% time-step.\n% f: function handle\n% A (non-linear) state transition function.\n% Q: matrix\n% The (xDim x xDim) process noise covariance matrix.\n% u: column vector, optional\n% An optional (xDim x 1) control input.\n% If omitted, no control input is used.\n% b: function handle, optional\n% A (non-linear) control gain function.\n% (Optional, Default = 1 if u provided, 0 otherwise)\n% O: matrix, optional\n% An optional (xDim x xDim) control noise covariance\n% matrix. If omitted, Q is assumed to be 0.\n%\n% Returns\n% -------\n% xPred: column vector\n% The (xDim x 1) predicted state estimate.\n% PPred: matrix\n% The (xDim x xDim) predicted state covariance matrix.\n% F: matrix\n% The computed Jacobian transition matrix\n% H: matrix\n% The computed (yDim x yDim) Jacobian measurement matrix\n% B: matrix, optional\n% The computed Jacobian control gain matrix\n%\n% October 2017 Lyudmil Vladimirov, University of Liverpool.\n \n switch(nargin)\n case(4) \n u = 0;\n b = 0;\n Qu = 0;\n case(5)\n b = 1;\n Qu = 0;\n case(6)\n Qu = 0;\n end\n \n % Prediction for state vector and covariance:\n [xPred,F] = ExtendedKalmanFilterX_computeJac(f,x); %nonlinear update and linearization at current state\n PPred = F*P*F' + Q; %partial update\n\n % Compute Control Input (if applicable)\n [controlInputWithGain,B] = ExtendedKalmanFilterX_computeJac(b,u); \n \n % Add control input\n xPred = xPred + controlInputWithGain;\n PPred = PPred + B*Qu*B'; \nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/Kalman/ExtendedKalmanFilterX/Functions/Prediction/ExtendedKalmanFilterX_PredictState.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6276439832117578}} {"text": "function y= DAB(T,P,MA,MB,sigmA,sigmB,epsA,epsB)\n%DAB Calculates gas-phase diffusivity using Wilke-Lee equation, p. 17 Text.\n% DAB(T,P,MA,MB,sigmA,sigmB,epsA,epsB)\n% T = absolute temperature in K\n% P = pressure in bar\n% MA, MB = molecular weights\n% sigmA, sigmB, epsA, epsB = Lennard-Jones parameters\n% in Angstroms and Kelvin, respectively\n% DAB = diffusivity in square cm/sec.\nsigmAB=(sigmA+sigmB)/2;\nepsAB=sqrt(epsA*epsB);\nx=T/epsAB;\na=1.06036;b=0.15610;c=0.19300;d=0.47635;\ne1=1.03587;f=1.52996;g=1.76474;h=3.89411;\nMAB=2*(1/MA+1/MB)^-1;\nomega=a/x^b+c/exp(d*x)+e1/exp(f*x)+g/exp(h*x);\ny=0.001*(3.03-0.98/sqrt(MAB))*T^1.5/(P*sigmAB^2*omega*sqrt(MAB));", "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/2970-principles-and-modern-applications-of-mass-transfer-operations/MatlabExamples/Dab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.6276051589396461}} {"text": "function sigma = massey_berlekamp_M2(n,k,t,S,field)\n\n%http://www.ee.ucla.edu/~matache/rsc/node8.html#SECTION00051000000000000000\n\n%Step 2: Initialize variables\nkk = 0;\n\n\n\nfor i = 1:n\n Kappa(1,i) = -Inf;\nend\nKappa(1,1) = 0;\n\n%Kappa\n\n\n\nLAMBDA = 0;\nTau = [-inf 0];\n\ndone = 0;\n\n%Step 3:\nwhile (done ~= 1)\n %disp('K');\n \n kk = kk + 1;\n \n %disp('S(kk)');\n %S(kk)\n \n %disp('LAMBDA')\n %LAMBDA\n \n sum = -Inf;\n for i = 1:LAMBDA\n %Kappa(kk,i+1)\n %S(kk-i)\n sum = gfadd(sum,gfmul(Kappa(kk,i+1),S(kk-i),field),field);\n end\n \n %disp('Delta - sum')\n %sum\n \n delta(kk) = gfadd(S(kk),sum,field);\n \n %disp('delta');\n %delta\n \n %Step 4:\n if (delta(kk) == -Inf)\n for i = 1:n\n Kappa(kk+1,i) = Kappa(kk,i);\n end\n end\n \n \n if (delta(kk) ~= -Inf)\n \n for i = 1:n\n Kappa_i(i) = Kappa(kk-1+1,i);\n end\n \n Kappa_k = gfadd(Kappa_i,gfconv(delta(kk),Tau,field),field);\n \n while length(Kappa_k) < n\n Kappa_k = [Kappa_k -Inf];\n end\n \n for i = 1:length(Kappa_k)\n Kappa(kk+1,i) = Kappa_k(i);\n end\n \n \n %Step 7:\n if (2*LAMBDA < kk)\n LAMBDA = kk - LAMBDA;\n \n for i = 1:n\n Kappa_k(i) = Kappa(kk+1-1,i);\n end\n \n Tau = gfconv(Kappa_k,gfdiv(0,delta(kk),field),field);\n end\n end\n \n %Step 8:\n Tau = gfconv([-Inf 0],Tau,field);\n \n %step 9:\n if kk >= 2*t\n done = 1;\n end\n \n %Kappa\n %LAMBDA\n %Tau\n \n \nend \n\n\nfor i = 1:n\n sigma(i) = Kappa(kk+1,i);\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/27116-mfsk-modulation-in-awgn-noise-with-reed-solomon-decoding/MFSK/Errors_and_Erasures/massey_berlekamp_M3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.627576701170653}} {"text": "function F=dwt_sr_fuse(I1,I2,zt,D,overlap,epsilon)\n% DWT-SR\n% Input:\n% I1 - input image A\n% I2 - input image B\n% zt - maximum decomposition level\n% D - Dictionary for sparse representation\n% overlap - the overlapped pixels between two neighbor patches\n% epsilon - sparse reconstuction error\n% Output:\n% F - fused image \n%\n% The code is edited by Yu Liu, 01-09-2014.\n\n%-------------------------------------------------------------------------%\n% DWT\n%-------------------------------------------------------------------------%\nI1=double(I1);\nI2=double(I2);\ntempA=I1;\ntempB=I2;\n \nX=cell(zt,4); \nY=cell(zt,4); \nZ=cell(zt,4); \nfor i=1:zt\n [X{i,1},X{i,2},X{i,3},X{i,4}]=dwt2(tempA,'db1','mode','per'); \n tempA=X{i,1};\n [Y{i,1},Y{i,2},Y{i,3},Y{i,4}]=dwt2(tempB,'db1','mode','per'); \n tempB=Y{i,1};\nend\n\n%-------------------------------------------------------------------------%\n% low-pass fusion\n%-------------------------------------------------------------------------%\nZ{zt,1}=sparse_fusion(X{zt,1},Y{zt,1},D,overlap,epsilon);\n\n\n%-------------------------------------------------------------------------%\n% high-pass fusion\n%-------------------------------------------------------------------------% \nfor i=zt:-1:1 \n for j=2:4\n Z{i,j}=selc(X{i,j},Y{i,j},3); \n end\nend\n\n%-------------------------------------------------------------------------%\n% IDWT\n%-------------------------------------------------------------------------%\nfor i=zt:-1:1\n if i>1\n Z{i-1,1}=idwt2(Z{i,1},Z{i,2},Z{i,3},Z{i,4},'db1','mode','per');\n else\n F=idwt2(Z{i,1},Z{i,2},Z{i,3},Z{i,4},'db1','mode','per');\n end\nend\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dwt_sr_fuse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6275265863639287}} {"text": "function [C, D] = WatsonSHCoeff(k)\n% function [C, D] = WatsonSHCoeff(k)\n% Computes the spherical harmonic (SH) coefficients of the Watson's\n% distribution with the concentration parameter k (kappa) up to the 12th order\n% and the derivatives if requested.\n%\n% Truncating at the 12th order gives good approximation for kappa up to 64.\n%\n% INPUTS:\n%\n% k should be an array of positive numbers, specifying a set of\n% concentration parameters for the Watson's distribution.\n%\n% OUTPUTS:\n%\n% C will be a 2-D array and each row contains the SH coefficients of the\n% orders 0, 2, 4, ..., to 2n for the parameter in the corresponding row in\n% k.\n%\n% Note that the SH coefficients of the odd orders are always zero.\n%\n% D will be the 1st order derivative of C.\n%\n% author: Gary Hui Zhang (gary.zhang@ucl.ac.uk)\n%\n\nlarge = find(k>30);\nexact = find(k>0.1);\napprox = find(k<=0.1);\n% Necessary to make matlab happy when k is a single value\nexact = exact(:);\napprox = approx(:);\nlarge = large(:);\n\n% The maximum order of SH coefficients (2n)\nn = 6;\n\n% Computing the SH coefficients\nC = zeros(length(k),n+1);\n\n% 0th order is a constant\nC(:,1) = 2*sqrt(pi);\n\n% Precompute the special function values\nsk = sqrt(k(exact));\nsk2 = sk.*k(exact);\nsk3 = sk2.*k(exact);\nsk4 = sk3.*k(exact);\nsk5 = sk4.*k(exact);\nsk6 = sk5.*k(exact);\nsk7 = sk6.*k(exact);\nk2 = k.^2;\nk3 = k2.*k;\nk4 = k3.*k;\nk5 = k4.*k;\nk6 = k5.*k;\nk7 = k6.*k;\n\nerfik = NODDI_erfi(sk);\nierfik = 1./erfik;\nek = exp(k(exact));\ndawsonk = 0.5*sqrt(pi)*erfik./ek;\n\n% for large enough kappa\nC(exact,2) = 3*sk - (3 + 2*k(exact)).*dawsonk;\nC(exact,2) = sqrt(5)*C(exact,2).*ek;\nC(exact,2) = C(exact,2).*ierfik./k(exact);\n\nC(exact,3) = (105 + 60*k(exact) + 12*k2(exact)).*dawsonk;\nC(exact,3) = C(exact,3) -105*sk + 10*sk2;\nC(exact,3) = .375*C(exact,3).*ek./k2(exact);\nC(exact,3) = C(exact,3).*ierfik;\n\nC(exact,4) = -3465 - 1890*k(exact) - 420*k2(exact) - 40*k3(exact);\nC(exact,4) = C(exact,4).*dawsonk;\nC(exact,4) = C(exact,4) + 3465*sk - 420*sk2 + 84*sk3;\nC(exact,4) = C(exact,4)*sqrt(13*pi)/64./k3(exact);\nC(exact,4) = C(exact,4)./dawsonk;\n\nC(exact,5) = 675675 + 360360*k(exact) + 83160*k2(exact) + 10080*k3(exact) + 560*k4(exact);\nC(exact,5) = C(exact,5).*dawsonk;\nC(exact,5) = C(exact,5) - 675675*sk + 90090*sk2 - 23100*sk3 + 744*sk4;\nC(exact,5) = sqrt(17)*C(exact,5).*ek;\nC(exact,5) = C(exact,5)/512./k4(exact);\nC(exact,5) = C(exact,5).*ierfik;\n\nC(exact,6) = -43648605 - 22972950*k(exact) - 5405400*k2(exact) - 720720*k3(exact) - 55440*k4(exact) - 2016*k5(exact);\nC(exact,6) = C(exact,6).*dawsonk;\nC(exact,6) = C(exact,6) + 43648605*sk - 6126120*sk2 + 1729728*sk3 - 82368*sk4 + 5104*sk5;\nC(exact,6) = sqrt(21*pi)*C(exact,6)/4096./k5(exact);\nC(exact,6) = C(exact,6)./dawsonk;\n\nC(exact,7) = 7027425405 + 3666482820*k(exact) + 872972100*k2(exact) + 122522400*k3(exact) + 10810800*k4(exact) + 576576*k5(exact) + 14784*k6(exact);\nC(exact,7) = C(exact,7).*dawsonk;\nC(exact,7) = C(exact,7) - 7027425405*sk + 1018467450*sk2 - 302630328*sk3 + 17153136*sk4 - 1553552*sk5 + 25376*sk6;\nC(exact,7) = 5*C(exact,7).*ek;\nC(exact,7) = C(exact,7)/16384./k6(exact);\nC(exact,7) = C(exact,7).*ierfik;\n\n% for very large kappa\nif size(large,1) > 0\n lnkd = log(k(large)) - log(30);\n lnkd2 = lnkd.*lnkd;\n lnkd3 = lnkd2.*lnkd;\n lnkd4 = lnkd3.*lnkd;\n lnkd5 = lnkd4.*lnkd;\n lnkd6 = lnkd5.*lnkd;\n C(large,2) = 7.52308 + 0.411538*lnkd - 0.214588*lnkd2 + 0.0784091*lnkd3 - 0.023981*lnkd4 + 0.00731537*lnkd5 - 0.0026467*lnkd6;\n C(large,3) = 8.93718 + 1.62147*lnkd - 0.733421*lnkd2 + 0.191568*lnkd3 - 0.0202906*lnkd4 - 0.00779095*lnkd5 + 0.00574847*lnkd6;\n C(large,4) = 8.87905 + 3.35689*lnkd - 1.15935*lnkd2 + 0.0673053*lnkd3 + 0.121857*lnkd4 - 0.066642*lnkd5 + 0.0180215*lnkd6;\n C(large,5) = 7.84352 + 5.03178*lnkd - 1.0193*lnkd2 - 0.426362*lnkd3 + 0.328816*lnkd4 - 0.0688176*lnkd5 - 0.0229398*lnkd6;\n C(large,6) = 6.30113 + 6.09914*lnkd - 0.16088*lnkd2 - 1.05578*lnkd3 + 0.338069*lnkd4 + 0.0937157*lnkd5 - 0.106935*lnkd6;\n C(large,7) = 4.65678 + 6.30069*lnkd + 1.13754*lnkd2 - 1.38393*lnkd3 - 0.0134758*lnkd4 + 0.331686*lnkd5 - 0.105954*lnkd6;\nend\n\n% for small kappa\nC(approx,2) = 4/3*k(approx) + 8/63*k2(approx);\nC(approx,2) = C(approx,2)*sqrt(pi/5);\n\nC(approx,3) = 8/21*k2(approx) + 32/693*k3(approx);\nC(approx,3) = C(approx,3)*(sqrt(pi)*0.2);\n\nC(approx,4) = 16/693*k3(approx) + 32/10395*k4(approx);\nC(approx,4) = C(approx,4)*sqrt(pi/13);\n\nC(approx,5) = 32/19305*k4(approx);\nC(approx,5) = C(approx,5)*sqrt(pi/17);\n\nC(approx,6) = 64*sqrt(pi/21)*k5(approx)/692835;\n\nC(approx,7) = 128*sqrt(pi)*k6(approx)/152108775;\n\nif nargout == 1\n\treturn;\nend\n\n% Computing the derivatives\ndawsonk2 = dawsonk.^2;\nidawsonk2 = 1./dawsonk2;\n\nD = zeros(length(k),n+1);\nD(:,1) = 0.0;\n\n% exact\nD(exact,2) = -k(exact) + (2*sk2 -sk).*dawsonk + 2*dawsonk2;\nD(exact,2) = (.75*sqrt(5*pi))*D(exact,2)./k2(exact).*idawsonk2;\n\nD(exact,3) = 21*k(exact) - 2*k2(exact);\nD(exact,3) = D(exact,3) + (63*sk -44*sk2 + 4*sk3).*dawsonk;\nD(exact,3) = D(exact,3) - (84 + 24*k(exact)).*dawsonk2;\nD(exact,3) = D(exact,3)*(15*sqrt(pi)/32)./k3(exact).*idawsonk2;\n\nD(exact,4) = -165*k(exact) + 20*k2(exact) - 4*k3(exact);\nD(exact,4) = D(exact,4) + (-825*sk + 390*sk2 - 44*sk3 + 8*sk4).*dawsonk;\nD(exact,4) = D(exact,4) + (990 + 360*k(exact) + 40*k2(exact)).*dawsonk2;\nD(exact,4) = D(exact,4)*(21*sqrt(13*pi)/128)./k4(exact).*idawsonk2;\n\nD(exact,5) = 225225*k(exact) - 30030*k2(exact) + 7700*k3(exact) - 248*k4(exact);\nD(exact,5) = D(exact,5) + (1576575*sk - 600600*sk2 + 83160*sk3 - 15648*sk4 + 496*sk5).*dawsonk;\nD(exact,5) = D(exact,5) - (1801800 + 720720*k(exact) + 110880*k2(exact) + 6720*k3(exact)).*dawsonk2;\nD(exact,5) = D(exact,5)*(3*sqrt(17*pi)/2048)./k5(exact).*idawsonk2;\n\nD(exact,6) = -3968055*k(exact) + 556920*k2(exact) - 157248*k3(exact) + 7488*k4(exact) - 464*k5(exact);\nD(exact,6) = D(exact,6) + (-35712495*sk + 11834550*sk2 - 1900090*sk3 + 336960*sk4 - 15440*sk5 + 928*sk6).*dawsonk;\nD(exact,6) = D(exact,6) + (39680550 + 16707600*k(exact) + 2948400*k2(exact) + 262080*k3(exact) + 10080*k4(exact)).*dawsonk2;\nD(exact,6) = D(exact,6)*(11*sqrt(21*pi)/8192)./k6(exact).*idawsonk2;\n\nD(exact,7) = 540571185*k(exact) - 78343650*k2(exact) + 23279256*k3(exact) - 1319472*k4(exact) + 119504*k5(exact) - 1952*k6(exact);\nD(exact,7) = D(exact,7) + (5946283035*sk - 1786235220*sk2 + 319642092*sk3 - 53155872*sk4 + 2997456*sk5 - 240960*sk6 + 3904*sk7).*dawsonk;\nD(exact,7) = D(exact,7) - (6486854220 + 2820371400*k(exact) + 537213600*k2(exact) + 56548800*k3(exact) + 3326400*k4(exact) + 88704*k5(exact)).*dawsonk2;\nD(exact,7) = D(exact,7)*(65*sqrt(pi)/65536)./k7(exact).*idawsonk2;\n\n% approximation\nD(approx,2) = 4/3 + 16/63*k(approx) - 16/315*k2(approx) - 128/6237*k3(approx);\nD(approx,2) = D(approx,2)*sqrt(pi/5);\n\nD(approx,3) = 16/105*k(approx) + 32/1155*k2(approx) - 3712/675675*k3(approx) - 5888/2837835*k4(approx);\nD(approx,3) = D(approx,3)*sqrt(pi);\n\nD(approx,4) = 16/231*k2(approx) + 128/10395*k3(approx) - 256/106029*k4(approx);\nD(approx,4) = D(approx,4)*sqrt(pi/13);\n\nD(approx,5) = 128/19305*k3(approx) + 256/220077*k4(approx);\nD(approx,5) = D(approx,5)*sqrt(pi/17);\n\nD(approx,6) = 64/138567*k4(approx);\nD(approx,6) = D(approx,6)*sqrt(pi/21);\n\nD(approx,7) = 256/50702925*k5(approx);\nD(approx,7) = D(approx,7)*sqrt(pi);\n\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/NODDI_toolbox_v1.0/models/watson/WatsonSHCoeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.627526580142128}} {"text": "function [res,resL2,qualMeasOut]=SART_TV(proj,geo,angles,niter,varargin)\n% SART_TV solves Cone Beam CT image reconstruction using Oriented Subsets\n% Simultaneous Algebraic Reconstruction Technique algorithm\n%\n% SART_TV(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem\n% using the projection data PROJ taken over ALPHA angles, corresponding\n% to the geometry described in GEO, using NITER iterations.\n%\n% SART_TV(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The\n% possible options in OPT are:\n%\n%\n% 'lambda': Sets the value of the hyperparameter. Default is 1\n%\n% 'lambda_red': Reduction of lambda. Every iteration\n% lambda=lambdared*lambda. Default is 0.99\n%\n% 'Init': Describes different initialization techniques.\n% 'none' : Initializes the image to zeros (default)\n% 'FDK' : Initializes image to FDK reconstruction\n% 'multigrid': Initializes image by solving the problem in\n% small scale and increasing it when relative\n% convergence is reached.\n% 'image' : Initialization using a user specified\n% image. Not recommended unless you really\n% know what you are doing.\n% 'InitImg' an image for the 'image' initialization. Avoid.\n%\n% 'TViter' number of iterations in the TV step. Default 50\n%\n% 'TVlambda' hyperparameter in TV iteration. It gives the ratio of\n% importance of the image vs the minimum total variation.\n% default is 15. Lower means more TV denoising.\n%\n% 'Verbose' 1 or 0. Default is 1. Gives information about the\n% progress of the algorithm.\n%\n% 'QualMeas' Asks the algorithm for a set of quality measurement\n% parameters. Input should contain a cell array of desired\n% quality measurement names. Example: {'CC','RMSE','MSSIM'}\n% These will be computed in each iteration.\n% 'OrderStrategy' Chooses the subset ordering strategy. Options are\n% 'ordered' : uses them in the input order, but divided\n% 'random' : orders them randomly\n% 'angularDistance': chooses the next subset with the\n% biggest angular distance with the ones used.\n% 'redundancy_weighting': true or false. Default is true. Applies data\n% redundancy weighting to projections in the update step\n% (relevant for offset detector geometry)\n% 'groundTruth' an image as grounf truth, to be used if quality measures\n% are requested, to plot their change w.r.t. this known\n% data.\n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n%\n% Copyright (c) 2015, University of Bath and\n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD.\n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri\n%--------------------------------------------------------------------------\n\n%% Deal with input parameters\n[lambda,res,lamdbared,verbose,QualMeasOpts,TViter,TVlambda,OrderStrategy,nonneg,gpuids,redundancy_weights,gt]=parse_inputs(proj,geo,angles,varargin);\nmeasurequality=~isempty(QualMeasOpts) | ~any(isnan(gt(:)));\nif ~any(isnan(gt(:)))\n QualMeasOpts{end+1}='error_norm';\n res_prev=gt;\n clear gt\nend\nif nargout<3 && measurequality\n warning(\"Image metrics requested but none catched as output. Call the algorithm with 3 outputs to store them\")\n measurequality=false;\nend\nqualMeasOut=zeros(length(QualMeasOpts),niter);\n\nresL2=zeros(1,niter);\nif nargout>1\n computeL2=true;\nelse\n computeL2=false;\nend\n\nblocksize=1;\n[alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy);\n\nangles_reorder=cell2mat(alphablocks);\nindex_angles=cell2mat(orig_index);\n% does detector rotation exist?\nif ~isfield(geo,'rotDetector')\n geo.rotDetector=[0;0;0];\nend\n%% Create weighting matrices\n\n% Projection weight, W\nW=computeW(geo,angles,gpuids);\n\n% Back-Projection weight, V\nV=computeV(geo,angles,alphablocks,orig_index,'gpuids',gpuids);\n\nif redundancy_weights\n % Data redundancy weighting, W_r implemented using Wang weighting\n % reference: https://iopscience.iop.org/article/10.1088/1361-6560/ac16bc\n \n num_frames = size(proj,3);\n W_r = redundancy_weighting(geo);\n W_r = repmat(W_r,[1,1,num_frames]);\n % disp('Size of redundancy weighting matrix');\n % disp(size(W_r));\n W = W.*W_r; % include redundancy weighting in W\nend\n\n%% Iterate\noffOrigin=geo.offOrigin;\noffDetector=geo.offDetector;\nrotDetector=geo.rotDetector;\nDSD=geo.DSD;\nDSO=geo.DSO;\n% TODO : Add options for Stopping criteria\nfor ii=1:niter\n if (ii==1 && verbose==1);tic;end\n % If quality is going to be measured, then we need to save previous image\n % THIS TAKES MEMORY!\n if measurequality && ~strcmp(QualMeasOpts,'error_norm')\n res_prev = res; % only store if necesary\n end\n \n \n for jj=1:size(angles,2)\n if size(offOrigin,2)==size(angles,2)\n geo.offOrigin=offOrigin(:,index_angles(:,jj));\n end\n if size(offDetector,2)==size(angles,2)\n geo.offDetector=offDetector(:,index_angles(:,jj));\n end\n if size(rotDetector,2)==size(angles,2)\n geo.rotDetector=rotDetector(:,index_angles(:,jj));\n end\n if size(DSD,2)==size(angles,2)\n geo.DSD=DSD(jj);\n end\n if size(DSO,2)==size(angles,2)\n geo.DSO=DSO(jj);\n end\n % proj_err=proj(:,:,jj)-Ax(res,geo,angles(:,jj)); % (b-Ax)\n % weighted_err=W(:,:,jj).*proj_err; % W^-1 * (b-Ax)\n % backprj=Atb(weighted_err,geo,angles(:,jj)); % At * W^-1 * (b-Ax)\n % weigth_backprj=bsxfun(@times,1./V(:,:,jj),backprj); % V * At * W^-1 * (b-Ax)\n % res=res+lambda*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax)\n res=res+lambda* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,index_angles(:,jj))-Ax(res,geo,angles_reorder(:,jj),'gpuids',gpuids)),geo,angles_reorder(:,jj),'gpuids',gpuids));\n if nonneg\n res=max(res,0);\n end\n end\n \n % If quality is being measured\n if measurequality\n qualMeasOut(:,ii)=Measure_Quality(res,res_prev,QualMeasOpts);\n end\n \n lambda=lambda*lamdbared;\n % TV denoising\n res=im3DDenoise(res,'TV',TViter,TVlambda,'gpuids',gpuids);\n \n \n if computeL2\n geo.offOrigin=offOrigin;\n geo.offDetector=offDetector;\n geo.DSD=DSD;\n geo.rotDetector=rotDetector;\n resL2(ii)=im3Dnorm(proj(:,:,index_angles)-Ax(res,geo,angles,'gpuids',gpuids),'L2'); % Compute error norm2 of b-Ax\n % If the error is not minimized.\n if ii~=1 && resL2(ii)>resL2(ii-1)\n if verbose\n disp(['Convergence criteria met, exiting on iteration number:', num2str(ii)]);\n end\n return\n end\n end\n \n if (ii==1 && verbose==1)\n expected_time=toc*niter;\n disp('SART_TV');\n disp(['Expected duration : ',secs2hms(expected_time)]);\n disp(['Expected finish time: ',datestr(datetime('now')+seconds(expected_time))]);\n disp('');\n end\nend\n\n\n\n\n\nend\n\nfunction initres=init_multigrid(proj,geo,alpha,TViter,TVlambda,gpuids)\n\nfinalsize=geo.nVoxel;\n% start with 64\ngeo.nVoxel=[64;64;64];\ngeo.dVoxel=geo.sVoxel./geo.nVoxel;\nif any(finalsizefinalsize)=finalsize(geo.nVoxel>finalsize);\n geo.dVoxel=geo.sVoxel./geo.nVoxel;\n % Upsample!\n % (hopefully computer has enough memory............)\n [y, x, z]=ndgrid(linspace(1,size(initres,1),geo.nVoxel(1)),...\n linspace(1,size(initres,2),geo.nVoxel(2)),...\n linspace(1,size(initres,3),geo.nVoxel(3)));\n initres=interp3(initres,x,y,z);\n clear x y z\nend\nend\n\n\nfunction [lambda,res,lamdbared,verbose,QualMeasOpts,TViter,TVlambda,OrderStrategy,nonneg,gpuids,redundancy_weights,gt]=parse_inputs(proj,geo,alpha,argin)\nopts={'lambda','init','initimg','verbose','lambda_red','qualmeas','tviter','tvlambda','orderstrategy','nonneg','gpuids','redundancy_weighting','groundtruth'};\ndefaults=ones(length(opts),1);\n% Check inputs\nnVarargs = length(argin);\nif mod(nVarargs,2)\n error('TIGRE:SART_TV:InvalidInput','Invalid number of inputs')\nend\nmultigrid=false;\n% check if option has been passed as input\nfor ii=1:2:nVarargs\n ind=find(ismember(opts,lower(argin{ii})));\n if ~isempty(ind)\n defaults(ind)=0;\n else\n error('TIGRE:SART_TV:InvalidInput',['Optional parameter \"' argin{ii} '\" does not exist' ]);\n end\nend\n\nfor ii=1:length(opts)\n opt=opts{ii};\n default=defaults(ii);\n % if one option is not default, then extract value from input\n if default==0\n ind=double.empty(0,1);jj=1;\n while isempty(ind)\n ind=find(isequal(opt,lower(argin{jj})));\n jj=jj+1;\n end\n if isempty(ind)\n error('TIGRE:SART_TV:InvalidInput',['Optional parameter \"' argin{jj} '\" does not exist' ]);\n end\n val=argin{jj};\n end\n \n switch opt\n % % % % % % % Verbose\n case 'verbose'\n if default\n verbose=1;\n else\n verbose=val;\n end\n if ~is2014bOrNewer\n warning('TIGRE: Verbose mode not available for older versions than MATLAB R2014b');\n verbose=false;\n end\n % % % % % % % hyperparameter, LAMBDA\n case 'lambda'\n if default\n lambda=1;\n else\n if length(val)>1 || ~isnumeric(val)\n error('TIGRE:SART_TV:InvalidInput','Invalid lambda')\n end\n lambda=val;\n end\n case 'lambda_red'\n if default\n lamdbared=0.99;\n else\n if length(val)>1 || ~isnumeric(val)\n error('TIGRE:SART_TV:InvalidInput','Invalid lambda')\n end\n lamdbared=val;\n end\n case 'init'\n res=[];\n if default || strcmp(val,'none')\n res=zeros(geo.nVoxel','single');\n continue\n end\n if strcmp(val,'FDK')\n res=FDK(proj,geo,alpha);\n continue\n end\n if strcmp(val,'multigrid')\n multigrid=true;\n continue\n end\n if strcmp(val,'image')\n initwithimage=1;\n continue\n end\n if isempty(res)\n error('TIGRE:SART_TV:InvalidInput','Invalid Init option')\n end\n % % % % % % % ERROR\n case 'initimg'\n if default\n continue\n end\n if exist('initwithimage','var')\n if isequal(size(val),geo.nVoxel')\n res=single(val);\n else\n error('TIGRE:SART_TV:InvalidInput','Invalid image for initialization');\n end\n end\n case 'qualmeas'\n if default\n QualMeasOpts={};\n else\n if iscellstr(val)\n QualMeasOpts=val;\n else\n error('CBCT:SART_TV:InvalidInput','Invalid quality measurement parameters');\n end\n end\n case 'tviter'\n if default\n TViter=50;\n else\n TViter=val;\n end\n case 'tvlambda'\n if default\n TVlambda=50;\n else\n TVlambda=val;\n end\n case 'orderstrategy'\n if default\n OrderStrategy='random';\n else\n OrderStrategy=val;\n end\n \n case 'nonneg'\n if default\n nonneg=true;\n else\n nonneg=val;\n end\n case 'gpuids'\n if default\n gpuids = GpuIds();\n else\n gpuids = val;\n end\n case 'redundancy_weighting'\n if default\n redundancy_weights = true;\n else\n redundancy_weights = val;\n end\n case 'groundtruth'\n if default\n gt=nan;\n else\n gt=val;\n end\n otherwise\n error('TIGRE:SART_TV:InvalidInput',['Invalid input name:', num2str(opt),'\\n No such option in SART()']);\n end\nend\nif multigrid\n res=init_multigrid(proj,geo,alpha,TViter,TVlambda,gpuids);\nend\n\nend", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Algorithms/SART_TV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6274504053634995}} {"text": "function [dat, state] = ft_preproc_standardize(dat, begsample, endsample, state)\n\n% FT_PREPROC_STANDARDIZE performs a z-transformation or standardization\n% of the data. The standardized data will have a zero-mean and a unit\n% standard deviation.\n%\n% Use as\n% [dat] = ft_preproc_standardize(dat, begsample, endsample)\n% where\n% dat data matrix (Nchans dat Ntime)\n% begsample index of the begin sample for the mean and stdev estimate\n% endsample index of the end sample for the mean and stdev estimate\n%\n% If no begin and end sample are specified, it will be estimated on the\n% complete data.\n%\n% See also PREPROC\n\n% Copyright (C) 2008, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif nargin<2 || isempty(begsample)\n begsample = 1;\nend\n\nif nargin<3 || isempty(endsample)\n endsample = size(dat,2);\nend\n\nif nargin<4\n state = [];\nend\n\n% preprocessing fails on channels that contain NaN\nif any(isnan(dat(:)))\n ft_warning('FieldTrip:dataContainsNaN', 'data contains NaN values');\nend\n\n% get the data selection\ny = dat(:,begsample:endsample);\n\n% determine the size of the selected data: nChans dat nSamples\n[m, n] = size(y);\n\n% compute the sum and sum of squares\ns = sum(y,2);\nss = sum(y.^2,2);\n\n% include the state information from the previous calls\nif ~isempty(state)\n s = s + state.s;\n ss = ss + state.ss;\n n = n + state.n;\nend\n\n% compute the mean and standard deviation\nmy = s ./ n;\nsy = sqrt((ss - (s.^2)./n) ./ (n-1));\n\n% standardize the complete input data\ndat = (dat - repmat(my, 1, size(dat, 2))) ./ repmat(sy, 1, size(dat, 2));\n\n% remember the state\nstate.s = s; % sum\nstate.ss = ss; % sum of sqares\nstate.n = n; % number of samples\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/preproc/ft_preproc_standardize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6274423384761786}} {"text": "function [y, iter, lambda, status] = minimize_cubic_newton(H, g, sigma, options)\n% Minimize a cubicly regularized quadratic via Newton root finding.\n%\n% [y, iter, lambda, status] = minimize_cubic_newton(H, g, sigma, options)\n%\n% Inputs: a symmetric matrix H of size n, a nonzero vector g of length n,\n% a positive real sigma and an options structure. The code expects H to\n% be tridiagonal, stored as a sparse matrix.\n%\n% The main output is a vector y of length n, which should minimize\n%\n% f(y) = g'*y + (1/2)*y'*H*y + (1/3)*sigma*norm(y)^3.\n%\n% This is achieved by reducing the problem to a univariate root finding\n% problem, where the unknown is a scalar lambda. This root is computed\n% using a Newton method.\n%\n% Other outputs are iter (the number of Newton iterations completed),\n% lambda (a real scalar, see below) and status. The latter is 0 if the\n% target tolerance was reached, 1 if subsequent iterations induce no\n% significant change, and -1 if the algorithm return because it reached\n% the maximum number of iterations (see the options structure.)\n% Non-negative status values are considered successes.\n%\n% The options structure must contain the following fields (between\n% parentheses are some recommended values):\n% options.verbosity (3): to control how much information this function\n% prints to the command window. Anything below 6 silences the function.\n% options.maxiter_newton (100): maximum number of Newton iterations.\n% options.tol_newton (1e-16): tolerance on the root finding accuracy. See\n% in code for details.\n%\n% The code is based on Section 6 in\n% Cartis, Gould and Toint, \"Adaptive cubic regularisation methods for\n% unconstrained optimization. Part I: motivation, convergence and numerical\n% results\", Mathematical Programming, 2011.\n% https://link.springer.com/article/10.1007/s10107-009-0286-5\n% \n% Theorem 3.1 in the referenced paper states y is optimal if and only\n% if it there exists a real lambda such that\n% \n% (H + lambda*I)y = -g, lambda = sigma*||y|| and H + lambda*I is psd,\n% \n% where psd means positive semidefinite. The other way around, if we\n% find the corresponding scalar lambda, than we can recover y by\n% solving a linear system (though this system might not have a unique\n% solution in full generality.) Thus, the general strategy is to search\n% for lambda rather than for y.\n%\n% See also: arc arc_lanczos\n\n% This file is part of Manopt: www.manopt.org.\n% Original authors: May 1, 2018,\n% Naman Agarwal, Brian Bullins, Nicolas Boumal and Coralia Cartis.\n% Contributors:\n% Change log:\n\n n = size(H, 1);\n \n % Pick an initial lambda that is cheap to compute and that surely makes\n % the shifted H positive definite.\n lambda = norm(H, 1) + 2;\n H_shifted = H + lambda*speye(n);\n \n % Compute the smallest eigenvalue of H, as we know the target lambda\n % must be at least as large as the negative of that, so that the\n % shifted H will be positive semidefinite.\n % \n % Since H ought to be sparse and tridiagonal, and since we only need\n % its smallest eigenvalue, this computation could be sped up\n % significantly. It does not appear to be a bottleneck, and eig is\n % simple and reliable, so we keep this for now.\n lambda_min = min(eig(H));\n left_barrier = max(0, -lambda_min);\n \n % Counter 'iter' holds the number of fully executed Newton iterations.\n iter = 0;\n while true\n \n if iter >= options.maxiter_newton\n % Iterations exceeded maximum number allowed.\n status = -1;\n return;\n end\n \n % If lambda has the correct value and the shifted H is positive\n % definite, then this y is a minimizer.\n y = -(H_shifted\\g);\n ynorm = norm(y);\n\n % If the following quantity is zero, we have found a solution.\n phi = 1/ynorm - sigma/lambda;\n \n % Check if it is close enough to zero to stop.\n if abs(phi) <= options.tol_newton*ynorm\n status = 0;\n return;\n end\n psi = ynorm^2;\n\n % TODO: clarify this part of the code (see referenced paper).\n % The following is a Newton type of step on the equation\n % sigma/lambda = 1/sqrt(psi(lambda_prev)) ...\n % - (lambda - lambda_prev)((psi'(lambda_prev))/2(psi)^1.5)\n delta_y = -(H_shifted\\y);\n psi_prime = 2*(y'*delta_y);\n p0 = 2*sigma*(psi^(1.5));\n p1 = -2*psi - lambda*psi_prime;\n p2 = psi_prime;\n r = roots([p2 p1 p0]);\n del_lambda = max(r) - lambda;\n iter = iter + 1;\n\n % If the Newton step would bring us left of the left barrier, jump\n % instead to the midpoint between the left barrier and the current\n % lambda.\n if lambda + del_lambda <= left_barrier\n del_lambda = -.5*(lambda - left_barrier);\n end\n\n % If the step is so small that it numerically does not make a\n % difference when added to the current lambda, we stop.\n if abs(del_lambda) <= eps(lambda)\n status = 1;\n return;\n end\n\n % Update lambda\n H_shifted = H_shifted + del_lambda*speye(n);\n lambda = lambda + del_lambda;\n \n \n if options.verbosity >= 6\n fprintf(['lambda %.12e, ||y|| %.12e, lambda/sigma %.12e, ' ...\n 'phi %.12e\\n\\n'], lambda, ynorm, lambda / sigma, phi);\n end\n\n end\n\nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/solvers/arc/minimize_cubic_newton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6274423275782821}} {"text": "\nfunction [D, dD1, dD2] = dist_earth(coord1, coord2)\n% [D, dD] = dist_earth(coord1, coord2)\n% coord1 is 2 x N\n% coord2 is 2 x M\n% Returns N x M matrix D of mutual distances.\n\nif nargin < 2 || isempty(coord2)\n coord2 = coord1;\nend\n\nR = 6371.01; % Spherical Earth radius approximation\n\nn1 = cols(coord1);\nn2 = cols(coord2);\n\nD = zeros(n1, n2);\n\ncoord1 = pi/180 * coord1;\ncoord2 = pi/180 * coord2;\nif nargout >= 2\n dD1 = zeros([n1, n2, 2]);\nend\nif nargout >= 3\n error('Hmm.. maybe you shouldn''t use third output? :)');\n dD2 = zeros([n1, n2, 2]);\nend\n\nfor i=1:n1\n lat1 = coord1(2,i);\n lat2 = coord2(2,:);\n dlon = (coord2(1,:) - coord1(1,i));\n f = sin(lat2).*sin(lat1) + cos(lat2).*cos(lat1).*cos(dlon);\n f(f>=1-eps) = 1-eps; % correction because of numerical errors, f should be [-1,1]\n f(f<=eps-1) = eps-1; % correction because of numerical errors, f should be [-1,1]\n D(i,:) = R * acos(f);\n if ~isreal(D)\n coord1\n f\n% D\n error('Oohps! Complex distance..');\n end\n %dD_df(isinf(dD_df)) = 0;%-R ./ sqrt(1-f.^2);\n \n if nargout >= 2\n dD_df = -R ./ sqrt(1-f.^2);\n dD1(i,:,1) = pi/180 * dD_df .* cos(lat1) .* cos(lat2) .* sin(dlon);\n dD1(i,:,2) = pi/180 * dD_df .* (cos(lat1).*sin(lat2) - sin(lat1).* ...\n cos(lat2).*cos(dlon));\n end\n% $$$ if any(isnan(dD1))\n% $$$ dD1\n% $$$ error('WTF?');\n% $$$ end\n% $$$ if nargout >= 3\n% $$$ dD2(i,:,1) = -dD1(i,:,1);\n% $$$ dD2(i,:,2) = dD_df .* (sin(lat1).*cos(lat2) - cos(lat1).*sin(lat2).*cos(dlon));\n% $$$ end\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/geometry/dist_earth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6272726581237152}} {"text": "function e = rmModelSearchFit_oneOvalGaussian(p,Y,Xv,Yv,stim,t)\n% rmModelSearchFit_oneOvalGaussian - actual fit function of rmSearchFit\n%\n% error = rmModelSearchFit_oneOvalGaussian(p,Y,trends,Xgrid,YGrid,stimulusMatrix);\n%\n% Basic barebones fit of a single time-series. Error is returned in\n% percentage: 100% is RSS of unfitted time-series. This way we can quantify\n% the improvement of the fit independend of the variation in the raw\n% time-series.\n%\n% 2006/06 SOD: wrote it.\n% 2006/12 SOD: modifications for fmincon, this is litterally called >10000\n% times so we cut every corner possible. \n\n% make RF (taken from rfGaussian2d)\nXv = Xv - p(1); % positive x0 moves center right\nYv = Yv - p(2); % positive y0 moves center up\n\nXold = Xv;\nYold = Yv;\nXv = Xold .* cos(p(5)) - Yold .* sin(p(5));\nYv = Xold .* sin(p(5)) + Yold .* cos(p(5));\n\n% make gaussian on current grid\nRF = exp( -.5 * ((Yv ./ p(3)).^2 + (Xv ./ p(4)).^2));\n\n% make prediction (taken from rfMakePrediction)\nX = [stim*RF t];\n\n% fit - inlining pinv\n%b = pinv(X)*Y; \n[U,S,V] = svd(X,0);\ns = diag(S); \ntol = numel(X) * eps(max(s));\nr = sum(s > tol);\nif (r == 0)\n pinvX = zeros(size(X'));\nelse\n s = diag(ones(r,1)./s(1:r));\n pinvX = V(:,1:r)*s*U(:,1:r)';\nend\nb = pinvX*Y;\n\n% compute residual sum of squares (e)\n% e = norm(Y - X*abs(b));\nif b(1)>0,\n e = norm(Y - X*b);\nelse\n e = norm(Y).*(1+sum(abs(b(1))));\nend\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/Analysis/retinotopyModel/rmModelSearchFit_oneOvalGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6272039991548221}} {"text": "% irreg_demo\n%\n% demo of an irregularly sampled problem\n%\n% Author Piet M.T. Broersen, September 2008\n%\n% The three statements :\n% ****************************************************** \n% * [asel bsel sellog]=ARMAsel_mis(ti,xi,ARmax,Tr,w); *\n% * psdsel=arma2psd(asel,bsel); *\n% * corsel=arma2cor(asel,bsel,50); *\n% ****************************************************** \n% compute the selected estimated spectrum and autocorrelation function.\n% Sellog gives additional information and plots spectra of all estimated\n% AR models\n%\n% ti : observation times [s]\n% xi : observation amplitudes\n% ARmax : higherst candidate AR order\n% Tr : equidistant resampling distance [s]\n% w ; slot width as fraction of Tr [s]\n%\n% If the mean sampling frequency f0 Hz is high in comparison with the highest\n% frequency in the desired spectrum, it is advisable to use\n% nearest neighbor resampling and armasel.\n% See the example in simple_irreg_demo.\n% This gives very accurate spectra until f0/20 Hz and\n% about 50 % error due to resampling at f0/2pi.\n% The error becomes very large for higher frequencies and\n% armasel_irreg is advised for spectra higher than f0/2pi Hz.\n\nclear all, close all, clc, echo off\n \nload irreg_data\n% row vectors of times ti and amplitudes xi of irregularly sampled observations\n\nN=length(ti)\n\nfigure\nplot(ti,xi,'p',ti,xi,':r')\ntitle([int2str(N),' irregular benchmark data.'])\nxlabel('\\rightarrow time axis [s]')\naxis tight\n\ndisp('Mean time between observations')\nT0=(ti(N) - ti(1))/(N-1)\n \ndisp(' ')\ndisp('************************************************************************')\ndisp('Some warning messages from the OPTIM toolbox cannot be suppressed easily')\ndisp('It is not necessary to provide gradient information')\ndisp('Warnings generated by the MATLAB OPTIM routine fminunc can be ignored')\ndisp('************************************************************************')\ndisp(' ')\ndisp('Input values for ARMAsel_irreg')\nARmax=3\nw=1/2 %*Tres slot width, fraction of Tres\nTr=1/2000\ndisp(' ')\ndisp('[air bir sellogir] = ARMAsel_irreg(ti,xi,ARmax,Tr,w)')\n\n[air bir sellogir] = ARMAsel_irreg(ti,xi,ARmax,Tr,w)\n\ndisp('************************************************************************')\ndisp(' ')\ndisp('New input for w')\nw=1/8\ndisp(' ')\ndisp('[air2 bir2 sellogir2] = ARMAsel_irreg(ti,xi,ARmax,Tr,w)')\n[air2 bir2 sellogir2] = ARMAsel_irreg(ti,xi,ARmax,Tr,w)\n\ndisp('************************************************************************')\ndisp(' ')\ndisp('New input for w and Tr')\nw=1/2 %*Tres slot width, fraction of Tres\nTr2=1/4000\ndisp(' ')\ndisp('[air3 bir3 sellogir3] = ARMAsel_irreg(ti,xi,ARmax,Tr,w)')\n[air3 bir3 sellogir3] = ARMAsel_irreg(ti,xi,ARmax,Tr2,w)\n\n[h_ir f_ir] = arma2psd(air,bir,1000,Tr);\nh_ir2 = arma2psd(air2,bir2,1000,Tr);\n[h_ir3 f_ir3] = arma2psd(sellogir3.AR_sel_corrected,1,1000,Tr2);\n\ndisp(' ')\ndisp(' rc AR_sel for w = 1/2 and for w = 1/8, Tr = 0.0005 s')\n[dum rc_sel]=ar2arset(sellogir.ar);\n[dum rc_sel2]=ar2arset(sellogir2.ar);\n[dum rc_sel3]=ar2arset(sellogir3.AR_sel_corrected);\ndisp(rc_sel)\ndisp(rc_sel2)\ndisp(' rc AR_sel-corrected for w = 1/2, Tr = 0.00025 s')\ndisp(rc_sel3)\n\nfigure\nloglog(f_ir,h_ir,f_ir,h_ir2,f_ir3,h_ir3)\nlegend('\\it{Tr}\\rm = 0.0005 s, \\itw\\rm = 1/2 * \\it{Tr}\\rm s', ...\n '\\it{Tr}\\rm = 0.0005 s, \\itw\\rm = 1/8 * \\it{Tr}\\rm s', ...\n '\\it{Tr}\\rm = 0.00025 s, \\itw\\rm = 1/2 * \\it{Tr}\\rm s',3)\ntitle(['PSD of ',int2str(N),' irregular benchmark data.'])\nxlabel('\\rightarrow frequency [Hz]')\nylabel('\\rightarrow Logarithm of power spectral density')\naxis tight\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/18429-armasel-for-irregular-or-missing-data/irreg_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6271786699362942}} {"text": "function [w,b,sv,obj] = linear_primal_svm(lambda,wInit,bInit,D,noneg, maxIteration,opt)\n% Solves the following SVM optimization problem in the primal (with quatratic\n% penalization of the training errors). Default solved by Newton.\n%\n% min_{w,e} lambda/2 * w'w + 1/2 sum_i out_i^2\n% s.t. Y_i * (w .* X_i + b) >= D_i - out_i\n% w(nonneg)>=0\n%\n% A global variable X containing the training inputs\n% should be defined. X is an n x d matrix (n = number of points).\n% X can be either normal matrix or sparse matrix.\n% A global variable Y is the target vector of size nx1. Normal SVM will\n% have +1 and -1 value, but it can be actually aribitury value\n% A global variable n is the number of elements that you want to use for training.\n% LAMBDA is the regularization parameter ( = 1/C)\n% wInit is an optional input for the initial value of [w;b]\n% dvec is an optional input, usually it is 1 for standard SVM\n% maxIteration is the number of iterations allowd\n%\n% W is the hyperplane w (vector of length d).\n% B is the bias\n% The outputs on the training points are either X*W+B\n% SV is the support vector index number\n% OBJ is the objective function value\n% OPT is a structure containing the options (in brackets default values):\n% cg: Do not use Newton, but nonlinear conjugate gradients [0]\n% lin_cg: Compute the Newton step with linear CG\n% [0 unless solving sparse linear SVM]\n% iter_max_Newton: Maximum number of Newton steps [20]\n% prec: Stopping criterion\n% cg_prec and cg_it: stopping criteria for the linear CG.\n\n% Original written by Olivier Chapelle @ http://olivier.chapelle.cc/primal/\n% Modified by Jianxiong Xiao to have several advance features @ http://mit.edu/jxiao/\n\n\nif ~exist('maxIteration','var') || maxIteration==Inf % Assign the options to their default values\n maxIteration = 10000000;\nend\n\nif ~exist('opt','var') % Assign the options to their default values\n opt = [];\nend\nif ~isfield(opt,'cg'), opt.cg = 0; end;\nif ~isfield(opt,'lin_cg'), opt.lin_cg = 0; end;\nif ~isfield(opt,'iter_max_Newton'), opt.iter_max_Newton = 20; end; % used to be 20\nif ~isfield(opt,'prec'), opt.prec = 1e-6; end;\nif ~isfield(opt,'cg_prec'), opt.cg_prec = 1e-4; end;\nif ~isfield(opt,'cg_it'), opt.cg_it = 20; end;\n\n\nglobal X;\nglobal Y;\n\nif ~exist('noneg','var')\n noneg = [];\nend\n\nif ~exist('dvec','var') || isempty(D)\n D = ones(numel(Y),1);\nend\n\nif isempty(X), error('Global variable X undefined'); end;\n\nif ~exist('bInit','var')\n bInit=0;\nend\nif ~exist('wInit','var')\n d = size(X,2);\n wInit = zeros(d,1);\nend\nif issparse(X)\n opt.lin_cg = 1;\nend;\nif ~opt.cg\n [sol,obj, sv] = primal_svm_linear (lambda,maxIteration,wInit,bInit,D,noneg,opt);\nelse\n [sol,obj, sv] = primal_svm_linear_cg(lambda,maxIteration,wInit,bInit,D,noneg,opt);\nend;\n\n% The last component of the solution is the bias b.\nb = sol(end);\nw = sol(1:end-1);\nfprintf('\\n');\n\n\n% -------------------------------\n% Train a linear SVM using Newton\n% -------------------------------\nfunction [w,obj,sv] = primal_svm_linear(lambda,maxIteration,wInit,bInit,D,noneg,opt)\n\nglobal X;\nglobal Y;\nglobal n;\nd = size(X,2);\n\nw = [wInit; bInit]; % The last component of w is b.\nw(noneg) = max(w(noneg),0);\n%out = ones(n,1); % Vector containing 1-Y.*(X*w)\nout = D(1:n) - Y(1:n).*(X(1:n,:)*w(1:end-1)+w(end));\n\nfor iter=1:maxIteration\n if iter > opt.iter_max_Newton;\n warning('PrimalSVM:MaxNumNewton','Maximum number of Newton steps reached. Try larger lambda');\n break;\n end;\n \n [obj, grad, sv] = obj_fun_linear(w,lambda,out);\n \n % Compute the Newton direction either exactly or by linear CG\n if opt.lin_cg\n % Advantage of linear CG when using sparse input: the Hessian is never computed explicitly.\n [step, foo, relres] = minres(@hess_vect_mult, -grad, opt.cg_prec,opt.cg_it,[],[],[],sv,lambda);\n else\n Xsv = X(sv,:);\n hess = lambda*diag([ones(d,1); 0]) + [[Xsv'*Xsv sum(Xsv,1)']; [sum(Xsv) length(sv)]]; % Hessian\n step = - hess \\ grad; % Newton direction\n end;\n \n % Do an exact line search\n [t,out, sv] = line_search_linear(w,step,out, lambda);\n \n w = w + t*step;\n w(noneg) = max(w(noneg),0);\n fprintf('Iter = %d, Obj = %f, Nb of sv = %d, Newton decr = %.3f, Line search = %.3f',iter,obj,length(sv),-step'*grad/2,t);\n if opt.lin_cg\n fprintf(', Lin CG acc = %.4f \\n',relres);\n else\n fprintf(' \\n');\n end;\n \n if -step'*grad < opt.prec * obj\n % Stop when the Newton decrement is small enough\n break;\n end;\nend;\n\n\n\n% -----------------------------------------------------\n% Train a linear SVM using nonlinear conjugate gradient\n% -----------------------------------------------------\nfunction [w, obj, sv] = primal_svm_linear_cg(lambda,maxIteration,wInit,bInit, D,noneg,opt)\nglobal X;\nglobal Y;\nglobal n;\nd = size(X,2);\n\nw = [wInit; bInit]; % The last component of w is b.\nw(noneg) = max(w(noneg),0);\n%out = ones(n,1); % Vector containing 1-Y.*(X*w)\nout = D(1:n) - Y(1:n).*(X(1:n,:)*w(1:end-1)+w(end));\n\n%go = [X(1:n,:)'*Y(1:n); sum(Y(1:n))]; % -gradient at w=0, need to be change for w!=0 initialization\n[~, grad] = obj_fun_linear(w,lambda,out); go = -grad; % -gradient\n\n\ns = go; % The first search direction is given by the gradient\nfor iter=1:maxIteration\n if iter > opt.cg_it * min(n,d)\n warning('PrimalSVM:MaxNumCG','Maximum number of CG iterations reached. Try larger lambda');\n break;\n end;\n \n % Do an exact line search\n [t,out,sv] = line_search_linear(w,s,out,lambda);\n w = w + t*s;\n w(noneg) = max(w(noneg),0);\n \n % Compute the new gradient\n [obj, gn, sv] = obj_fun_linear(w,lambda,out); gn=-gn;\n fprintf('Iter = %d, Obj = %f, Norm of grad = %.3f \\n',iter,obj,norm(gn));\n \n % Stop when the relative decrease in the objective function is small\n if t*s'*go < opt.prec*obj, break; end;\n \n % Flecher-Reeves update. Change 0 in 1 for Polack-Ribiere\n be = (gn'*gn - 0*gn'*go) / (go'*go);\n s = be*s+gn;\n go = gn;\nend;\n\n\n\n\n\nfunction [obj, grad, sv] = obj_fun_linear(w,lambda,out)\n% Compute the objective function, its gradient and the set of support vectors\n% Out is supposed to contain 1-Y.*(X*w)\nglobal X;\nglobal Y;\nglobal n;\nout = max(0,out);\nwb0 = w; wb0(end) = 0; % Do not penalize b <= Very important for object detection\nobj = sum(out.^2)/2 + lambda*(wb0')*wb0/2; % L2 penalization of the errors\ngrad = lambda*wb0 - [((out.*Y(1:n))'*X(1:n,:))'; sum(out.*Y(1:n))]; % Gradient\nsv = find(out>0);\n\n\nfunction [t,out,sv] = line_search_linear(w,d,out,lambda)\n% From the current solution w, do a line search in the direction d by\n% 1D Newton minimization\nglobal X;\nglobal Y;\nglobal n;\nt = 0;\n% Precompute some dots products\nXd = X(1:n,:)*d(1:end-1)+d(end);\nwd = lambda * w(1:end-1)'*d(1:end-1);\ndd = lambda * d(1:end-1)'*d(1:end-1);\nwhile 1\n out2 = out - t*(Y(1:n).*Xd); % The new outputs after a step of length t\n sv = find(out2>0);\n g = wd + t*dd - (out2(sv).*Y(sv))'*Xd(sv); % The gradient (along the line)\n h = dd + Xd(sv)'*Xd(sv); % The second derivative (along the line)\n t = t - g/h; % Take the 1D Newton step. Note that if d was an exact Newton\n % direction, t is 1 after the first iteration.\n if g^2/h < 1e-10, break; end;\n % fprintf('%f %f\\n',t,g^2/h)\nend;\nout = out2;\n\n\n\nfunction y = hess_vect_mult(w,sv,lambda)\n% Compute the Hessian times a given vector x.\n% hess = lambda*diag([ones(d-1,1); 0]) + (X(sv,:)'*X(sv,:));\nglobal X;\nglobal n;\ny = lambda*w;\ny(end) = 0;\nz = (X(1:n,:)*w(1:end-1)+w(end)); % Computing X(sv,:)*x takes more time in Matlab :-(\nzz = zeros(length(z),1);\nzz(sv)=z(sv);\ny = y + [(zz'*X(1:n,:))'; sum(zz)];\n\n\n\n\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/linearSVM/linear_primal_svm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6271786646686405}} {"text": "function jac = p13_jac2 ( option, m, nvar, lambda, u )\n\n%*****************************************************************************80\n%\n%% P13_JAC2 computes the jacobian by recasting it on a square grid.\n%\n% Discussion:\n%\n% Actually, to stave off insanity, we only \"recast\" the variables into\n% a 2D array that corresponds to the spatial ordering of the grid.\n% We leave the jacobian in its original arrangement, which assumes\n% a linear ordering of variables and equations, and we simply\n% compute the equation and variable indices of the jacobian when\n% we are ready to put entries into it. This approach seems to produce\n% a smaller amount of cosmic grief than the alternatives.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer OPTION, the option index.\n%\n% Input, integer M, the number of grid points on a side of the square.\n%\n% Input, integer NVAR, the number of variables.\n%\n% Input, real LAMBDA, the value of the parameter.\n%\n% Input, real U(M,M), the value of the grid function.\n%\n% Output, real JAC(NVAR-1,NVAR), the jacobian matrix evaluated\n% at X. The NVAR-th row is not set by this routine.\n%\n jac(1:nvar-1,1:nvar) = 0.0;\n\n h = 1.0 / ( m + 1 );\n\n ieqn = 0;\n\n for i = 1 : m\n for j = 1 : m\n\n ieqn = ( j - 1 ) * m + i;\n\n uc = u(i + (j-1)*m);\n\n if ( i < m )\n un = u(i+1+(j-1)*m);\n else\n un = 0.0;\n end\n\n if ( 1 < i )\n us = u(i-1+(j-1)*m);\n else\n us = 0.0;\n end\n\n if ( j < m )\n ue = u(i+j*m);\n else\n ue = 0.0;\n end\n\n if ( 1 < j )\n uw = u(i+(j-2)*m);\n else\n uw = 0.0;\n end\n\n fc = p13_gx ( option, uc );\n fn = p13_gx ( option, un );\n fs = p13_gx ( option, us );\n fe = p13_gx ( option, ue );\n fw = p13_gx ( option, uw );\n\n del5f = fc + h * h * ( - 4.0 * fc + fn + fs + fe + fw ) / 12.0;\n\n fcp = p13_gp ( option, uc );\n fnp = p13_gp ( option, un );\n fsp = p13_gp ( option, us );\n fep = p13_gp ( option, ue );\n fwp = p13_gp ( option, uw );\n\n ivar = ( j - 1 ) * m + i;\n jac(ieqn,ivar) = - 20.0 / ( 6.0 * h * h ) ...\n + lambda * ( fcp - 4.0 * h * h * fcp / 12.0 );\n\n if ( i < m )\n ivar = ( j - 1 ) * m + i + 1;\n jac(ieqn,ivar) = 4.0 / ( 6.0 * h * h ) ...\n + lambda * h * h * fnp / 12.0;\n end\n\n if ( 1 < i )\n ivar = ( j - 1 ) * m + i - 1;\n jac(ieqn,ivar) = 4.0 / ( 6.0 * h * h ) ...\n + lambda * h * h * fsp / 12.0;\n end\n\n if ( j < m )\n ivar = j * m + i;\n jac(ieqn,ivar) = 4.0 / ( 6.0 * h * h ) ...\n + lambda * h * h * fep / 12.0;\n end\n\n if ( 1 < j )\n ivar = ( j - 2 ) * m + i;\n jac(ieqn,ivar) = 4.0 / ( 6.0 * h * h ) ...\n + lambda * h * h * fwp / 12.0;\n end\n\n if ( 1 < i & 1 < j )\n ivar = ( j - 2 ) * m + i - 1;\n jac(ieqn,ivar) = 1.0 / ( 6.0 * h * h );\n end\n\n if ( 1 < i & j < m )\n ivar = j * m + i - 1;\n jac(ieqn,ivar) = 1.0 / ( 6.0 * h * h );\n end\n\n if ( i < m & 1 < j )\n ivar = ( j - 2 ) * m + i + 1;\n jac(ieqn,ivar) = 1.0 / ( 6.0 * h * h );\n end\n\n if ( i < m & j < m )\n ivar = j * m + i + 1;\n jac(ieqn,ivar) = 1.0 / ( 6.0 * h * h );\n end\n\n ivar = nvar;\n jac(ieqn,nvar) = del5f;\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_con/p13_jac2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6271786442390126}} {"text": "function zz=lpcfq2zz(f,q)\n%LPCFQ2ZZ Convert frequencies and q factors to z-plane poles ZZ=(F,Q)\n%all input values are in normalized Hz\n% roots are at exp(2*pi*f*(-1/(2q) +- j)\n% if f has more columns than q, remaining columns are real roots at -f\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: lpcfq2zz.m,v 1.4 2007/05/04 07:01:38 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[nf,pf]=size(f);\nif nargin < 2\n pq=0;\nelse\n pq=size(q,2);\nend;\nzz=zeros(nf,pf+pq);\nif pq\n ii=1:pq;\n zz(:,2*ii-1)=exp(pi*f(:,ii).*(2i-q.^(-1)));\n zz(:,2*ii)=conj(zz(:,2*ii-1));\nend\nif pf>pq\n ii=1+pq:pf;\n zz(:,ii+pq)= exp(-2*pi*f(:,ii));\nend\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/lpcfq2zz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6271752299775134}} {"text": "%Kalman Demo 2 (Mauna Loa Periodic CO2 Readings)\n%\n% In this demo we apply the state space inference methods to the \n% well-known time series data consisting of atmospheric CO2 \n% concentration readings in parts per million (ppm) by volume from \n% air samples collected at the Mauna Loa observatory, Hawaii (see\n% [1] for details and further references).\n%\n% The benefit from the state space formulation is that the \n% computational complexity is linear with respect to the number\n% of data points. Due to efficient matrix solvers in Matlab \n% (favoring the traditional GP solution over sequential looping),\n% the advantages in speed start to show in datasets with thousands\n% of data points.\n%\n% The take-home message from this demo is that the GP can be\n% set up exactly as any other GP regression model in GPstuff, \n% and then solved by Kalman filtering methods by specifying the\n% 'type' in the GP structure to be 'KALMAN'.\n%\n% The methods in this demo are based on the paper:\n%\n% [1] Arno Solin and Simo Sarkka (2014). Explicit link between periodic \n% covariance functions and state space models. Accepted for \n% publication in Proceedings of the Seventeenth International \n% Conference on Artifcial Intelligence and Statistics (AISTATS 2014).\n%\n% Copyright (c) 2014 Arno Solin and Jukka Koskenranta\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%% Load the data\n\n % Load the data\n S = which('demo_kalman2.m');\n L = strrep(S,'demo_kalman2.m','demodata/maunaloa_data.txt');\n\n % Set training data (x = time in years, y = CO2 observations)\n data = load(L);\n y = data(:, 2:13)'; y=y(:);\n x = (data(1,1):1/12:data(end,1)+11/12)';\n \n % Remove data points with missing information\n x = x(y>0); y = y(y>0);\n \n % Make data zero mean\n ymean = mean(y); y = y-ymean;\n \n % Show original data\n figure(1); clf\n plot(x,y+ymean,'-k')\n xlabel('Time (year)');\n ylabel('CO_2 concentration (PPM)')\n title('Kalman Demo 2 (Mauna Loa Periodic CO2 Readings) - Data')\n \n \n%% Set up GP model\n\n % Noise variance prior\n ps2 = prior_logunif(); \n \n % The likelihood model\n lik = lik_gaussian('sigma2', 1, 'sigma2_prior', ps2);\n \n % Covariance function hyperparameter priors\n pl = prior_logunif(); \n pm = prior_logunif();\n \n % A squared exponential covariance function \n % to deal with the smooth long term effects\n gpcf1 = gpcf_sexp('lengthScale', 100, 'magnSigma2', 5000, ...\n 'lengthScale_prior',pl,'magnSigma2_prior',pl);\n \n % A quasi-periodic covariance function deals with peridic \n % variation in the data. The quasi-periodic covariance function \n % is a product of a periodic covariance function and a squared\n % exponential. \n gpcf2 = gpcf_periodic('magnSigma2',1,'lengthScale',1,'period',1, ...\n 'decay',1,'lengthScale_sexp',100, ...\n 'lengthScale_prior',pl,'magnSigma2_prior',pl, ...\n 'lengthScale_sexp_prior',pl);\n \n \n % A Matern52 covariance function deals with short term\n % non-periodic effects that remain otherwise unexplained\n gpcf3 = gpcf_matern52('lengthScale', 10, 'magnSigma2', 10, ...\n 'lengthScale_prior',pl,'magnSigma2_prior',pl);\n \n % Finally create the GP structure\n gp = gp_set('lik', lik, 'cf', {gpcf1,gpcf2,gpcf3});\n \n % Set type to KALMAN\n gp = gp_set(gp,'type','KALMAN');\n \n \n%% Optimize hyperparameters and predict\n\n % Optimization parameters\n opt=optimset('TolFun',1e-4,'TolX',1e-4,'Display','iter');\n\n % Find hyperparameters by optimization (BFGS)\n gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);\n \n % Set the test points\n xt = (x(end):1/12:x(end)+10)';\n \n % Predict values\n [Eft,Varft] = gp_pred(gp, x, y,'xt',xt);\n \n % Also predict the latent components separately\n [Eft1, Varft1] = gp_pred(gp, x, y, x, 'predcf', [1 3]);\n [Eft2, Varft2] = gp_pred(gp, x, y, x, 'predcf', [2]);\n\n \n%% Visualize results\n\n % Plot\n figure(2); clf; hold on\n \n % Plot the 95% confidence interval of the predictions\n p=patch([xt; flipud(xt)], ...\n [ymean + Eft + 1.96*sqrt(Varft); ...\n flipud(ymean + Eft - 1.96*sqrt(Varft))],[0.9,0.9,0.9]);\n set(p,'EdgeColor','none')\n \n % Plot observations\n plot(x,ymean+y,'.k','MarkerSize',5)\n\n % Labels and legends\n title('Kalman Demo 2 (Mauna Loa Periodic CO2 Readings)')\n xlabel('Time (years)');\n ylabel('CO_2 concentration (PPM)')\n legend('95% confidence region', ...\n 'Monthly average measurements',...\n 'Location', 'NorthWest');\n \n % Axis options\n box on; axis tight; set(gca,'Layer','top')\n\n \n%% Show components separately\n \n figure(3); clf;\n subplot(211)\n \n plot(x,Eft1,'-k')\n \n title('Long-term trend and short-scale variation')\n xlabel('Time (years)');\n ylabel('Effect on CO_2 concentration (PPM)')\n \n axis tight\n \n subplot(212)\n \n plot(x,Eft2,'-k')\n \n title('Quasi-periodic effect')\n xlabel('Time (years)');\n ylabel('Effect on CO_2 concentration (PPM)')\n \n axis tight\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/demo_kalman2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.627155837007865}} {"text": "\n% ######################################################################################################################################################################################\n% We are here talking about spatio-temporal detections, i.e. a set of ground-truth bounding boxes that\n% I will denote by g_t, with t between t_g^b and t_g^e (beginning and end time of the ground-truth)\n% versus a detection which is also a set of bounding boxes, denoted by d_t, with t between t_d^e et t_d^e.\n%\n% a) temporal iou = T_i / T_u\n% this is the intersection over union between the timing of the the tubes,\n% ie mathematically T_i / T_u with\n% the intersection T_i = max(0, max(t_g^b,t_d^b)-min(t_d^e,t_g^e) )\n% and the union T_u = min(t_g^b,t_d^b)-max(t_d^e,t_g^e)\n%\n% b) for each t between max(tgb,tdb)-min(tde,tge), we compute the IoU between g_t and d_t, and average them\n%\n% Multiplying (a) and (b) is the same as computed the average of the spatial iou over all frames in T_u of the two tubes, with a spatial iou of 0 for frames where only one box exists.\n% c) as this is standard in detection problem, if there are multiple detections for the same groundtruth detection, the first one is counted as positive and the other ones as negatives\n% ######################################################################################################################################################################################\n%{\ngt_fnr = 1xn doube\ngt_bb = nx4 doubld - [x y w h]\ndt_fnr = 1xm double\ndt_bb = mx4 double - [x y w h]\n%}\n% -------------------------------------------------------------------------\nfunction st_iou = compute_spatio_temporal_iou(gt_fnr, gt_bb, dt_fnr, dt_bb)\n% -------------------------------------------------------------------------\n\n% time gt begin\n\ntgb = gt_fnr(1);\n% time gt end\ntge = gt_fnr(end);\n%time dt begin\ntdb = dt_fnr(1);\ntde = dt_fnr(end);\n% temporal intersection\nT_i = double(max(0, min(tge,tde)-max(tgb,tdb)));\n\nif T_i>0\n T_i = T_i +1;\n % temporal union\n T_u = double(max(tge,tde) - min(tgb,tdb)+1);\n %temporal IoU\n T_iou = T_i/T_u;\n % intersect frame numbers\n int_fnr = max(tgb,tdb):min(tge,tde);\n \n % find the ind of the intersected frames in the detected frames\n [~,int_find_dt] = ismember(int_fnr, dt_fnr);\n [~,int_find_gt] = ismember(int_fnr, gt_fnr);\n \n assert(length(int_find_dt)==length(int_find_gt));\n \n iou = zeros(length(int_find_dt),1);\n for i=1:length(int_find_dt)\n if int_find_gt(i)<1\n% fprintf('error ')\n pf = pf;\n else\n pf = i;\n end\n \n gt_bound = gt_bb(int_find_gt(pf),:);\n dt_bound = dt_bb(int_find_dt(pf),:)+1;\n \n % gt_bound = [gt_bound(:,1:2) gt_bound(:,3:4)-gt_bound(:,1:2)];\n % dt_bound = [dt_bound(:,1:2) dt_bound(:,3:4)-dt_bound(:,1:2)];\n iou(i) = inters_union(double(gt_bound),double(dt_bound));\n end\n % finalspatio-temporal IoU threshold\n st_iou = T_iou*mean(iou);\nelse\n st_iou =0;\nend\n% % iou_thresh = 0.2,...,0.6 % 'Learing to track paper' takes 0.2 for UCF101 and 0.5 for JHMDB\n% if delta >= iou_thresh\n% % consider this tube as valid detection\n% end\n\nend\n\n% -------------------------------------------------------------------------\nfunction iou = inters_union(bounds1,bounds2)\n% -------------------------------------------------------------------------\n\ninters = rectint(bounds1,bounds2);\nar1 = bounds1(:,3).*bounds1(:,4);\nar2 = bounds2(:,3).*bounds2(:,4);\nunion = bsxfun(@plus,ar1,ar2')-inters;\n\niou = inters./(union+eps);\n\nend\n", "meta": {"author": "gurkirt", "repo": "corrected-UCF101-Annots", "sha": "5de776b9b57a3bb27cb22dc75f3efa808b4445ff", "save_path": "github-repos/MATLAB/gurkirt-corrected-UCF101-Annots", "path": "github-repos/MATLAB/gurkirt-corrected-UCF101-Annots/corrected-UCF101-Annots-5de776b9b57a3bb27cb22dc75f3efa808b4445ff/evaluation/compute_spatio_temporal_iou.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6270787366543035}} {"text": "\n% ######################################################################################################################################################################################\n% We are here talking about spatio-temporal detections, i.e. a set of ground-truth bounding boxes that\n% I will denote by g_t, with t between t_g^b and t_g^e (beginning and end time of the ground-truth)\n% versus a detection which is also a set of bounding boxes, denoted by d_t, with t between t_d^e et t_d^e.\n%\n% a) temporal iou = T_i / T_u\n% this is the intersection over union between the timing of the the tubes,\n% ie mathematically T_i / T_u with\n% the intersection T_i = max(0, max(t_g^b,t_d^b)-min(t_d^e,t_g^e) )\n% and the union T_u = min(t_g^b,t_d^b)-max(t_d^e,t_g^e)\n%\n% b) for each t between max(tgb,tdb)-min(tde,tge), we compute the IoU between g_t and d_t, and average them\n%\n% Multiplying (a) and (b) is the same as computed the average of the spatial iou over all frames in T_u of the two tubes, with a spatial iou of 0 for frames where only one box exists.\n% c) as this is standard in detection problem, if there are multiple detections for the same groundtruth detection, the first one is counted as positive and the other ones as negatives\n% ######################################################################################################################################################################################\n%{\ngt_fnr = 1xn doube\ngt_bb = nx4 doubld - [x y w h]\ndt_fnr = 1xm double\ndt_bb = mx4 double - [x y w h]\n%}\n% -------------------------------------------------------------------------\nfunction st_iou = compute_spatio_temporal_iou(gt_fnr, gt_bb, dt_fnr, dt_bb)\n% -------------------------------------------------------------------------\n\n% time gt begin\ntgb = gt_fnr(1);\n% time gt end\ntge = gt_fnr(end);\n%time dt begin\ntdb = dt_fnr(1);\ntde = dt_fnr(end);\n% temporal intersection\nT_i = double(max(0, min(tge,tde)-max(tgb,tdb)));\n\nif T_i>0\n T_i = T_i +1;\n % temporal union\n T_u = double(max(tge,tde) - min(tgb,tdb)+1);\n %temporal IoU\n T_iou = T_i/T_u;\n % intersect frame numbers\n int_fnr = max(tgb,tdb):min(tge,tde);\n \n % find the ind of the intersected frames in the detected frames\n [~,int_find_dt] = ismember(int_fnr, dt_fnr);\n [~,int_find_gt] = ismember(int_fnr, gt_fnr);\n \n assert(length(int_find_dt)==length(int_find_gt));\n \n iou = zeros(length(int_find_dt),1);\n for i=1:length(int_find_dt)\n if int_find_gt(i)<1\n% fprintf('error ')\n pf = pf;\n else\n pf = i;\n end\n \n gt_bound = gt_bb(int_find_gt(pf),:);\n dt_bound = dt_bb(int_find_dt(pf),:)+1;\n \n % gt_bound = [gt_bound(:,1:2) gt_bound(:,3:4)-gt_bound(:,1:2)];\n % dt_bound = [dt_bound(:,1:2) dt_bound(:,3:4)-dt_bound(:,1:2)];\n iou(i) = inters_union(double(gt_bound),double(dt_bound));\n end\n % finalspatio-temporal IoU threshold\n st_iou = T_iou*mean(iou);\nelse\n st_iou =0;\nend\n% % iou_thresh = 0.2,...,0.6 % 'Learing to track paper' takes 0.2 for UCF101 and 0.5 for JHMDB\n% if delta >= iou_thresh\n% % consider this tube as valid detection\n% end\n\nend\n\n% -------------------------------------------------------------------------\nfunction iou = inters_union(bounds1,bounds2)\n% -------------------------------------------------------------------------\n\ninters = rectint(bounds1,bounds2);\nar1 = bounds1(:,3).*bounds1(:,4);\nar2 = bounds2(:,3).*bounds2(:,4);\nunion = bsxfun(@plus,ar1,ar2')-inters;\n\niou = inters./(union+eps);\n\nend\n", "meta": {"author": "gurkirt", "repo": "realtime-action-detection", "sha": "9dd8e1b5642c7cb3170a31cc3ec5a3c586a3b261", "save_path": "github-repos/MATLAB/gurkirt-realtime-action-detection", "path": "github-repos/MATLAB/gurkirt-realtime-action-detection/realtime-action-detection-9dd8e1b5642c7cb3170a31cc3ec5a3c586a3b261/matlab-online-display/eval/compute_spatio_temporal_iou.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6270787342863048}} {"text": "function uI = faceinterpolate(u,node,elem,elemType)\n%% FACEINTERPOLATE interpolate to face elements (RT0 or BDM1).\n%\n% uI = faceinterpolate(u,node,elem,elemType) interpolates a given function u\n% into the lowesr order RT0 or BDM1 finite element spaces. The coefficient\n% is given by the line integral int_e u*n ds. The input elemType can be 'RT0'\n% or 'BDM1'.\n%\n% Example: RT0\n% \n% maxIt = 5;\n% node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n% elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % elements\n% bdFlag = setboundary(node,elem,'Dirichlet');\n% pde = mixBCdata;\n% err = zeros(maxIt,2); \n% h = zeros(maxIt,1);\n% for k =1:maxIt\n% [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% [u,sigma,eqn] = PoissonRT0(node,elem,bdFlag,pde);\n% sigmaI = faceinterpolate(pde.Du,node,elem,'RT0');\n% err(k,1) = getL2errorRT0(node,elem,pde.Du,sigmaI);\n% err(k,2) = sqrt((sigma-sigmaI)'*eqn.M*(sigma-sigmaI));\n% h(k) = 1./(sqrt(size(node,1))-1);\n% end\n% figure;\n% showrateh2(h,err(:,1),2,'r-+','|| \\sigma - \\sigma_I ||',...\n% h,err(:,2),2,'b-+','|| \\sigma_h - \\sigma_I ||');\n%\n% Example: BDM1\n%\n% maxIt = 5;\n% node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n% elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % elements\n% bdFlag = setboundary(node,elem,'Dirichlet');\n% pde = mixBCdata;\n% err = zeros(maxIt,2); \n% h = zeros(maxIt,1);\n% for k =1:maxIt\n% [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% [u,sigma,eqn] = PoissonBDM1(node,elem,bdFlag,pde);\n% sigmaI = faceinterpolate(pde.Du,node,elem,'BDM1');\n% err(k,1) = getL2errorBDM1(node,elem,pde.Du,sigmaI);\n% err(k,2) = sqrt((sigma-sigmaI)'*eqn.M*(sigma-sigmaI));\n% h(k) = 1./(sqrt(size(node,1))-1);\n% end\n% figure;\n% showrateh2(h,err(:,1),2,'r-+','|| \\sigma - \\sigma_I ||',...\n% h,err(:,2),2,'b-+','|| \\sigma_h - \\sigma_I ||');\n%\n%\n% Example: RT1\n%\n% maxIt = 5;\n% node = [1,0; 1,1; 0,1; -1,1; -1,0; -1,-1; 0,-1; 0,0]; % nodes\n% elem = [1,2,8; 3,8,2; 8,3,5; 4,5,3; 7,8,6; 5,6,8]; % elements\n% bdFlag = setboundary(node,elem,'Dirichlet');\n% pde = mixBCdata;\n% err = zeros(maxIt,2); \n% h = zeros(maxIt,1);\n% for k = 1:maxIt\n% [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% sigmaI = faceinterpolate(pde.Du,node,elem,'RT1');\n% err(k,1) = getL2errorRT1(node,elem,pde.Du,sigmaI);\n% h(k) = 1./(sqrt(size(node,1))-1);\n% end\n% figure;\n% showrateh2(h,err(:,1),2,'r-+','|| \\sigma - \\sigma_I ||',...\n% h,err(:,2),2,'b-+','|| \\sigma_h - \\sigma_I ||');\n%\n%\n% See also edgeinterpolate, edgeinterpolate1, edgeinterpolate2\n%\n% Created by Ming Wang at Mar 29, 2011, M-lint modified at May 14, 2011.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('elemType','var'), elemType = 'RT0'; end\n%% edge \nif size(elem,2) == 2 % the input elem is edge\n edge = elem;\nelse\n [elem2edge,edge] = dofedge(elem);\nend\nNE = size(edge,1);\nNT = size(elem,1);\nedgeVec = node(edge(:,2),:) - node(edge(:,1),:);\nnVec = zeros(NE,2);\nnVec(:,1) = edgeVec(:,2); \nnVec(:,2) = -edgeVec(:,1);\nclear edgeVec\n\n%% dof for RT0\n[lambda,weight] = quadpts1(4);\nnQuad = size(lambda,1);\nuI = zeros(NE,1);\nfor i = 1:nQuad\n pxy = lambda(i,1)*node(edge(:,1),:)+lambda(i,2)*node(edge(:,2),:);\n flux = u(pxy);\n uI = uI + weight(i)*dot(flux,nVec,2); \nend\n\n%% dof for BDM1\nif strcmp(elemType,'BDM1') || strcmp(elemType,'RT1')\n uI(NE+1:2*NE) = zeros(NE,1);\n for i = 1:nQuad\n pxy = lambda(i,1)*node(edge(:,1),:)+lambda(i,2)*node(edge(:,2),:);\n uI(NE+1:2*NE) = uI(NE+1:2*NE)+ ...\n weight(i)*3*(lambda(i,1)-lambda(i,2))*dot(u(pxy),nVec,2); \n end\nend\n\n%% dof for RT1\nif strcmp(elemType,'RT1')\n mid = (node(edge(:,1),:) + node(edge(:,2),:))/2;\n umid = u(mid);\n uI(2*NE+2*NT) = 0;\n % Face dof coefficients\n uquadpts = umid(elem2edge(:,1),:)+umid(elem2edge(:,2),:)+umid(elem2edge(:,3),:);\n lf = [4*dot(nVec(elem2edge(:,2),:),uquadpts,2) ...\n 4*dot(nVec(elem2edge(:,3),:),uquadpts,2)];\n elem2edgeDofValue = [uI(elem2edge(:,1:3)) uI(elem2edge(:,1:3)+NE)];\n localMatrix = [4 8 4 -4 0 4; ...\n 8 4 -4 0 -4 4]';\n lf = lf - elem2edgeDofValue*localMatrix;\n uI((2*NE+1):end) = [2*lf(:,1) - lf(:,2); ...\n 2*lf(:,2) - lf(:,1)]/3; \nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/faceinterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6270787209958699}} {"text": "function varargout = rotation3dToEulerAngles(mat, varargin)\n%ROTATION3DTOEULERANGLES Extract Euler angles from a rotation matrix.\n%\n% [PHI, THETA, PSI] = rotation3dToEulerAngles(MAT)\n% Computes Euler angles PHI, THETA and PSI (in degrees) from a 3D 4-by-4\n% or 3-by-3 rotation matrix.\n%\n% ANGLES = rotation3dToEulerAngles(MAT)\n% Concatenates results in a single 1-by-3 row vector. This format is used\n% for representing some 3D shapes like ellipsoids.\n%\n% ... = rotation3dToEulerAngles(MAT, CONVENTION)\n% CONVENTION specifies the axis rotation sequence. Default is 'ZYX'.\n% Supported conventions are: \n% 'ZYX','ZXY','YXZ','YZX','XYZ','XZY'\n% 'ZYZ','ZXZ','YZY','YXY','XZX','XYX'\n%\n% Example\n% rotation3dToEulerAngles\n%\n% References\n% Code from '1994 - Shoemake - Graphics Gems IV: Euler Angle Conversion:\n% http://webdocs.cs.ualberta.ca/~graphics/books/GraphicsGems/gemsiv/euler_angle/EulerAngles.c\n% (see rotm2eul, that is part of MATLAB's Robotics System Toolbox)\n% Modified using explanations in:\n% http://www.gregslabaugh.net/publications/euler.pdf\n% https://www.geometrictools.com/Documentation/EulerAngles.pdf\n%\n% See also \n% transforms3d, rotation3dAxisAndAngle, createRotation3dLineAngle,\n% eulerAnglesToRotation3d\n%\n\n% ------\n% Authors: David Legland, oqilipo\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2010-08-11, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010-2022 INRA - Cepia Software Platform\n\np = inputParser;\nvalidStrings = {...\n 'ZYX','ZXY','YXZ','YZX','XYZ','XZY',...\n 'ZYZ','ZXZ','YZY','YXY','XZX','XYX'};\naddOptional(p,'convention','ZYX',@(x) any(validatestring(x,validStrings)));\nlogParValidFunc = @(x) (islogical(x) || isequal(x,1) || isequal(x,0));\naddParameter(p,'IsRotation', 1, logParValidFunc);\nvalTol = @(x) validateattributes(x,{'numeric'},{'scalar', '>=',eps(class(mat)), '<=',1});\naddParameter(p,'tolerance', 1e-8, valTol);\nparse(p,varargin{:});\nconvention=p.Results.convention;\nisRotation = p.Results.IsRotation;\ntolerance = p.Results.tolerance;\n\nif isRotation\n if ~isTransform3d(mat(1:3,1:3), 'rotation', 1, 'tolerance', tolerance)\n warning(['Rotation matrix contains reflection or scaling ' ...\n 'tested with a tolerance of ' num2str(tolerance) '.' newline ...\n 'Calculation of euler angles might be incorrect.'])\n end\nend\n\nswitch convention\n case 'ZYX'\n % extract |cos(theta)|\n cy = hypot(mat(1,1), mat(2,1));\n % avoid dividing by 0\n if cy > 16*eps\n % normal case: theta <> 0\n phi = atan2( mat(2,1), mat(1,1));\n theta = atan2(-mat(3,1), cy);\n psi = atan2( mat(3,2), mat(3,3));\n else\n phi = 0;\n theta = atan2(-mat(3,1), cy);\n psi = atan2(-mat(2,3), mat(2,2));\n end\n case 'ZXY'\n cy = hypot(mat(2,2), mat(1,2));\n if cy > 16*eps\n phi = -atan2( mat(1,2), mat(2,2));\n theta = -atan2(-mat(3,2), cy);\n psi = -atan2( mat(3,1), mat(3,3));\n else\n phi = 0;\n theta = -atan2(-mat(3,2), cy);\n psi = -atan2(-mat(1,3), mat(1,1));\n end\n case 'YXZ'\n cy = hypot(mat(3,3), mat(1,3));\n if cy > 16*eps\n phi = atan2( mat(1,3), mat(3,3));\n theta = atan2(-mat(2,3), cy);\n psi = atan2( mat(2,1), mat(2,2));\n else\n phi = 0;\n theta = atan2(-mat(2,3), cy);\n psi = atan2(-mat(1,2), mat(1,1));\n end\n case 'YZX'\n cy = hypot(mat(1,1), mat(3,1));\n if cy > 16*eps\n phi = -atan2( mat(3,1), mat(1,1));\n theta = -atan2(-mat(2,1), cy);\n psi = -atan2( mat(2,3), mat(2,2));\n else\n phi = 0;\n theta = -atan2(-mat(2,1), cy);\n psi = -atan2(-mat(3,2), mat(3,3));\n end\n case 'XYZ'\n cy = hypot(mat(3,3), mat(2,3));\n if cy > 16*eps\n phi = -atan2( mat(2,3), mat(3,3));\n theta = -atan2(-mat(1,3), cy);\n psi = -atan2( mat(1,2), mat(1,1));\n else\n phi = 0;\n theta = -atan2(-mat(1,3), cy);\n psi = -atan2(-mat(2,1), mat(2,2));\n end\n case 'XZY'\n cy = hypot(mat(2,2), mat(3,2));\n if cy > 16*eps\n phi = atan2( mat(3,2), mat(2,2));\n theta = atan2(-mat(1,2), cy);\n psi = atan2( mat(1,3), mat(1,1));\n else\n phi = 0;\n theta = atan2(-mat(1,2), cy);\n psi = atan2(-mat(3,1), mat(3,3));\n end\n \n case 'ZYZ'\n cy = hypot(mat(3,2), mat(3,1));\n if cy > 16*eps\n phi = -atan2(mat(2,3), -mat(1,3));\n theta = -atan2(cy, mat(3,3));\n psi = -atan2(mat(3,2), mat(3,1));\n else\n phi = 0;\n theta = -atan2(cy, mat(3,3));\n psi = -atan2(-mat(2,1), mat(2,2));\n end\n case 'ZXZ'\n cy = hypot(mat(3,2), mat(3,1));\n if cy > 16*eps\n phi = atan2(mat(1,3), -mat(2,3));\n theta = atan2(cy, mat(3,3));\n psi = atan2(mat(3,1), mat(3,2));\n else\n phi = 0;\n theta = atan2(cy, mat(3,3));\n psi = atan2(-mat(1,2), mat(1,1));\n end\n case 'YZY'\n cy = hypot(mat(2,3), mat(2,1));\n if cy > 16*eps\n phi = atan2(mat(3,2), -mat(1,2));\n theta = atan2(cy, mat(2,2));\n psi = atan2(mat(2,3), mat(2,1));\n else\n phi = 0;\n theta = atan2(cy, mat(2,2));\n psi = atan2(-mat(3,1), mat(3,3));\n end\n case 'YXY'\n cy = hypot(mat(2,3), mat(2,1));\n if cy > 16*eps\n phi = -atan2(mat(1,2), -mat(3,2));\n theta = -atan2(cy, mat(2,2));\n psi = -atan2(mat(2,1), mat(2,3));\n else\n phi = 0;\n theta = -atan2(cy, mat(2,2));\n psi = -atan2(-mat(1,3), mat(1,1));\n end\n case 'XZX'\n cy = hypot(mat(1,3), mat(1,2));\n if cy > 16*eps\n phi = -atan2(mat(3,1), -mat(2,1));\n theta = -atan2(cy, mat(1,1));\n psi = -atan2(mat(1,3), mat(1,2));\n else\n phi = 0;\n theta = -atan2(cy, mat(1,1));\n psi = -atan2(-mat(3,2), mat(3,3));\n end\n case 'XYX'\n cy = hypot(mat(1,2), mat(1,3));\n if cy > 16*eps\n phi = atan2(mat(2,1), -mat(3,1));\n theta = atan2(cy, mat(1,1));\n psi = atan2(mat(1,2), mat(1,3));\n else\n phi = 0;\n theta = atan2(cy, mat(1,1));\n psi = atan2(-mat(2,3), mat(2,2));\n end\nend\n\n% format output arguments\nif nargout <= 1\n % one array\n varargout{1} = rad2deg([phi theta psi]);\nelse\n % three separate arrays\n varargout = cellfun(@rad2deg, {phi theta psi},'uni',0);\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/rotation3dToEulerAngles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6270787186278716}} {"text": "classdef SPX_ConjugateDescent < handle\n% Conjugate gradient algorithm implementation\n\n\n properties\n % Settable and gettable properties\n\n % Maximum number of iterations for which the algorithm can run\n MaxIterations\n % Threshold of norm (in terms of percentage)\n NormThreshold\n end\n\n\n properties(SetAccess=private)\n % Gettable properties\n\n % The sparse symmetric positive definite matrix operator\n A\n % The vectors to be solved\n B\n % Problem dimension\n N\n % Number of equations to be solved\n S\n % Number of iterations taken for solving the problem\n Iterations\n % Residual norms at the end\n ResidualNorms\n % The solution vectors\n X\n % Residual vectors\n Residuals\n % Indicates if the problems converged\n % This would be false only if the algorithm crossed max iterations\n Converged\n end\n\n methods\n % Public methods\n function self = SPX_ConjugateDescent(A, B)\n % Constructor\n if isa(A, 'spx.dict.Operator')\n self.A = A;\n elseif ismatrix(A)\n self.A = spx.dict.MatrixOperator(A); \n else\n error('Unsupported operator.');\n end\n self.B = B;\n [self.N, self.S] = size(B);\n self.MaxIterations = self.N ;\n self.NormThreshold = 1e-6;\n end\n\n function result = solve(self)\n aa = self.A;\n bb = self.B;\n % Initial estimate vectors are all zeros\n xx = zeros(self.N, self.S);\n result = xx;\n self.Iterations = zeros(self.S, 1);\n self.ResidualNorms = zeros(self.S, 1);\n self.Converged = false(self.S, 1);\n % Initial residual vectors\n rr = bb - aa * xx;\n self.Residuals = rr;\n % Norm squared of initial residual vectors\n deltas = spx.norm.inner_product_cw(rr, rr);\n % The factor with which the norm needs to be reduced\n epsilon = self.NormThreshold;\n % Target limits on norm squared of residuals\n limits = epsilon^2 * deltas;\n % Maximum number of iterations for which the algorithm \n % is allowed to run\n imax = self.MaxIterations;\n % Number of problems being solved\n ns = self.S;\n for s=1:ns\n % Initialize iteration counter\n i = 0;\n % The quantities for this problem\n limit = limits(s);\n delta = deltas(s);\n % First residual\n r = rr(:, s);\n % First estimate\n x = xx(:, s);\n % Target b\n b = bb(:, s);\n % First direction\n d = r;\n while i < imax && delta > limit\n % Compute the intermediate variable\n q = aa * d;\n % the line search scale factor in current direction\n alpha = delta / (d' * q);\n % Update estimate in current direction\n x = x + alpha * d;\n if mod(i , 50) == 0\n % In order to avoid propagation of floating point\n % errors, we will recompute the value of residual\n r = b - aa * x;\n else\n % Otherwise we use a shortcut\n r = r - alpha * q;\n end\n % hold the current residual norm squared\n delta_old = delta;\n % Update residual norm squared\n delta = r' * r;\n % Compute the ratio\n beta = delta / delta_old;\n % choose the new direction\n d = r + beta * d;\n % Increase iteration counter\n i = i + 1;\n end\n % The problem has been solved\n result(:, s) = x;\n % Number of iterations taken to solve this problem\n self.Iterations(s) = i;\n self.ResidualNorms(s) = sqrt(delta);\n self.Residuals(:, s) = r;\n self.Converged(s) = delta <= limit;\n end\n % Maintain the result for reference\n self.X = result;\n end\n\n function result = hasConverged(self)\n % Returns if all the solutions have converged\n result = all(self.Converged);\n end\n\n function printResults(self)\n ns = self.S;\n nn = self.N;\n for s = 1:ns\n fprintf('Problem: %d\\n', s);\n fprintf('Iterations: %d\\n', self.Iterations(s));\n fprintf('Residual norm: %.2f, Converged: %d\\n', ...\n self.ResidualNorms(s), self.Converged(s));\n if nn < 10\n % We will print the solutions too\n fprintf('Solution vector: ');\n fprintf('%.4f ', self.X(:, s));\n fprintf('\\n');\n fprintf('Residual vector: ');\n fprintf('%.4f ', self.Residuals(:, s));\n fprintf('\\n');\n end\n end\n end\n end\n\n\n methods(Access=private)\n % Private methods\n\n end\n\n\n\n methods(Static)\n % Public static methods\n\n\n end\n\n\nend\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+opt/convex_optimization/conjugate_gradient/SPX_ConjugateDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6270787159697845}} {"text": "function [z,a,it,ord,s,fct] = backcor(n,y,ord,s,fct)\n\n% BACKCOR Background estimation by minimizing a non-quadratic cost function.\n%\n% [EST,COEFS,IT] = BACKCOR(N,Y,ORDER,THRESHOLD,FUNCTION) computes and estimation EST\n% of the background (aka. baseline) in a spectroscopic signal Y with wavelength N.\n% The background is estimated by a polynomial with order ORDER using a cost-function\n% FUNCTION with parameter THRESHOLD. FUNCTION can have the four following values:\n% 'sh' - symmetric Huber function : f(x) = { x^2 if abs(x) < THRESHOLD,\n% { 2*THRESHOLD*abs(x)-THRESHOLD^2 otherwise.\n% 'ah' - asymmetric Huber function : f(x) = { x^2 if x < THRESHOLD,\n% { 2*THRESHOLD*x-THRESHOLD^2 otherwise.\n% 'stq' - symmetric truncated quadratic : f(x) = { x^2 if abs(x) < THRESHOLD,\n% { THRESHOLD^2 otherwise.\n% 'atq' - asymmetric truncated quadratic : f(x) = { x^2 if x < THRESHOLD,\n% { THRESHOLD^2 otherwise.\n% COEFS returns the ORDER+1 vector of the estimated polynomial coefficients\n% (computed with n sorted and bounded in [-1,1] and y bounded in [0,1]).\n% IT returns the number of iterations.\n%\n% [EST,COEFS,IT] = BACKCOR(N,Y) does the same, but run a graphical user interface\n% to help setting ORDER, THRESHOLD and FCT.\n%\n% For more informations, see:\n% - V. Mazet, C. Carteret, D. Brie, J. Idier, B. Humbert. Chemom. Intell. Lab. Syst. 76 (2), 2005.\n% - V. Mazet, D. Brie, J. Idier. Proceedings of EUSIPCO, pp. 305-308, 2004.\n% - V. Mazet. PhD Thesis, University Henri Poincaré Nancy 1, 2005.\n% \n% 22-June-2004, Revised 19-June-2006, Revised 30-April-2010,\n% Revised 12-November-2012 (thanks E.H.M. Ferreira!)\n% Comments and questions to: vincent.mazet@unistra.fr.\n\n\n% Check arguments\nif nargin < 2, error('backcor:NotEnoughInputArguments','Not enough input arguments'); end;\nif nargin < 5, [z,a,it,ord,s,fct] = backcorgui(n,y); return; end; % delete this line if you do not need GUI\nif ~isequal(fct,'sh') && ~isequal(fct,'ah') && ~isequal(fct,'stq') && ~isequal(fct,'atq'),\n error('backcor:UnknownFunction','Unknown function.');\nend;\n\n% Rescaling\nN = length(n);\n[n,i] = sort(n);\ny = y(i);\nmaxy = max(y);\ndely = (maxy-min(y))/2;\nn = 2 * (n(:)-n(N)) / (n(N)-n(1)) + 1;\ny = (y(:)-maxy)/dely + 1;\n\n% Vandermonde matrix\np = 0:ord;\nT = repmat(n,1,ord+1) .^ repmat(p,N,1);\nTinv = pinv(T'*T) * T';\n\n% Initialisation (least-squares estimation)\na = Tinv*y;\nz = T*a;\n\n% Other variables\nalpha = 0.99 * 1/2; % Scale parameter alpha\nit = 0; % Iteration number\nzp = ones(N,1); % Previous estimation\n\n% LEGEND\nwhile sum((z-zp).^2)/sum(zp.^2) > 1e-9,\n \n it = it + 1; % Iteration number\n zp = z; % Previous estimation\n res = y - z; % Residual\n \n % Estimate d\n if isequal(fct,'sh'),\n d = (res*(2*alpha-1)) .* (abs(res)=s);\n elseif isequal(fct,'ah'),\n d = (res*(2*alpha-1)) .* (res=s);\n elseif isequal(fct,'stq'),\n d = (res*(2*alpha-1)) .* (abs(res)=s);\n elseif isequal(fct,'atq'),\n d = (res*(2*alpha-1)) .* (res=s);\n end;\n \n % Estimate z\n a = Tinv * (y+d); % Polynomial coefficients a\n z = T*a; % Polynomial\n \nend;\n\n% Rescaling\n[~,j] = sort(i);\nz = (z(j)-1)*dely + maxy;\n\n a(1) = a(1)-1;\n a = a*dely;% + maxy;\n\nend\n\n% delete lines below if you do not need GUI\n\nfunction [z,a,it,ord,s,fct] = backcorgui(n,y)\n\n% BACKCORGUI Graphical User Interface for background estimation.\n\n% Initialization\nz = [];\na = [];\nit = [];\nord = [];\ns = [];\nfct = [];\n\norder = 4;\nthreshold = 0.01;\ncostfunction = 'atq';\n\n% Main window\nhwin = figure('Visible','off','Position',[0 0 750 400],'NumberTitle','off','Name','Background Correction',...\n 'MenuBar','none','Toolbar','figure','Resize','on','ResizeFcn',{@WinResizeFcn});\nbgclr = get(hwin,'Color');\n\n% Axes\nhaxes = axes('Units','pixels');\n\n% Buttons OK & Cancel\nhok = uicontrol('Style','pushbutton','String','OK','Position',[600,40,80,25],'Callback',{@OKFcn},'BackgroundColor',bgclr); \nhcancel = uicontrol('Style','pushbutton','String','Cancel','Position',[510,40,80,25],'Callback',{@CancelFcn},'BackgroundColor',bgclr); \n\n% Cost functions menu\nhfctlbl = uicontrol('Style','text','String','Cost function:','HorizontalAlignment','left','BackgroundColor',bgclr);\nhfct = uicontrol('Style','popupmenu','Value',4,'BackgroundColor','white','Callback',{@CostFunctionFcn},...\n 'String',{'Symmetric Huber function','Asymmetric Huber function','Symmetric truncated quadratic','Asymmetric truncated quadratic'});\n\n% Threshold text\nhthresholdlbl = uicontrol('Style','text','String','Threshold:','HorizontalAlignment','left','BackgroundColor',bgclr);\nhthreshold = uicontrol('Style','edit','String',num2str(threshold),'BackgroundColor','white','Callback',{@ThresholdFcn});\n\n% Order slider\nhorderlbl = uicontrol('Style','text','String','Polynomial order:','HorizontalAlignment','left','BackgroundColor',bgclr);\nhorder = uicontrol('Style','slider','SliderStep',[0.5 0.5],'Min',0,'Max',10,'Value',order,'SliderStep',[0.1 0.1],'Callback',{@OrderFcn});\nhorderval = uicontrol('Style','text','String',num2str(order),'BackgroundColor',bgclr);\n\n% Move the GUI to the center of the screen\nmovegui(hwin,'center');\n\n% Plot a first estimation\n[ztmp,atmp,ittmp,order,threshold,costfunction] = compute(n,y,order,threshold,costfunction);\n\n% Make the GUI visible\nset(hwin,'Visible','on');\n\n% Callback functions\n\n function CancelFcn(source,eventdata)\n % Just close the window\n uiresume(gcbf);\n close(hwin);\n end\n \n function OKFcn(source,eventdata)\n % Return the current estimation and close the window\n z = ztmp;\n a = atmp;\n it = ittmp;\n ord = order;\n s = threshold;\n fct = costfunction;\n uiresume(gcbf);\n close(hwin);\n end\n\n function CostFunctionFcn(source,eventdata)\n % Change cost function\n cf = get(hfct,'Value');\n if cf == 1,\n costfunction = 'sh';\n elseif cf == 2,\n costfunction = 'ah';\n elseif cf == 3,\n costfunction = 'stq';\n elseif cf == 4,\n costfunction = 'atq';\n end\n [ztmp,atmp,ittmp,ord,s,fct] = compute(n,y,order,threshold,costfunction);\n end\n\n function OrderFcn(source,eventdata)\n % Change order\n order = get(horder,'Value');\n set(horderval,'String',num2str(order));\n [ztmp,atmp,ittmp,ord,s,fct] = compute(n,y,order,threshold,costfunction);\n end\n\n function ThresholdFcn(source,eventdata)\n % Change threshold\n threshold = get(hthreshold,'String');\n threshold = str2double(threshold);\n [ztmp,atmp,ittmp,ord,s,fct] = compute(n,y,order,threshold,costfunction);\n end\n \n function [ztmp,atmp,ittmp,order,threshold,costfunction] = compute(n,y,order,threshold,costfunction)\n % Compute and plot an estimation (need to sort the data)\n [ztmp,atmp,ittmp,order,threshold,costfunction] = backcor(n,y,order,threshold,costfunction);\n [~,i] = sort(n);\n plot(n(i),y(i),'b-',n(i),ztmp(i),'r-');\n end\n\n function WinResizeFcn(source,eventdata)\n % Resize the window\n pos = get(hwin,'Position');\n w = pos(3);\n h = pos(4);\n if w>400 && h>100,\n set(haxes,'Position',[40,40,w-320,h-70]);\n end;\n set(hok,'Position',[w-90,30,80,25]);\n set(hcancel,'Position',[w-180,30,80,25]);\n set(hfctlbl,'Position',[w-240,h-30,220,20]);\n set(hfct,'Position',[w-240,h-50,220,25]);\n set(hthresholdlbl,'Position',[w-240,h-80,220,20]);\n set(hthreshold,'Position',[w-240,h-100,220,20]);\n set(horderlbl,'Position',[w-240,h-130,220,20]);\n set(horder,'Position',[w-210,h-150,190,20]);\n set(horderval,'Position',[w-240,h-150,20,20]);\n end\n\nuiwait(gcf);\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/27429-background-correction/backcor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6270698229020178}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Example code for estimating the HRF using the Inverse-Logit Model, a\n% Finte Impluse Response Model and the Canonical HRF with 2 derivatives.\n% Also the code illustrates our code for detecting model misspecification. \n%\n% By Martin Lindquist and Tor Wager\n% Created 10/02/09\n% Last edited 05/20/13\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Load time course\n%\n\nmypath = which('ilogit');\nif isempty(mypath), error('Cannot find directory with ilogit.m and other functions. Not on path?'); end\n[mydir] = fileparts(mypath)\n\nload(fullfile(mydir,'timecourse'))\n\ntc = (tc- mean(tc))/std(tc);\nlen = length(tc);\n\n\n%% Or: create your own\n[xBF] = spm_get_bf(struct('dt', .5, 'name', 'hrf (with time and dispersion derivatives)', 'length', 32));\nclear Xtrue\nfor i = 1:1, xx = conv(xBF.bf(:,i), [1 1 1 1 1 1 ]');\n Xtrue(:, i) = xx(1:66);\nend\nfor i = 2:3, xx = conv(xBF.bf(:,i), [1 1]');\n Xtrue(:, i) = xx(1:66);\nend\nhrf = Xtrue * [1 .3 .2]';\nxsecs = 0:.5:32;\n\nhrf = [ 0; 0; hrf];\nhrf = hrf(1:length(xsecs));\nhrf = hrf ./ max(hrf);\nfigure; plot(xsecs, hrf, 'k')\n%hrf = hrf(1:4:end); % downsample to TR, if TR is > 0.5\n\n\nR = randperm(640); R = sort(R(1:36));\nRun = zeros(640,1);\nfor i=1:length(R), Run(R(i)) = 1; end;\ntrue_sig = conv(Run, hrf);\ntrue_sig = true_sig(1:640);\n\n% tc_noise = noise_arp(640, [.7 .2]);\n% tc = true_sig + 0.1 * tc_noise;\ntc = true_sig;\n%figure; plot(tc);\n\n\nRunc{1} = Run;\n\n%%\n\ncreate_figure; subplot(3,1,1); han = plot(tc);\ntitle('Sample time course'); drawnow\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Settings\n% \n\nTR = 0.5;\n%T = round(30/TR);\nT = 30;\nt = 1:TR:T; % samples at which to get Logit HRF Estimate\nFWHM = 4; % FWHM for residual scan\npval = 0.01;\ndf = 600;\nalpha = 0.001;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Create stick function (sample event onsets)\n% Variable R contains onset times\n% Variable Run contains stick (a.k.a. delta or indicator) function\n\n% R = [3, 21, 56, 65, 109, 126, 163, 171, 216, 232, 269, 282, 323, 341, 376, 385, 429, 446, 483, 491, 536, 552, 589, 602];\n% Run = zeros(640,1);\n% for i=1:length(R), Run(R(i)) = 1; end;\n% \n\ntry\n hold on;\n hh = plot_onsets(R,'k',-3,1, 1);\n drawnow\ncatch\n disp('Couldn''t find function to add onset sticks to plot. Skipping.')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fit HRF using IL-function\n\n% Choose mode (deterministic/stochastic)\n\nmode = 0; % 0 - deterministic aproach \n % 1 - simulated annealing approach\n % Please note that when using simulated annealing approach you\n % may need to perform some tuning before use.\n\n[h1, fit1, e1, param] = Fit_Logit2(tc,TR,Runc,T,mode);\n[pv sres sres_ns1] = ResidScan(e1, FWHM);\n[PowLoss1] = PowerLoss(e1, fit1, (len-7) , tc, TR, Runc, alpha);\n\nhold on; han(2) = plot(fit1,'r');\n\ndisp('Summary: IL_function');\n\ndisp('Amplitude:'); disp(param(1));\ndisp('Time-to-peak:'); disp(param(2)*TR);\ndisp('Width:'); disp(param(3)*TR);\n\ndisp('MSE:'); disp((1/(len-1)*sum(e1.^2)));\ndisp('Mis-modeling:'); disp(pv);\ndisp('Power Loss:'); disp(PowLoss1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fit HRF using FIR-model\n\n% Choose mode (FIR/sFIR)\n\nmode = 1; % 0 - FIR \n % 1 - smooth FIR\n \n[h2, fit2, e2, param] = Fit_sFIR(tc,TR,Runc,T,mode);\n[pv sres sres_ns2] = ResidScan(e2, FWHM);\n[PowLoss2] = PowerLoss(e2, fit2, (len-T) , tc, TR, Runc, alpha);\n\nhold on; han(3) = plot(fit2,'g');\n\ndisp('Summary: FIR');\n\ndisp('Amplitude'); disp(param(1));\ndisp('Time-to-peak'); disp(param(2)*TR);\ndisp('Width'); disp(param(3)*TR);\n\ndisp('MSE:'); disp((1/(len-1)*sum(e2.^2)));\ndisp('Mis-modeling'); disp(pv);\ndisp('Power Loss:'); disp(PowLoss2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fit HRF using Canonical HRF + 2 derivatives\n\np=1;\n \n[h3, fit3, e3, param, info] = Fit_Canonical_HRF(tc,TR,Runc,30,p);\n[pv sres sres_ns3] = ResidScan(e3, FWHM);\n[PowLoss3] = PowerLoss(e3, fit3, (len-p) , tc, TR, Runc, alpha);\n\nhold on; han(4) = plot(fit3,'m');\n\nlegend(han,{'Data' 'IL' 'sFIR' 'DD'})\n\n\ndisp('Summary: Canonical + 2 derivatives');\n\ndisp('Amplitude'); disp(param(1));\ndisp('Time-to-peak'); disp(param(2)*TR);\ndisp('Width'); disp(param(3)*TR);\n\ndisp('MSE:'); disp((1/(len-1)*sum(e3.^2)));\ndisp('Mis-modeling'); disp(pv);\ndisp('Power Loss:'); disp(PowLoss3);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%figure; \n%%\n\nsubplot(3,2,5); hold on;\nplot(xsecs, hrf, 'k')\nxsecs1 = xsecs(1:length(h1));\nhan2 = plot(xsecs1, h1,'r');\nxsecs2 = xsecs(1:length(h2));\nhan2(2) = plot(xsecs2, h2,'g');\nxsecs3 = xsecs(1:length(h3));\nhan2(3) = plot(xsecs3, h3,'m');\nlegend(han2,{'IL' 'sFIR' 'DD'})\ntitle('Estimated HRF');\n\n\nsubplot(3,1,2); hold on;\nhh = plot_onsets(R,'k',-3,1);\ndrawnow\n\nhan3 = plot(sres_ns1,'r');\nhold on; han3(2) = plot(sres_ns2,'g');\nhold on; han3(3) = plot(sres_ns3,'m');\nhold on; plot((1:len),zeros(len,1),'--k');\nlegend(han3,{'IL' 'sFIR' 'DD'})\ntitle('Mis-modeling (time course)');\n\n\nsubplot(3,2,6); hold on;\n\n[s1] = Fit_sFIR(sres_ns1,TR,Runc,T,0);\n[s2] = Fit_sFIR(sres_ns2,TR,Runc,T,0);\n[s3] = Fit_sFIR(sres_ns3,TR,Runc,T,0);\n\nhan4 = plot(s1(1:T),'r');\nhold on; han4(2) = plot(s2(1:T),'g');\nhold on; han4(3) = plot(s3(1:T),'m');\nhold on; plot((1:T),zeros(T,1),'--k');\nlegend(han4,{'IL' 'sFIR' 'DD'})\ntitle('Mis-modeling (HRF)');\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/HRF_Est_Toolbox2/Example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6270698106451019}} {"text": "function q = qinv(p)\n\n% QINV quaternion inverse\n%\n% Q = QINV(P) returns a quaternion Q which is the quaternion inverse of\n% quaternion P.\n% - P is a quaternion. It is a 4-vector or a 4*N array (column i\n% represents quaternion i) where N is the number of quaternions.\n% - Q is the quaternion inverse of quaternion P. It is a 4*N array.\n\nsp = size(p);\nif sp == [1 4]\n p = p.'; \n sp = size(p); \nend\n\n% wrong format\nif sp(1) ~= 4\n error('DualQuaternion:Qinv:wrongsize',...\n '%d rows in the P array. It should be 4.',sp(1));\nend\n\nnormp = qnorm(p);\nq = qconj(p)./repmat(normp.^2,4,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/43393-dual-quaternion-symbolic-toolbox/Dual quaternion symbolic toolbox/private/qinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6269792030835188}} {"text": "function res = qdist(a,b)\n%QDIST Implements q(a,b) metrical distance\n% Name qdist is used to avoid ambiguities with variable q\n% This functions for non-interval input only for completeness\n%\n% res = qdist(a,b)\n%\n% for real input abs(a-b)\n% for complex input qdist(real(a),real(b)) + qdist(imag(a),imag(b))\n%\n\n% written 03/23/00 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n%\n\n if isreal(a) & isreal(b)\n res = abs(a-b);\n else\n res = abs(real(a)-real(b)) + abs(imag(a)-imag(b));\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/intval/qdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6269792004934326}} {"text": "function res = computeDirectionWeights3d13(varargin)\n%COMPUTEDIRECTIONWEIGHTS3D13 Direction weights for 13 directions in 3D\n%\n% C = computeDirectionWeights3d13\n% Returns an array of 13-by-1 values, corresponding to directions:\n% C(1) = [+1 0 0]\n% C(2) = [ 0 +1 0]\n% C(3) = [ 0 0 +1]\n% C(4) = [+1 +1 0]\n% C(5) = [-1 +1 0]\n% C(6) = [+1 0 +1]\n% C(7) = [-1 0 +1]\n% C(8) = [ 0 +1 +1]\n% C(9) = [ 0 -1 +1]\n% C(10) = [+1 +1 +1]\n% C(11) = [-1 +1 +1]\n% C(12) = [+1 -1 +1]\n% C(13) = [-1 -1 +1]\n% The sum of the weights in C equals 1.\n% Some values are equal whatever the resolution:\n% C(4)==C(5);\n% C(6)==C(7);\n% C(8)==C(9);\n% C(10)==C(11)==C(12)==C(13);\n%\n% C = computeDirectionWeights3d13(DELTA)\n% With DELTA = [DX DY DZ], specifies the resolution of the grid.\n%\n% Example\n% c = computeDirectionWeights3d13;\n% sum(c)\n% ans =\n% 1.0000\n%\n% c = computeDirectionWeights3d13([2.5 2.5 7.5]);\n% sum(c)\n% ans =\n% 1.0000\n%\n%\n% See also\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-10-18, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\n%% Initializations\n\n% grid resolution\ndelta = [1 1 1];\nif ~isempty(varargin)\n delta = varargin{1};\nend\n\n% If resolution is [1 1 1], return the pre-computed set of weights\nif all(delta == [1 1 1])\n area1 = 0.04577789120476 * 2;\n area2 = 0.03698062787608 * 2;\n area3 = 0.03519563978232 * 2;\n res = [...\n area1; area1; area1; ...\n area2; area2; area2; area2; area2; area2;...\n area3; area3; area3; area3 ];\n return;\nend\n\n% Define points of interest in the 26 discrete directions\n% format is pt[Xpos][Ypos][Zpos], with [X], [Y] or [Z] being one of \n% 'N' (for negative), 'P' (for Positive) or 'Z' (for Zero)\n\n% points below the OXY plane\nptPNN = normalizeVector3d([+1 -1 -1].*delta);\nptPZN = normalizeVector3d([+1 0 -1].*delta);\nptNPN = normalizeVector3d([-1 +1 -1].*delta);\nptZPN = normalizeVector3d([ 0 +1 -1].*delta);\nptPPN = normalizeVector3d([+1 +1 -1].*delta);\n\n% points belonging to the OXY plane\nptPNZ = normalizeVector3d([+1 -1 0].*delta);\nptPZZ = normalizeVector3d([+1 0 0].*delta);\nptNPZ = normalizeVector3d([-1 +1 0].*delta);\nptZPZ = normalizeVector3d([ 0 +1 0].*delta);\nptPPZ = normalizeVector3d([+1 +1 0].*delta);\n\n% points above the OXY plane\nptNNP = normalizeVector3d([-1 -1 +1].*delta);\nptZNP = normalizeVector3d([ 0 -1 +1].*delta);\nptPNP = normalizeVector3d([+1 -1 +1].*delta);\nptNZP = normalizeVector3d([-1 0 +1].*delta);\nptZZP = normalizeVector3d([ 0 0 +1].*delta);\nptPZP = normalizeVector3d([+1 0 +1].*delta);\nptNPP = normalizeVector3d([-1 +1 +1].*delta);\nptZPP = normalizeVector3d([ 0 +1 +1].*delta);\nptPPP = normalizeVector3d([+1 +1 +1].*delta);\n\n\n%% Spherical cap type 1, direction [1 0 0]\n\n% Compute area of voronoi cell for a point on the Ox axis, i.e. a point\n% in the 6-neighborhood of the center.\nrefPoint = ptPZZ;\n\n% neighbours of chosen point, sorted by CCW angle\nneighbors = [ptPNN; ptPNZ; ptPNP; ptPZP; ptPPP; ptPPZ; ptPPN; ptPZN];\n\n% compute area of spherical polygon\narea1 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 1, direction [0 1 0]\n\n% Compute area of voronoi cell for a point on the Oy axis, i.e. a point\n% in the 6-neighborhood of the center.\nrefPoint = ptZPZ;\n\n% neighbours of chosen point, sorted by angle\nneighbors = [ptPPZ; ptPPP; ptZPP; ptNPP; ptNPZ; ptNPN; ptZPN; ptPPN];\n\n% compute area of spherical polygon\narea2 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 1, direction [0 0 1]\n\n% Compute area of voronoi cell for a point on the Oz axis, i.e. a point\n% in the 6-neighborhood of the center.\nrefPoint = ptZZP;\n\n% neighbours of chosen point, sorted by angle\nneighbors = [ptPZP; ptPPP; ptZPP; ptNPP; ptNZP; ptNNP; ptZNP; ptPNP];\n\n% compute area of spherical polygon\narea3 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 2, direction [1 1 0]\n\n% Compute area of voronoi cell for a point on the Oxy plane, i.e. a point\n% in the 18-neighborhood\nrefPoint = ptPPZ;\n\n% neighbours of chosen point, sorted by angle\nneighbors = [ptPZZ; ptPPP; ptZPZ; ptPPN];\n\n% compute area of spherical polygon\narea4 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 2, direction [1 0 1]\n\n% Compute area of voronoi cell for a point on the Oxz plane, i.e. a point\n% in the 18-neighborhood\nrefPoint = ptPZP;\n% neighbours of chosen point, sorted by angle\nneighbors = [ptPZZ; ptPPP; ptZZP; ptPNP];\n\n% compute area of spherical polygon\narea5 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 2, direction [0 1 1]\n\n% Compute area of voronoi cell for a point on the Oxy plane, i.e. a point\n% in the 18-neighborhood\nrefPoint = ptZPP;\n% neighbours of chosen point, sorted by angle\nneighbors = [ptZPZ; ptNPP; ptZZP; ptPPP];\n\n% compute area of spherical polygon\narea6 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Spherical cap type 3 (all cubic diagonals)\n\n% Compute area of voronoi cell for a point on the Oxyz diagonal, i.e. a\n% point in the 26 neighborhood only\nrefPoint = ptPPP;\n% neighbours of chosen point, sorted by angle\nneighbors = [ptPZP; ptZZP; ptZPP; ptZPZ; ptPPZ; ptPZZ];\n\n% compute area of spherical polygon\narea7 = sphericalVoronoiDomainArea(refPoint, neighbors);\n\n\n%% Concatenate results\n\n% return computed areas, formatted as fraction of sphere surface\nres = [...\n area1 area2 area3 ...\n area4 area4 area5 area5 area6 area6...\n area7 area7 area7 area7...\n ]/(2*pi);\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imMinkowski/private/computeDirectionWeights3d13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6269791866835859}} {"text": "function wavelet_test07 ( )\n\n%*****************************************************************************80\n%\n%% WAVELET_TEST07 tests DAUB14_TRANSFORM and DAUB14_TRANSFORM_INVERSE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 July 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'WAVELET_TEST07\\n' );\n fprintf ( 1, ' DAUB14_TRANSFORM computes the DAUB14 transform of a vector.\\n' );\n fprintf ( 1, ' DAUB14_TRANSFORM_INVERSE inverts it.\\n' );\n%\n% Random data.\n%\n n = 16;\n seed = 123456789;\n [ u, seed ] = r8vec_uniform_01 ( n, seed );\n\n v = daub14_transform ( n, u );\n\n w = daub14_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D14(U)(i) D14inv(D14(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Constant signal.\n%\n n = 8;\n u(1:n) = 1.0;\n\n v = daub14_transform ( n, u );\n\n w = daub14_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D14(U)(i) D14inv(D14(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Linear signal.\n%\n n = 16;\n a_first = 1.0;\n a_last = n;\n u = linspace ( a_first, a_last, n );\n\n v = daub14_transform ( n, u );\n\n w = daub14_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D14(U)(i) D14inv(D14(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n%\n% Quadratic data.\n%\n n = 8;\n u(1) = 25.0;\n u(2) = 16.0;\n u(3) = 9.0;\n u(4) = 4.0;\n u(5) = 1.0;\n u(6) = 0.0;\n u(7) = 1.0;\n u(8) = 4.0;\n\n v = daub14_transform ( n, u );\n\n w = daub14_transform_inverse ( n, v );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' i U(i) D14(U)(i) D14inv(D14(U))(i)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %2d %10.4f %10.4f %10.4f\\n', i, u(i), v(i), w(i) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wavelet/wavelet_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6269742945536414}} {"text": "function [Y] = Rotation_ForceMoment_FromTireFixed(X,A_K_F,A_Rfl_F,A_Rfr_F,A_down_up)\n%% Input parameters:\n% A_K_F [---] Rotation Matrix from RearAxle Fixed Coordinate System to VehicleFixed Coordinate System\n% A_Rfl_F [---] Rotation Matrix from RearAxle Fixed Coordinate System to WheelFixed Coordinate System FrontLeft\n% A_Rfr_F [---] Rotation Matrix from RearAxle Fixed Coordinate System to WheelFixed Coordinate System FrontRight\n% A_down_up [...] Orientation Change Matrix between z-up Orientation and z-down Orientation\n% X [---] Original Input Vectors [x1 x2 x3 x4] [3x4]\n% Output parameters:\n% Y [---] Transformed Output Vectors [y1 y2 y3 y4] [3x4]\n\n%% Output of transformed vectors\n% Quarter Vehicle Model along Vehicle Fixed z-Axis: Rotation from TireFixed Coordinate System into VehicleFixed Coordinate System\n% Y=[(A_K_F*transpose(A_Rfl_F)*A_down_up*X(:,1)) (A_K_F*transpose(A_Rfr_F)*A_down_up*X(:,2)) (A_K_F*A_down_up*X(:,3)) (A_K_F*A_down_up*X(:,4))];\n\n% Quarter Vehicle Model along Rear Axle Fixed z-Axis: Rotation from TireFixed Coordinate System into RearAxleFixed Coordinate System\nY=[(transpose(A_Rfl_F)*A_down_up*X(:,1)) (transpose(A_Rfr_F)*A_down_up*X(:,2)) (A_down_up*X(:,3)) (A_down_up*X(:,4))];\n\n% Quarter Vehicle Model according MATLAB-Documentation\n% Y=[(transpose(A_Rfl_F)*A_down_up*X(:,1)) (transpose(A_Rfr_F)*A_down_up*X(:,2)) (A_down_up*X(:,3)) (A_down_up*X(:,4))];\n\nend\n\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/Rotation_ForceMoment_FromTireFixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.6269304960790664}} {"text": "function hermite_cubic_test12 ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_CUBIC_TEST12 tests HERMITE_CUBIC_LAGRANGE_INTEGRAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_CUBIC_TEST12:\\n' );\n fprintf ( 1, ' HERMITE_CUBIC_LAGRANGE_INTEGRAL returns the integrals\\n' );\n fprintf ( 1, ' of the four Lagrange basis functions associated \\n' );\n fprintf ( 1, ' with F1, D1, F2 and D2 such that\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' P(X) = F1 * LF1(X) + D1 * LD1(X)\\n' );\n fprintf ( 1, ' + F2 * LF2(X) + D2 * LD2(X).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The Lagrange basis function integrals:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X1 X2 LF1 LD1 LF2 LD2\\n' );\n fprintf ( 1, '\\n' );\n\n x2 = 1.0;\n for x1 = -6 : +2\n q = hermite_cubic_lagrange_integral ( x1, x2 );\n fprintf ( 1, ' %10.4f %10.4f %10.4f %10.4f %10.4f %10.4f\\n', ...\n x1, x2, q(1:4) )\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_cubic/hermite_cubic_test12.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6269238417792273}} {"text": "function perm=field2d(Nx,Ny,k_avg,V_dp,clx,cly)\n% All credits go to http://www.mysimlabs.com/surface_generation.html\n% modified by Ali A. Eftekhari\n% See the license file\n% Note: a very very simple approach! Use it with utmost care :-)\nLx=1.0; % domain length\nx=linspace(-Lx/2.0,Lx/2.0,Nx);\ny=linspace(-Lx/2.0,Lx/2.0,Ny);\n[X,Y]=ndgrid(x,y);\ns=-log(1-V_dp); % standard deviation\nmu=log(k_avg)-s*s/2.0; % mean for a log-random field\nZ=s*randn(Nx,Ny); % normal distribution\nF = exp(-(X.^2/(clx*clx/2.0)+Y.^2/(cly*cly/2.0)));\n% Gaussian filter\nf =2.0/sqrt(pi)*Lx/sqrt(Nx*Ny)/sqrt(clx)/sqrt(cly).*ifft2(fft2(Z).*fft2(F)); % another filter\nperm=exp(mu+real(f)); % perm field\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/FieldGeology/field2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6269085357816737}} {"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% Calibrating kl, ku, mu and nu for a sabr model for Kienitz extrapolation\n% the prices are calculated from known sabr parameters\n\nf = 0.03; t =1; % forward time\na = 0.25; b = 0.5; r = -.5; n = 0.2; % sabr parameters\n\nk = 0.0001:0.0001:1; % strike range\n\ncall = sprice(a, b, r, n, f, k, t,1); % call prices (standard sabr)\nput = sprice(a, b, r, n, f, k, t,0); % put prices (standard sabr)\nput(1) = 0;\ncall(1) = f; % assures forward is matched\n\nNparam = 4; % number of calibrated params\n\n% objective function\nof = @(x) of_sabr(a, b, r, n, f, k, t, x(3), x(4), x(1), x(2), call, put);\n\nx0 = [.25*f; 25.5*f; 1.8; 2.4]; % starting values % \n\nA = zeros(Nparam,Nparam); bc= zeros(Nparam,1);\nAeq = A; beq = bc;\nlb = [.25*f; f; 1; 3]; % lower bound\nub = [f; 30*f; 1.5; 5]; % upper bound\ny = fmincon(of,x0,A,bc,Aeq,beq,lb,ub); % optimization\n\n% verification of results\nxval = 0:0.001:.25; % x-values\n[cl, bl, al, cu, bu, au] = psabr_param_3(a, b, r, n, f, t,y(3),y(4),y(1),y(2));\nyval = psabr_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n y(3), cl, bl,al, y(4), cu,bu,au);% y-values calculated\n\nplot(xval,yval); % plot the results\nFactor = 1000000; % used for plotting\n\nyval_call = sprice_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n y(3), cl, bl,al, y(4), cu,bu,au, 1); % SABR Call prices\nfigure; hold on; \n plot(xval,Factor*yval_call,'r'); \n plot(k,Factor*call,'g'); \nhold off;\n\nyval_put = sprice_5(a, b, r, n, f, xval, t, y(1), y(2), ...\n y(3), cl, bl,al, y(4), cu,bu,au, 0); % SABR Put prices\nfigure; hold on; \n plot(xval,Factor*yval_put,'r'); \n plot(k,Factor*put,'g'); \nhold off;\n\nfval = sprice_5(a, b, r, n, f, 0, t, y(1), y(2), ...\n y(3), cl, bl,al, y(4), cu,bu,au, 1); % calculate forward value\ny % calibrated values\nf - fval % display difference to forward\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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/Cal_sabr_dens_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6268639494865277}} {"text": "% corrcoef_cell() - compute pairwise correlations using arrays and \n% cell array inputs.\n%\n% Usage:\n% >> c = corrcoef_cell( data );\n% >> c = corrcoef_cell( data );\n%\n% Inputs:\n% data - [cell array] data consisting of PAIRED arrays to be compared. \n% The last dimension of embeded data arrays is used to compute \n% correlation (see examples).\n% Outputs:\n% c - Correlation values. Same size as data without the last dimension.\n%\n% Note: the main advantage over the corrcoef Matlab function is the\n% capacity to compute millions of pairwise correlations per second.\n%\n% Example:\n% a = { rand(1,10) rand(1,10) };\n% c1 = corrcoef_cell(a);\n% c2 = corrcoef(a{1}, a{2});\n% % in this case, c1 is equal to c2(2)\n%\n% a = { rand(200,300,100) rand(200,300,100) };\n% c = corrcoef_cell(a);\n% % the call above would require 200 x 300 calls to the corrcoef function\n% % and be about 1000 times slower\n%\n% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010\n\n% Copyright (C) Arnaud Delorme\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 c = corrcoef_cell(a,b);\n\nif nargin < 1\n help corrcoef_cell;\n return;\nend;\n\nif nargin < 2\n b = a{2};\n a = a{1};\nend;\n\nnd = myndims(a);\nif nd == 1\n aa = a-mean(a);\n bb = b-mean(b);\n cv = aa'*bb/(10-1);\n cva = aa'*aa/(10-1);\n cvb = bb'*bb/(10-1);\n\n c = cv/sqrt(cva*cvb);\nelseif nd == 2\n aa = a-repmat(mean(a,2),[1 size(a,2)]);\n bb = b-repmat(mean(b,2),[1 size(a,2)]);\n cv = sum(aa.*bb,2);\n cva = sum(aa.*aa,2);\n cvb = sum(bb.*bb,2);\n\n c = cv./sqrt(cva.*cvb);\nelseif nd == 3\n aa = a-repmat(mean(a,3),[1 1 size(a,3)]);\n bb = b-repmat(mean(b,3),[1 1 size(a,3)]);\n cv = sum(aa.*bb,3);\n cva = sum(aa.*aa,3);\n cvb = sum(bb.*bb,3);\n\n c = cv./sqrt(cva.*cvb);\nelseif nd == 4\n aa = a-repmat(mean(a,4),[1 1 1 size(a,4)]);\n bb = b-repmat(mean(b,4),[1 1 1 size(a,4)]);\n cv = sum(aa.*bb,4);\n cva = sum(aa.*aa,4);\n cvb = sum(bb.*bb,4);\n\n c = cv./sqrt(cva.*cvb);\nend;\n\nfunction val = myndims(a)\n if ndims(a) > 2\n val = ndims(a);\n else\n if size(a,1) == 1,\n val = 2;\n elseif size(a,2) == 1,\n val = 1;\n else\n val = 2;\n end;\n end; \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/statistics/corrcoef_cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6268007744805225}} {"text": "function [Hx,Hy,Ez,time] = Maxwell2D(Hx, Hy, Ez, FinalTime)\n\n% function [Hx,Hy,Ez] = Maxwell2D(Hx, Hy, Ez, FinalTime)\n% Purpose :Integrate TM-mode Maxwell's until FinalTime starting with initial conditions Hx,Hy,Ez\n\nGlobals2D;\ntime = 0;\n\n% Runge-Kutta residual storage \nresHx = zeros(Np,K); resHy = zeros(Np,K); resEz = zeros(Np,K); \n\n% compute time step size\nrLGL = JacobiGQ(0,0,N); rmin = abs(rLGL(1)-rLGL(2));\ndtscale = dtscale2D; dt = min(dtscale)*rmin*2/3\n\n% outer time step loop \nwhile (timeFinalTime), dt = FinalTime-time; end\n\n for INTRK = 1:5 \n % compute right hand side of TM-mode Maxwell's equations\n [rhsHx, rhsHy, rhsEz] = MaxwellRHS2D(Hx,Hy,Ez);\n\n % initiate and increment Runge-Kutta residuals\n resHx = rk4a(INTRK)*resHx + dt*rhsHx; \n resHy = rk4a(INTRK)*resHy + dt*rhsHy; \n resEz = rk4a(INTRK)*resEz + dt*rhsEz; \n \n % update fields\n Hx = Hx+rk4b(INTRK)*resHx; Hy = Hy+rk4b(INTRK)*resHy; Ez = Ez+rk4b(INTRK)*resEz; \n end;\n % Increment time\n time = time+dt;\nend\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/Maxwell2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6268007571109283}} {"text": "function [inc]=look2inc(la,height,lat)\n%LOOK2INC look angle to incidence angle\n%\n% [INCIDENCE]=LOOK2INC(LOOK_ANGLE,HEIGHT,LATITUDE)\n%\n% LOOK_ANGLE = Look angle (radians) (can be vector or matrix)\n% HEIGHT = Height of satellite (m)\n% LATITUDE = mean latitude of ground (degrees)\n%\n% Copyright (C) 2015 Bekaert David - University of Leeds\n% Email: eedpsb@leeds.ac.uk or davidbekaert.com\n% With permission from Andy Hooper\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 along\n% with this program; if not, write to the Free Software Foundation, Inc.,\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% by Andrew Hooper, 2010\n\nif nargin<3\n lat=40\nend\n\nlat1=lat*pi/180;\n\nWGS84_A=6378137.0; % semimajor axis wgs84\nWGS84_B=6356752.314; % semiminor axis wgs84\nRe=WGS84_A*WGS84_B./sqrt(WGS84_A^2*sin(lat1).^2+WGS84_B^2*cos(lat1).^2);\n\na=Re+height; % Earth centre to satellite\ninc=la;\n\n[R] = fminsearch(@(p) (a^2+p^2-2*a*p*cos(mean(la(:)))-Re^2)^2,[600])\nfor i=1:length(la(:))\n R = fminsearch(@(p) (a^2+p^2-2*a*p*cos(la(i))-Re^2)^2,R);\n inc(i)=pi-acos((Re^2+R^2-a^2)/2/Re/R);\nend\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/look2inc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6267359116770619}} {"text": "function varths = Get_VarthsPSI_swing(zetaj,ntilj,PSIdj,PSIdjm1)\n%UNTITLED2 Summary of this function goes here\n% Detailed explanation goes here\n\n\nzetaj2 = zetaj^2; zetaj3 = zetaj*zetaj; zetaj4 = zetaj*zetaj3;\n\nvarths = zeros(1,4);\ngamms = zeros(1,3);\n\n\ngamms(1) = (1 - zetaj4)/8 + zetaj3/3 - zetaj2/4;\ngamms(2) = 5/12 + zetaj4/4 - zetaj3/3 - zetaj2/2 + zetaj;\ngamms(3) = 1/12 - (1 + zetaj4)/8 + zetaj2/4;\n\nvarths(3) = PSIdjm1(ntilj(1)-1)*gamms(1) + PSIdjm1(ntilj(1))*gamms(2) + PSIdjm1(ntilj(1)+1)*gamms(3);\n\ngamms(1) = 1/12 - gamms(1);\ngamms(2) = 5/6 - gamms(2);\ngamms(3) = 1/12 - gamms(3);\n\nvarths(1) = PSIdj(ntilj(1)-1)*gamms(1) + PSIdj(ntilj(1))*gamms(2) + PSIdj(ntilj(1)+1)*gamms(3);\n\n%%%----------------------\n\ngamms(1) = zetaj4/8 - zetaj3/2 + zetaj2/2;\ngamms(2) = -zetaj4/4 + 2*zetaj3/3;\ngamms(3) = zetaj4/8 - zetaj3/6;\n\nvarths(4) = PSIdjm1(ntilj(1))*gamms(1) + PSIdjm1(ntilj(1)+1)*gamms(2) + PSIdjm1(ntilj(1)+2)*gamms(3);\n\ngamms(1) = 1/12 - gamms(1);\ngamms(2) = 5/6 - gamms(2);\ngamms(3) = 1/12 - gamms(3);\n\nvarths(2) = PSIdj(ntilj(1))*gamms(1) + PSIdj(ntilj(1)+1)*gamms(2) + PSIdj(ntilj(1)+2)*gamms(3);\n\nend\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/PROJ/LEVY/Swing_Options/coeff_funcs/Get_VarthsPSI_swing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6267358983329072}} {"text": "% Recursive Least-Squares Algorithm with exponential weighting\n%\n% From S. Haykin, \"Adaptive Filtering Theory (3rd Ed.)\", Prentice Hall,\n% Chapter 13.\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef rls < linear_filter\n \n properties (GetAccess = 'public', SetAccess = 'private')\n lambda = .99; % forgetting factor\n c = 1E-4; % regularization\n end\n \n properties (GetAccess = 'public', SetAccess = 'private')\n P = []; % inverse autocorrelation matrix\n w = []; % filter coefficients\n end\n \n methods\n \n function obj = rls(parameters) % constructor\n if (nargin > 0) % copy valid parameters\n for fn = fieldnames(parameters)'\n if ismember(fn,fieldnames(obj))\n obj.(fn{1}) = parameters.(fn{1});\n end\n end\n end\n end\n \n function y_est = evaluate(obj,x) % evaluate the algorithm\n if numel(obj.w)>0\n y_est = x*obj.w;\n else\n y_est = zeros(size(x,1),1);\n end\n end\n \n function train(obj,x,y) % train the algorithm\n if numel(obj.w)==0 % initialize\n m = length(x);\n obj.w = zeros(m,1);\n obj.P = obj.c\\eye(m);\n end\n \n g = obj.P*x'/(obj.lambda+x*obj.P*x'); % gain vector\n err = y - x*obj.w; % instantaneous error\n obj.w = obj.w + g*err; % update filter coefficients\n obj.P = obj.lambda\\(obj.P - g*x*obj.P); % update inv. autocorr.\n end\n \n end\nend\n", "meta": {"author": "steven2358", "repo": "kafbox", "sha": "694cf94df02a9728a90d7bacda1a8520b425f86f", "save_path": "github-repos/MATLAB/steven2358-kafbox", "path": "github-repos/MATLAB/steven2358-kafbox/kafbox-694cf94df02a9728a90d7bacda1a8520b425f86f/lib/rls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6267312072682463}} {"text": "function [rs,rp]=reflectionCoeffsVec(e1,e2,k,n,u1,u2)\n%%REFLECTIONCOEFFSVEC Reflection coefficients for the reflection of an\n% electromagnetic plane wave from a LOSSLESS medium off a LOSSY\n% medium (or another lossless medium) are computed given a vector\n% in the direction of propagation of the light and a vector\n% normal to the surface. Both media must have real\n% permeabilities. For example, one might approximate the\n% troposphere as lossless while accounting for the loss in sea\n% water. Lossy media have complex permittivities. This function\n% is a different parameterization of reflectionCoeffs.\n%\n%INPUTS: e1 The permittivity (refraction index) of the lossless medium.\n% The incoming ray is traveling through this prior to reflecting\n% off of the surface with permittivity e2. This must be a real\n% quantity (lossless). e1 and e2 can both be either absolute\n% permittivities or relative permittivities. \"Relative\" means\n% that the permittivity of the medium has been divided by the\n% permittivity of free space and is a dimensionless quantity.\n% e2 The permittivity of the medium against which the ray reflects.\n% This can be complex (lossy).\n% k A 3X1 vector in the direction of propagation of the light\n% approaching the surface from which it will reflect.\n% n A 3X1 normal vector to the surface of reflection. It does not\n% matter whether n is pointing up or down from the surface.\n% u1 The permeability of the lossless medium. This must be\n% a real quantity. u1 and u2 can both be either absolute\n% permeabilities or relative permeabilities. If omitted or an\n% empty matrix is passed, a value of 1 is used (the permeability\n% equals that of free space). That is a reasonable approximation\n% for air.\n% u2 The permeability of the lossy medium against which the incoming\n% ray reflects. medium. This must be a real quantity. If omitted\n% or an empty matrix is passed, a value of 1 is used. That is a\n% reasonable approximation for water.\n%\n%OUTPUTS: rs The complex reflection coefficient for s-polarized light, also\n% known as transverse-Electric (TE) polarized light.\n% rp The complex reflection coefficient for p-polarized light, also\n% known as transverse-Magnetic (TM) polarized light and as\n% tangent-plane polarized light.\n%\n%This function uses angBetweenVecs to get the angle between the incoming\n%vector and the normal to the surface (adjusting in case one should have\n%used -n instead of n) and then calls reflectionCoeffs.\n%\n%July 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(u2))\n u2=1;\nend\n\nif(nargin<5||isempty(u1))\n u1=1;\nend\n\nthetai=angBetweenVecs(k,n);\n\nif(thetai>pi/2)\n %If -n should have been used instead of n.\n thetai=pi-thetai;\nend\n[rs,rp]=reflectionCoeffs(e1,e2,thetai,u1,u2);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Physical_Values/reflectionCoeffsVec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6266705907808864}} {"text": "function cc_level_compose_animate ( )\n\n%*****************************************************************************80\n%\n%% CC_LEVEL_COMPOSE_ANIMATE displays the grids that compose one level.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_LEVEL_COMPOSE_ANIMATE:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Display the nested 2D Clenshaw-Curtis grids\\n' );\n fprintf ( 1, ' that compose one level.\\n' );\n\n dim_num = 2;\n \n while ( 1 )\n%\n% Get user input.\n%\n fprintf ( 1, '\\n' );\n level = input ( 'Enter the LEVEL or RETURN to exit;' );\n \n if ( isempty ( level ) )\n break\n end\n%\n% Generate the entire set of points.\n%\n [ grid_num, point_num ] = cc_levels_minmax_size ( dim_num, ...\n level, level );\n \n [ grid_level, grid_order, grid_points ] = cc_levels_minmax ( dim_num, ...\n level, level, grid_num, point_num );\n\n [ dim_num, grid_points_num ] = size ( grid_points );\n%\n% Display the full set of points as filled blue circles.\n%\n clf\n axes_handle = axes;\n handle_new = scatter ( grid_points(1,:), grid_points(2,:), 'b', 'filled' );\n axis square\n grid on\n set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'xticklabel', [] );\n set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'yticklabel', [] );\n axis ( [ -1.1, 1.1, -1.1, 1.1 ] )\n s = sprintf ( 'Entire grid for LEVEL %d', level );\n title ( s );\n fprintf ( 1, 'Press return\\n', level );\n pause\n\n hold off\n%\n% Display the full set of points in gray.\n% Display each contributing grid, one at a time, in red.\n%\n for gridd = 1 : grid_num\n\n order_1d(1:2) = grid_order(1:2,gridd)\n order_nd = prod ( order_1d(1:2) );\n grid_points_new = cc_grid ( dim_num, order_1d, order_nd );\n\n clf\n%\n% We have to name the axes in order to control the grid.\n%\n axes_handle = axes;\n%\n% Plot the OLD points.\n%\n handle_old = scatter ( grid_points(1,:), grid_points(2,:), 'bo' );\n\n hold on\n\n handle_new = scatter ( grid_points_new(1,:), grid_points_new(2,:), ...\n 'r', 'filled' );\n%\n% Force the plotting region to be square, not rectangular.\n%\n axis square\n%\n% Request grid lines.\n%\n grid on\n%\n% Specify the location of the grid lines, and suppress labeling.\n%\n set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'xticklabel', [] );\n set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'yticklabel', [] );\n%\n% Make the plotting region slightly bigger than the data.\n%\n axis ( [ -1.1, 1.1, -1.1, 1.1 ] )\n%\n% Title\n%\n s = sprintf ( '+ %d * %d CC grid', grid_level(1,gridd), grid_level(2,gridd) );\n title ( s );\n\n fprintf ( 1, '+ %d*%d CC grid, Press return\\n', ...\n grid_level(1,gridd), grid_level(2,gridd) );\n pause\n\n hold off\n\n end\n%\n% Display the full set of points as filled blue circles.\n%\n clf\n axes_handle = axes;\n handle_new = scatter ( grid_points(1,:), grid_points(2,:), 'b', 'filled' );\n axis square\n grid on\n set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'xticklabel', [] );\n set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'yticklabel', [] );\n axis ( [ -1.1, 1.1, -1.1, 1.1 ] )\n s = sprintf ( 'Entire grid for LEVEL %d', level );\n title ( s );\n fprintf ( 1, 'Press return\\n', level );\n pause\n\n hold off\n\n fprintf ( 1, 'Press return to CLEAR the grid!\\n' );\n pause\n clf\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_LEVEL_COMPOSE_ANIMATE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cc_display/cc_level_compose_animate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6266705783294084}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D \n% shape modeling and analysis toolkit. \n% It is a software package developed at Shenlab in Center for Neuroimaging, \n% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)\n% It is available to the scientific community as copyright freeware \n% under the terms of the GNU General Public Licence.\n% \n% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University\n% \n% This file is part of SPHARM-MAT.\n% \n% SPHARM-MAT 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% SPHARM-MAT 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 SPHARM-MAT. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ============================================\n% FLD.m\n%\n% Goal: \n% 1. Calculate the optimal FLD projection\n% 2. For two class problem\n%\n% Li Shen \n% 11/13/2002 - create\n\nfunction [FLD_basis, FLD_vals] = FLD(Samples,Labels)\n\nd = size(Samples);\nif (d(2)>d(1)-2)\n disp('---------------------------------');\n disp(sprintf('N=%d points, M=%d dims (IGNORE the last %d dims): a nonsigular Sb requires M<=N-c (c=2)',d,d(2)-d(1)+2));\n disp('---------------------------------');\n Samples = Samples(:,1:d(1)-2);\nend\n\nFLD_basis = [];\n\nSb = get_Sb(Samples,Labels);\nSw = get_Sw(Samples,Labels);\n\n[V,D] = eig(Sb,Sw);\n\n[eigval,ind] = sort(diag(D));\n\nFLD_basis = V(:,ind(end));\n\nFLD_vals = Samples*FLD_basis;\n\nreturn;\n\n%\n% calculate between class scatter matrix Sb\n%\n\nfunction Sb = get_Sb(Samples,Labels)\n\nc1_ind = find(Labels==1); c2_ind = find(Labels==2);\nm = mean(Samples,1); m1_m = mean(Samples(c1_ind,:),1) - m ; m2_m = mean(Samples(c2_ind,:),1) - m;\nSb = length(c1_ind)*(m1_m'*m1_m) + length(c2_ind)*(m2_m'*m2_m);\n\nreturn;\n\n%\n% calculate within class scatter matrix Sw\n%\n\nfunction Sw = get_Sw(Samples,Labels)\n\nc1_ind = find(Labels==1); c2_ind = find(Labels==2);\n\n% need to have at least 2 points in each class\nSw = cov(Samples(c1_ind,:))*(length(c1_ind)-1) + cov(Samples(c2_ind,:))*(length(c2_ind)-1);\n\nreturn;\n\n%\n% calculate within class scatter matrix Sw (directly according to the definition)\n%\n\nfunction Sw = get_Sw_v2(Samples,Labels)\n\nc1_ind = find(Labels==1); c2_ind = find(Labels==2);\n\n% to verify the correctness of Sw\nSw = zeros(size(Samples,2));\nm1 = mean(Samples(c1_ind,:),1);\nxs1 = Samples(c1_ind,:) - m1(ones(1,length(c1_ind)),:);\nfor i = 1:size(xs1,1)\n Sw = Sw + xs1(i,:)'*xs1(i,:);\nend\n\nm2 = mean(Samples(c2_ind,:),1);\nxs2 = Samples(c2_ind,:) - m2(ones(1,length(c2_ind)),:);\nfor i = 1:size(xs2,1)\n Sw = Sw + xs2(i,:)'*xs2(i,:);\nend\n\nreturn;", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SpharmToolbox/code/FLD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6266705752922028}} {"text": "function [mfg, mbg] = im_modes(im)\n% IM_MODES Estimate typical values (modes) of foreground/background\n% intensities in a greyscale image.\n%\n% [MFG, MBG] = im_modes(IM)\n%\n% IM is an N-array of grayscale intensity values.\n%\n% MFG, MBG are scalars with the typical intensity values of foreground\n% (darker) and foreground (lighter) voxels. \"Typical\" means the mode of\n% the corresponding distributions.\n%\n% The modes are estimated by computing histograms with up to 500 bins for\n% the intensity values, and smoothing the distribution until only 1 or 2\n% peaks are visible. In case of 1 peak, it is assume that the image\n% contains only background voxels, and MFG=NaN.\n\n% Author: Ramon Casero \n% Copyright © 2014 University of Oxford\n% Version: 0.1.0\n%\n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see\n% .\n\nDEBUG = 0;\n\n% check arguments\nnarginchk(1, 1);\nnargoutchk(0, 2);\n\n% ignore intensity values = 0. Those are considered to be masked out\nim2 = im(im > 0);\n\n% if the input image is empty, or too small, we assume that we don't have\n% enough information to estimate the background and foreground\nif (nnz(im2) < 100)\n mbg = nan;\n mfg = nan;\n return\nend\n\n% number of bins to use. We assume that we need at least 10 samples per\n% bin, but we don't need more than 500 bins in total. Histograms with more\n% bins are slower to process and smooth\nnbin = min(500, ceil(nnz(im2)/10));\n\n% compute histogram of the intensity values\n[fhist, xhist] = hist(im2, nbin);\nfhist = fhist / sum(fhist);\n\n% initial estimation of peaks in the histogram\n[pks, loc] = findpeaks(fhist, 'minpeakheight', 0.5e-3);\n\n% number of peaks found\nnpks = length(pks);\n\n% smooth the histogram until we find just 1 or 2 peaks\ntol = 0.5e-10;\nwhile ~((npks == 1) ...\n || ((npks == 2) && (abs(diff(loc)) >= 50)))\n \n % increase the smoothing parameter\n tol = tol * 2;\n \n % smooth the histogram\n [~, fhist2] = spaps(xhist, fhist, tol);\n \n % find the peaks\n [pks, loc] = findpeaks(fhist2, 'minpeakheight', 0.5e-3);\n \n % number of peaks found\n npks = length(pks);\n \nend\n\n% deal with the number of peaks\nif (npks == 2)\n \n % we have background and tissue. The background is lighter. Sort the\n % peaks in darker to lighter order\n loc = sort(loc, 'ascend');\n\n % extract typical intensities for background and foreground\n mfg = xhist(loc(1));\n mbg = xhist(loc(2));\n \n % DEBUG\n if (DEBUG)\n subplot(2, 1, 1)\n hold off\n plot(xhist, fhist, 'b')\n hold on\n plot(xhist, fhist2, 'r')\n plot(mfg*[1 1], [0 max(fhist)], 'g')\n plot(mbg*[1 1], [0 max(fhist)], 'k')\n \n subplot(2, 1, 2)\n hold off\n imagesc(im(:, :, round((size(im, 3)+1)/2)))\n end\n\nelseif (npks == 1)\n \n % we assume there's only background (although note that this could be a\n % case with only tissue)\n mfg = nan;\n mbg = xhist(loc);\n \n % DEBUG\n if (DEBUG)\n hold off\n plot(xhist, fhist, 'b')\n hold on\n plot(xhist, fhist2, 'r')\n plot(mbg*[1 1], [0 max(fhist)], 'r')\n end\n \nelse\n\n error('Assertion fail: The histogram has no peaks')\n \nend\n\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/FiltersToolbox/im_modes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6266705736979361}} {"text": "function [ sparse_order, sparse_index ] = sparse_grid_mixed_index ( ...\n dim_num, level_max, rule, point_num, point_total_num, sparse_unique_index )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_MIXED_INDEX indexes a sparse grid made from mixed 1D rules.\n%\n% Discussion:\n%\n% For each \"unique\" point in the sparse grid, we return its INDEX and ORDER.\n%\n% That is, for the I-th unique point P, we determine the product grid which\n% first generated this point, and we return in SPARSE_ORDER the orders of\n% the 1D rules in that grid, and in SPARSE_INDEX the component indexes in\n% those rules that generated this specific point.\n%\n% For instance, say P was first generated by a rule which was a 3D product\n% of a 9th order CC rule and a 15th order GL rule, and that to generate P,\n% we used the 7-th point of the CC rule and the 3rh point of the GL rule.\n% Then the SPARSE_ORDER information would be (9,15) and the SPARSE_INDEX\n% information would be (7,3). This, combined with the information in RULE,\n% is enough to regenerate the value of P.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 March 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Fabio Nobile, Raul Tempone, Clayton Webster,\n% A Sparse Grid Stochastic Collocation Method for Partial Differential\n% Equations with Random Input Data,\n% SIAM Journal on Numerical Analysis,\n% Volume 46, Number 5, 2008, pages 2309-2345.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer RULE(DIM_NUM), the rule in each dimension.\n% 1, \"CC\", Clenshaw Curtis, Closed Fully Nested rule.\n% 2, \"F2\", Fejer Type 2, Open Fully Nested rule.\n% 3, \"GP\", Gauss Patterson, Open Fully Nested rule.\n% 4, \"GL\", Gauss Legendre, Open Weakly Nested rule.\n% 5, \"GH\", Gauss Hermite, Open Weakly Nested rule.\n% 6, \"GGH\", Generalized Gauss Hermite, Open Weakly Nested rule.\n% 7, \"LG\", Gauss Laguerre, Open Non Nested rule.\n% 8, \"GLG\", Generalized Gauss Laguerre, Open Non Nested rule.\n% 9, \"GJ\", Gauss Jacobi, Open Non Nested rule.\n% 10, \"GW\", Golub Welsch, (presumed) Open Non Nested rule.\n% 11, \"CC_SE\", Clenshaw Curtis Slow Exponential, Closed Fully Nested rule.\n% 12, \"F2_SE\", Fejer Type 2 Slow Exponential, Closed Fully Nested rule.\n% 13, \"GP_SE\", Gauss Patterson Slow Exponential, Closed Fully Nested rule.\n% 14, \"CC_ME\", Clenshaw Curtis Moderate Exponential, Closed Fully Nested rule.\n% 15, \"F2_ME\", Fejer Type 2 Moderate Exponential, Closed Fully Nested rule.\n% 16, \"GP_ME\", Gauss Patterson Moderate Exponential, Closed Fully Nested rule.\n% 17, \"CCN\", Clenshaw Curtis Nested, Linear, Closed Fully Nested rule.\n%\n% Input, integer POINT_NUM, the number of unique points in the grid.\n%\n% Input, integer POINT_TOTAL_NUM, the total number of points in the grid.\n%\n% Input, integer SPARSE_UNIQUE_INDEX(POINT_TOTAL_NUM), associates each\n% point in the grid with its unique representative.\n%\n% Output, integer SPARSE_ORDER(DIM_NUM,POINT_NUM), lists, for each point,\n% the order of the 1D rules used in the grid that generated it.\n%\n% Output, integer SPARSE_INDEX(DIM_NUM,POINT_NUM), lists, for each point,\n% its index in each of the 1D rules in the grid that generated it.\n% The indices are 1-based.\n%\n\n%\n% Special cases.\n%\n if ( level_max < 0 )\n sparse_order = [];\n sparse_index = [];\n return\n end\n\n if ( level_max == 0 )\n sparse_order(1:dim_num,1) = 1;\n sparse_index(1:dim_num,1) = 1;\n return\n end\n\n sparse_order = zeros ( dim_num, point_num );\n sparse_index = zeros ( dim_num, point_num );\n\n point_count = 0;\n%\n% The outer loop generates values of LEVEL.\n%\n level_min = max ( 0, level_max + 1 - dim_num );\n\n for level = level_min : level_max\n%\n% The middle loop generates a GRID,\n% based on the next partition that adds up to LEVEL.\n%\n level_1d = [];\n more_grids = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ level_1d, more_grids, h, t ] = comp_next ( level, dim_num, level_1d, ...\n more_grids, h, t );\n\n order_1d = level_to_order_default ( dim_num, level_1d, rule );\n%\n% The inner loop generates a POINT of the GRID of the LEVEL.\n%\n point_index = [];\n more_points = 0;\n\n while ( 1 )\n\n [ point_index, more_points ] = vec_colex_next3 ( dim_num, order_1d, point_index, ...\n more_points );\n\n if ( ~more_points )\n break\n end\n\n point_count = point_count + 1;\n point_unique = sparse_unique_index(point_count);\n sparse_order(1:dim_num,point_unique) = order_1d(1:dim_num);\n sparse_index(1:dim_num,point_unique) = point_index(1:dim_num);\n\n end\n\n if ( ~more_grids )\n break\n end\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_mixed/sparse_grid_mixed_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6266705674721968}} {"text": "function res = lt(a,b)\n%LT Implements a < b elementwise for intervals a and b\n%\n% if true, a is definitely less than b\n%\n\n% written 10/16/98 S.M. Rump\n% modified 11/30/98 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n%\n\n if ~isa(a,'intval')\n a = intval(a);\n end\n if ~isa(b,'intval')\n b = intval(b);\n end\n\n if a.complex | b.complex\n res = real(sup(a)) < real(inf(b)) & imag(sup(a)) < imag(inf(b)) ;\n else\n res = sup(a) < inf(b) ;\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/intval/@intval/lt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6265631894401473}} {"text": "function xPol=Cart2DState2PolarState(xCart,systemType)\n%%CART2DSSTATE2POLARSTATE Transform a 2D Cartesian state into a state\n% consisting of position, heading and speed as well\n% as possibly a turn rate and a linear\n% acceleration, depending on the choice of\n% systemType.\n%\n%INPUTS: xCart A Cartesian state vector consisting of position velocity and\n% possibly acceleration into a state where heading and speed\n% have been separated. xCart has the form\n% [x;y;xdot;ydot;xddot;yddot], where the acceleration terms\n% xddot;yddot can be omitted if the system type is 'ConstVel'.\n% systemType A string constant specifying the desired type of output. In\n% all instances, the heading is measured in terms of radians\n% counterclockwise from the x-axis. Possible values are:\n% 'ConstVel' The target state is [position;heading;speed]\n% and xCart is [position;velocity]\n% 'ConstAccel' The target state is [position;heading;speed;\n% speed derivative] and xCart is\n% [position;velocity;acceleration]\n% 'ConstTurn' The target state is [position;heading;speed;\n% turn rate] and xCart is\n% [position;velocity;acceleration]\n% 'TurnAndAccel' The target state is [position;heading;speed;\n% turnrate; speed derivative] and xCart is\n% [position;velocity;acceleration]\n%\n%OUTPUTS: xPol The state converted from 2D Cartesian coordinates into the\n% selected 2D coordinate system.\n%\n%When the system type is 'ConstVel' or 'TurnAndAccel', only a single\n%solution is mathematically observable. When the system type is\n%'ConstAccel' or 'ConstTurn', the system is overdetermined, but only a\n%simple solution is used, not a least squares solution.\n%\n%The use of 2D states where the heading and speed have been separated is\n%discussed in [1] and [2].\n%\n%The opposite of this function is polar2DState2CartState.\n%\n%REFERENCES:\n%[1] M. Busch and S. Blackman, \"Evaluation of IMM filtering for an air\n% defense system application,\" in Proceedings of SPIE: Signal and Data\n% Processing of Small Targets, vol. 2561, 9 Jul. 1995, pp. 435-447.\n%[1] J. L. Gertz, \"Multisensor surveillance for improved aircraft\n% tracking,\" The Lincoln Laboratory Journal, vol. 2, no. 3, pp. 381-396,\n% 1989.\n%\n%July 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%Get position\nx=xCart(1);\ny=xCart(2);\n%Get velocity\nxDot=xCart(3);\nyDot=xCart(4);\n\nswitch(systemType)\n case 'ConstVel' %Given position, heading, and speed.\n xPol=[x;\n y;\n atan2(yDot,xDot);\n sqrt(yDot^2+xDot^2)];\n case 'ConstAccel'%Given position, heading, speed, and linear\n %acceleration\n %Get acceleration\n xDdot=xCart(5);\n yDdot=xCart(6);\n \n theta=atan2(yDot,xDot);%Heading\n %Determine the sign of the derivative velocity, ignoring the possible\n %effects of noise...\n vDot=sqrt(yDdot^2+xDdot^2);%Linear acceleration\n \n diff1=(vDot*cos(theta)-xDdot)^2+(vDot*sin(theta)-yDdot)^2;\n diff2=(-vDot*cos(theta)-xDdot)^2+(-vDot*sin(theta)-yDdot)^2;\n if(diff2 thres),opts);\n % Best universe\n if fit(i) < fitG\n fitG = fit(i);\n Xgb = X(i,:);\n end\n end\n % Sort universe from best to worst\n [fitSU, idx] = sort(fit,'ascend'); \n X_SU = X(idx,:); \n % Elitism (first 1 is elite)\n X(1,:) = X_SU(1,:);\n % Either 1-norm or 2-norm \n if type == 1 \n % Normalize inflation rate using 2-norm\n NI = fitSU ./ sqrt(sum(fitSU .^ 2)); \n elseif type == 2\n % Normalize inflation rate using 1-norm\n NI = fitSU / sum(fitSU);\n end\n % Normalize inverse inflation rate using 1-norm\n inv_fitSU = 1 ./ (1 + fitSU); \n inv_NI = inv_fitSU / sum(inv_fitSU);\n % Wormhole Existence probability (3.3), increases from 0.2 to 1\n WEP = Wmin + t * ((Wmax - Wmin) / max_Iter);\n % Travelling disrance rate (3.4), descreases from 0.6 to 0\n TDR = 1 - ((t ^ (1 / p)) / (max_Iter ^ (1 / p)));\n % Start with 2 since first is elite\n for i = 2:N\n % Define black hole\n idx_BH = i;\n for d = 1:dim\n % White/black hole tunnels & exchange object of universes (3.1)\n r1 = rand();\n if r1 < NI(i)\n % Random select k with roulette wheel\n idx_WH = jRouletteWheelSelection(inv_NI);\n % Position update\n X(idx_BH, d) = X_SU(idx_WH, d);\n end\n % Local changes for universes (3.2)\n r2 = rand(); \n if r2 < WEP \n r3 = rand(); \n r4 = rand();\n if r3 < 0.5\n X(i,d) = Xgb(d) + TDR * ((ub - lb) * r4 + lb);\n else\n X(i,d) = Xgb(d) - TDR * ((ub - lb) * r4 + lb);\n end\n else\n X(i,d) = X(i,d);\n end\n end\n % Boundary\n XB = X(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n X(i,:) = XB;\n end\n curve(t) = fitG;\n fprintf('\\nIteration %d Best (MVO)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features\nPos = 1:dim;\nSf = Pos((Xgb > thres) == 1); \nsFeat = feat(:,Sf);\n% Store results\nMVO.sf = Sf; \nMVO.ff = sFeat;\nMVO.nf = length(Sf); \nMVO.c = curve;\nMVO.f = feat;\nMVO.l = label;\nend\n\n\n%// Roulette Wheel Selection //\nfunction Index = jRouletteWheelSelection(prob)\n% Cummulative summation\nC = cumsum(prob);\n% Random one value, most probability value [0~1]\nP = rand();\n% Route wheel\nfor i = 1:length(C)\n\tif C(i) > P\n Index = i;\n break;\n end\nend\nend\n\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jMultiVerseOptimizer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.6265590326894308}} {"text": "function hydro = excitationIRF(hydro,tEnd,nDt,nDw,wMin,wMax)\n% Calculates the normalized excitation impulse response function:\n% \n% \t:math:`\\overline{K}_{e,i,\\theta}(t) = {\\frac{1}{2\\pi}}\\intop_{-\\infty}^{\\infty}{\\frac{X_i(\\omega,\\theta)e^{i{\\omega}t}}{{\\rho}g}}d\\omega`\n% \n% Default parameters can be used by inputting [].\n% See ``WEC-Sim\\examples\\BEMIO`` for examples of usage.\n% \n% Parameters\n% ----------\n% hydro : struct\n% Structure of hydro data\n% \n% tEnd : float\n% Calculation range for the IRF, where the IRF is calculated from t\n% = 0 to tEnd, and the default is 100 s\n% \n% nDt : float\n% Number of time steps in the IRF, the default is 1001 \n% \n% nDw : float\n% Number of frequency steps used in the IRF calculation\n% (hydrodynamic coefficients are interpolated to correspond), the\n% default is 1001\n% \n% wMin : float\n% Minimum frequency to use in the IRF calculation, the default is\n% the minimum frequency from the BEM data\n% \n% wMax : float\n% Maximum frequency to use in the IRF calculation, the default is\n% the maximum frequency from the BEM data\n%\n% Returns\n% -------\n% hydro : struct\n% Structure of hydro data with excitation IRF\n% \n\np = waitbar(0,'Calculating excitation IRFs...'); % Progress bar\n\n% Set defaults if empty\nif isempty(tEnd)==1; tEnd = 100; end\nif isempty(nDt)==1; nDt = 1001; end\nif isempty(nDw)==1; nDw = 1001; end\nif isempty(wMin)==1; wMin = min(hydro.w); end\nif isempty(wMax)==1; wMax = max(hydro.w); end\n\n% Interpolate to the given t and w\nt = linspace(-tEnd,tEnd,nDt);\nw = linspace(wMin,wMax,nDw); \nN = sum(hydro.dof)*hydro.Nh;\n\n% Calculate the impulse response function for excitation\nn = 0;\nfor i = 1:sum(hydro.dof)\n for j = 1:hydro.Nh\n ex_re = interp1(hydro.w,squeeze(hydro.ex_re(i,j,:)),w);\n ex_im = interp1(hydro.w,squeeze(hydro.ex_im(i,j,:)),w);\n hydro.ex_K(i,j,:) = (1/pi)*trapz(w,ex_re.*cos(w.*t(:))-ex_im.*sin(w.*t(:)),2);\n n = n+1;\n end\n waitbar(n/N)\nend\n\nhydro.ex_t = t;\nhydro.ex_w = w;\nclose(p);\n\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/BEMIO/excitationIRF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6265590250561488}} {"text": "function [xopt,fopt]=simann(func, x, LB, UB, sa_t, sa_rt, sa_nt, sa_ns,rseed) \n\n% Simulated Annealing programmed for minimization problem\n% INPUTS\n% func, string variable containing name of function file to be optimized \n% x, starting values\n% LB, lower bound on optimization parameters\n% UB, upper bound on optimization parameters\n% sa_t, initial temperature\n% sa_rt, temperature reduction factor, 0 < sa_rt < 1, try .85\n% sa_nt, number of times through ns loop before temperature reduction (recommended value: 5)\n% sa_ns, number of times through function before stepsize adjustment (recommended value: 20)\n%\n% OUTPUTS\n% xopt, the optimal solution\n%\n% \n\n\nLB=LB(:)'; \nUB=UB(:)';\n\nrand('state',rseed); %sets seed for random number generator\nsa_neps=4; %number of times eps\n %tolerance is achieved before termination\nsa_eps=eps; %convergence criteria\nsa_maxeval=60;%12000000; %maximum number of function evaluations\n\nsa_nargs=length(LB); %number of parameters\nsa_nobds=0;\nsa_nacc=0; %number of acceptions\nsa_nevals=0; %number of evaluations\nsa_opteval=0; %optimum number of\n %function evaluations\n\nfstar=Inf*ones(sa_neps,1);\n\n%x=LB+(UB-LB).*rand(1, sa_nargs); %starting values for model parameters\nf=feval(func,x); %function evaluation with parameters x\n%disp('initial loss function value:');disp(f);\nsa_nevals=sa_nevals+1;\nxopt=x;\nfopt=f;\nxtot=x;\nfstar(1)=f;\n\nVM=(UB-LB);%/2; %maximum step size\n\n%LOOP\nwhile 1 \n \n nup=0; %number of uphill movements\n nrej=0; %number of rejections\n nnew=0;\n ndown=0; %number of downhill movements\n lnobds=0;\n nacp=zeros(sa_nargs,1);\n C = progress('init','Determine initial hyperparameters for simplex...');\n for m=1:sa_nt\n for j=1:sa_ns\n for h=1:sa_nargs\n if sa_nevals>=sa_maxeval\n %disp('too many function evaluations')\n return\n end\n C = progress(C,sa_nevals/sa_maxeval);\n %workbar(sa_nevals/sa_maxeval,'Determine initial hyperparameters to build grid...','Progress') \n % generate xp, trial value of x\n xp=x;\n xp(h)=x(h)+VM(h)*(2*rand(1,1)-1.0); %calculate new value for x (xp)\n if (xp(h)UB(h))\n xp(h)=LB(h)+(UB(h)-LB(h))*rand(1,1);\n lnobds=lnobds+1;\n sa_nobds=sa_nobds+1;\n end \n % evaluate at xp and return as fp\n %disp ('current parameter vector:');disp(xp);\n fp=feval(func,xp); %function evaluation with parameters xp\n %disp ('function value');disp(fp);\n sa_nevals=sa_nevals+1;\n\n % we minimize! accept if the function value decreases\n if fp<=f\n x=xp;\n f=fp;\n sa_nacc=sa_nacc+1;\n nacp(h)=nacp(h)+1;\n nup=nup+1;\n % if smaller than any previous point, record as new optimum\n if fp0.6\n VM(i)=VM(i) * (1+c(i)*(ratio-0.6)/0.4);\n elseif ratio <0.4\n VM(i)=VM(i)/(1+c(i)*((0.4-ratio)/0.4));\n end\n if VM(i)>(UB(i)-LB(i))\n VM(i)=UB(i)-LB(i);\n end\n end\n\n % provide statistics about current state of optimization\n \n% disp('No. of evaluations');disp(sa_nevals);disp(' current temperature');disp(sa_t);\n% disp('current optimum function value');disp(fopt);\n% disp('No. of downhill steps');disp(nup); % note misnomer in variable declaration!\n% disp('No. of accepted uphill steps');disp(ndown); % we minimize, thus downhill is always accepted!\n% disp('No. of rejections');disp(nrej);\n% disp('current parameter values');disp(xp);\n% disp('current optimum vector');disp(xopt);\n% disp('current step size');disp(VM);\n %disp('Variables used:');whos;\n\n for i=1:sa_nargs\n nacp(i) = 0;\n end\n end\n \n \n % check termination criteria\n fstar(1)=f;\n quit = ((fstar(1)-fopt) <= sa_eps);\n if any(abs(fstar-f)>sa_eps)\n quit=0;\n end\n \n if quit\n disp(['simulated annealing achieved termination after ', num2str(sa_nevals),' evals']);\n return\n end\n \n % reduce temperature \n sa_t=sa_t*sa_rt;\n fstar(2:4)=fstar(1:3);\n % continue from current optimum\n x=xopt;\n f=fopt;\nend %while\n\n\n\n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/simann.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6265590137533968}} {"text": "function [x, options, flog, pointlog, scalelog] = scg(f, x, options, gradf, varargin)\n%SCG\tScaled conjugate gradient optimization.\n%\n%\tDescription\n%\t[X, OPTIONS] = SCG(F, X, OPTIONS, GRADF) uses a scaled conjugate\n%\tgradients algorithm to find a local minimum of the function F(X)\n%\twhose gradient is given by GRADF(X). Here X is a row vector and F\n%\treturns a scalar value. The point at which F has a local minimum is\n%\treturned as X. The function value at that point is returned in\n%\tOPTIONS(8).\n%\n%\t[X, OPTIONS, FLOG, POINTLOG, SCALELOG] = SCG(F, X, OPTIONS, GRADF)\n%\talso returns (optionally) a log of the function values after each\n%\tcycle in FLOG, a log of the points visited in POINTLOG, and a log of\n%\tthe scale values in the algorithm in SCALELOG.\n%\n%\tSCG(F, X, OPTIONS, GRADF, P1, P2, ...) allows additional arguments to\n%\tbe passed to F() and GRADF(). The optional parameters have the\n%\tfollowing interpretations.\n%\n%\tOPTIONS(1) is set to 1 to display error values; also logs error\n%\tvalues in the return argument ERRLOG, and the points visited in the\n%\treturn argument POINTSLOG. If OPTIONS(1) is set to 0, then only\n%\twarning messages are displayed. If OPTIONS(1) is -1, then nothing is\n%\tdisplayed.\n%\n%\tOPTIONS(2) is a measure of the absolute precision required for the\n%\tvalue of X at the solution. If the absolute difference between the\n%\tvalues of X between two successive steps is less than OPTIONS(2),\n%\tthen this condition is satisfied.\n%\n%\tOPTIONS(3) is a measure of the precision required of the objective\n%\tfunction at the solution. If the absolute difference between the\n%\tobjective function values between two successive steps is less than\n%\tOPTIONS(3), then this condition is satisfied. Both this and the\n%\tprevious condition must be satisfied for termination.\n%\n%\tOPTIONS(9) is set to 1 to check the user defined gradient function.\n%\n%\tOPTIONS(10) returns the total number of function evaluations\n%\t(including those in any line searches).\n%\n%\tOPTIONS(11) returns the total number of gradient evaluations.\n%\n%\tOPTIONS(14) is the maximum number of iterations; default 100.\n%\n%\tSee also\n%\tCONJGRAD, QUASINEW\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Set up the options.\nif length(options) < 18\n error('Options vector too short')\nend\n\nif(options(14))\n niters = options(14);\nelse\n niters = 100;\nend\n\ndisplay = options(1);\ngradcheck = options(9);\n\n% Set up strings for evaluating function and gradient\nf = fcnchk(f, length(varargin));\ngradf = fcnchk(gradf, length(varargin));\n\nnparams = length(x);\n\n% Check gradients\nif (gradcheck)\n feval('gradchek', x, f, gradf, varargin{:});\nend\n\nsigma0 = 1.0e-4;\nfold = feval(f, x, varargin{:});\t% Initial function value.\nfnow = fold;\noptions(10) = options(10) + 1;\t\t% Increment function evaluation counter.\ngradnew = feval(gradf, x, varargin{:});\t% Initial gradient.\ngradold = gradnew;\noptions(11) = options(11) + 1;\t\t% Increment gradient evaluation counter.\nd = -gradnew;\t\t\t\t% Initial search direction.\nsuccess = 1;\t\t\t\t% Force calculation of directional derivs.\nnsuccess = 0;\t\t\t\t% nsuccess counts number of successes.\nbeta = 1.0;\t\t\t\t% Initial scale parameter.\nbetamin = 1.0e-15; \t\t\t% Lower bound on scale.\nbetamax = 1.0e100;\t\t\t% Upper bound on scale.\nj = 1;\t\t\t\t\t% j counts number of iterations.\nif nargout >= 3\n flog(j, :) = fold;\n if nargout == 4\n pointlog(j, :) = x;\n end\nend\n\n% Main optimization loop.\nwhile (j <= niters)\n\n % Calculate first and second directional derivatives.\n if (success == 1)\n mu = d*gradnew';\n if (mu >= 0)\n d = - gradnew;\n mu = d*gradnew';\n end\n kappa = d*d';\n if kappa < eps\n options(8) = fnow;\n return\n end\n sigma = sigma0/sqrt(kappa);\n xplus = x + sigma*d;\n gplus = feval(gradf, xplus, varargin{:});\n options(11) = options(11) + 1; \n theta = (d*(gplus' - gradnew'))/sigma;\n end\n\n % Increase effective curvature and evaluate step size alpha.\n delta = theta + beta*kappa;\n if (delta <= 0) \n delta = beta*kappa;\n beta = beta - theta/kappa;\n end\n alpha = - mu/delta;\n \n % Calculate the comparison ratio.\n xnew = x + alpha*d;\n fnew = feval(f, xnew, varargin{:});\n options(10) = options(10) + 1;\n Delta = 2*(fnew - fold)/(alpha*mu);\n if (Delta >= 0)\n success = 1;\n nsuccess = nsuccess + 1;\n x = xnew;\n fnow = fnew;\n else\n success = 0;\n fnow = fold;\n end\n\n if nargout >= 3\n % Store relevant variables\n flog(j) = fnow;\t\t% Current function value\n if nargout >= 4\n pointlog(j,:) = x;\t% Current position\n if nargout >= 5\n\tscalelog(j) = beta;\t% Current scale parameter\n end\n end\n end \n if display > 0\n fprintf(1, 'Cycle %4d Error %11.6f Scale %e\\n', j, fnow, beta);\n end\n\n if (success == 1)\n % Test for termination\n\n if (max(abs(alpha*d)) < options(2) & max(abs(fnew-fold)) < options(3))\n options(8) = fnew;\n return;\n\n else\n % Update variables for new position\n fold = fnew;\n gradold = gradnew;\n gradnew = feval(gradf, x, varargin{:});\n options(11) = options(11) + 1;\n % If the gradient is zero then we are done.\n if (gradnew*gradnew' == 0)\n\toptions(8) = fnew;\n\treturn;\n end\n end\n end\n\n % Adjust beta according to comparison ratio.\n if (Delta < 0.25)\n beta = min(4.0*beta, betamax);\n end\n if (Delta > 0.75)\n beta = max(0.5*beta, betamin);\n end\n\n % Update search direction using Polak-Ribiere formula, or re-start \n % in direction of negative gradient after nparams steps.\n if (nsuccess == nparams)\n d = -gradnew;\n nsuccess = 0;\n else\n if (success == 1)\n gamma = (gradold - gradnew)*gradnew'/(mu);\n d = gamma*d - gradnew;\n end\n end\n j = j + 1;\nend\n\n% If we get here, then we haven't terminated in the given number of \n% iterations.\n\noptions(8) = fold;\nif (options(1) >= 0)\n disp(maxitmess);\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/scg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6265021263051535}} {"text": "function [hm,HMpix] = euc2hmg(pix)\n\n% EUC2HMG Euclidean to Homogeneous point transform.\n% EUC2HMG(E) transforms the Euclidean point E onto homogeneous space by\n% appending 1 at the last coordinate.\n%\n% [h,H_e] = EUC2HMG(E) returns the Jacobian of the transformation.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\nhm = [pix;ones(1,size(pix,2))];\n\nif nargout > 1 % Jac -- OK\n \n if size(pix,2) == 1\n \n HMpix = [eye(numel(pix));zeros(1,numel(pix))];\n \n else\n error('??? Jacobians not available for multipla points.')\n end\n \nend\n\nreturn\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/Points/euc2hmg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.626477526749519}} {"text": "function [xxx1,xxx2] =dymism(r1,r3,l,r4,r5,choice,rpm,loc) \n%-----------------------------------------------------------\nformat bank;\n% clf;\n t = 0:1:360;\n tg = t*pi/180.0;\n cx =[0,0,l,0];\n r2 = sqrt(l^2 - r3^2 + r1^2);\n jj = 0;\n%----------------------------------------------------------- \n for j = 1:1:361\n jj = jj+1;\n x1 = r1 * cos(tg(j));\n x2 = r1 * sin(tg(j));\n [cx41, cx42, cx43] = x4fun(x1,x2,r3,l);\n [x41,x42] = qfun(cx41,cx42,cx43);\n x31 = x3fun(x1,x2,x41,r3,l);\n x32 = x3fun(x1,x2,x42,r3,l);\n a(jj,1) = jj;\n a(jj,2) = x1;\n a(jj,3) = x2;\n a(jj,4) = x31;\n a(jj,5) = x41;\n a(jj,6) = x32;\n a(jj,7) = x42;\n a(jj,8) = tang(x31-l,x41);\n a(jj,9) = tang(x32-l,x42);\n%------------------------------------------------------------------------------------------------------\n if l < r4+r5 & r4*r5 > 0 % new check\n [cx61,cx62,cx63] = x6fun(x1,x2,x31,x41,r1,r4,r5);\n [x61,x62] = qfun(cx61,cx62,cx63);\n x51 = x5fun(x1,x2,x31,x41,x61,r1,r4,r5);\n x52 = x5fun(x1,x2,x31,x41,x62,r1,r4,r5);\n a(jj,10) = x51;\n a(jj,11) = x61;\n a(jj,12) = x52;\n a(jj,13) = x62;\n [ccx61,ccx62,ccx63] = x6fun(x1,x2,x32,x42,r1,r4,r5);\n [xx61,xx62] = qfun(ccx61,ccx62,ccx63);\n xx51 = x5fun(x1,x2,x32,x42,xx61,r1,r4,r5);\n xx52 = x5fun(x1,x2,x32,x42,xx62,r1,r4,r5);\n a(jj,14) = xx51;\n a(jj,15) = xx61;\n a(jj,16) = xx52;\n a(jj,17) = xx62;\n end; % new check \n end;\n%-----------------------------------------------------------\nif l < r4+r5 & r4*r5 > 0 % new check\n for i1 = 2:1:361\n [a(i1,10),a(i1,11),a(i1,12),a(i1,13)] = organize(a(i1-1,10),a(i1-1,11),a(i1,10),a(i1,11),a(i1,12),a(i1,13));\n [a(i1,14),a(i1,15),a(i1,16),a(i1,17)] = organize(a(i1-1,14),a(i1-1,15),a(i1,14),a(i1,15),a(i1,16),a(i1,17));\nend;\nend; % new check \n%-----------------------------------------------------------\n if l < r4+r5 & r4*r5 > 0 & choice == 1 \n% xxx = plot(a(:,2),a(:,3),a(:,4),a(:,5),a(:,10),a(:,11))\n [xxx1,xxx2] = cvelo(a(:,2),a(:,3),a(:,4),a(:,5),a(:,10),a(:,11),rpm,loc);\n end;\n%--------------------------------------------------------------------------------\n if l < r4+r5 & r4*r5 > 0 & choice == 2\n% xxx = plot(a(:,2),a(:,3),a(:,4),a(:,5),a(:,12),a(:,13));\n [xxx1,xxx2] = cvelo(a(:,2),a(:,3),a(:,4),a(:,5),a(:,12),a(:,13),rpm,loc)\n end;\n%-------------------------------------------------------------------------------\n if l < r4+r5 & r4*r5 > 0 & choice == 3\n% xxx = plot(a(:,2),a(:,3),a(:,6),a(:,7),a(:,14),a(:,15));\n [xxx1,xxx2] = cvelo(a(:,2),a(:,3),a(:,6),a(:,7),a(:,14),a(:,15),rpm,loc);\n end;\n%----------------------------------------------------------------------------------\n if l < r4+r5 & r4*r5 > 0 & choice == 4\n% xxx = plot(a(:,2),a(:,3),a(:,6),a(:,7),a(:,16),a(:,17));\n [xxx1,xxx2] = cvelo(a(:,2),a(:,3),a(:,6),a(:,7),a(:,16),a(:,17),rpm,loc); \n end; \n%---------------------------------------------------------------------------\n save link_age.dat xxx1 -ascii\n disp('The answers are')\n disp('Given crank location')\n disp('Velocity')\n disp('velocity angle')\n disp('Accelleration')\n disp('Accelleration angle')\n disp('.....')\n disp('For three nodes');\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/8690-linkage-mechanism-mechanical-engineering/linkage2/dymism.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523146, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6261757201543813}} {"text": "function u = fem2d_bvp_serene ( nx, ny, a, c, f, x, y, show11 )\n\n%*****************************************************************************80\n%\n%% FEM2D_BVP_SERENE solves boundary value problem on a rectangle.\n%\n% Discussion:\n%\n% The program uses the finite element method, with piecewise \n% serendipity basis functions to solve a 2D boundary value problem \n% over a rectangle.\n%\n% The following differential equation is imposed inside the region:\n%\n% - d/dx a(x,y) du/dx - d/dy a(x,y) du/dy + c(x,y) * u(x,y) = f(x,y)\n%\n% where a(x,y), c(x,y), and f(x,y) are given functions.\n%\n% On the boundary, the solution is constrained to have the value 0.\n%\n% The finite element method will use a regular grid of NX nodes in X, and \n% NY nodes in Y. Both NX and NY must be odd.\n%\n% The local element numbering is\n%\n% 3--2--1\n% | |\n% 4 8\n% | |\n% 5--6--7\n%\n% The serendipity element mass matrix is a multiple of:\n%\n% 6.0, -6.0, 2.0, -8.0, 3.0, -8.0, 2.0, -6.0\n% -6.0, 32.0, -6.0, 20.0, -8.0, 16.0, -8.0, 20.0\n% 2.0, -6.0, 6.0, -6.0, 2.0, -8.0, 3.0, -8.0\n% -8.0, 20.0, -6.0, 32.0, -6.0, 20.0, -8.0, 16.0\n% 3.0, -8.0, 2.0, -6.0, 6.0, -6.0, 2.0, -8.0\n% -8.0, 16.0, -8.0, 20.0, -6.0, 32.0, -6.0, 20.0\n% 2.0, -8.0, 3.0, -8.0, 2.0, -6.0, 6.0, -6.0\n% -6.0, 20.0, -8.0, 16.0, -8.0, 20.0, -6.0, 32.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NX, NY, the number of X and Y grid values.\n% NX and NY must be odd and at least 3.\n%\n% Input, function A(X,Y), evaluates a(x,y);\n%\n% Input, function C(X,Y), evaluates c(x,y);\n%\n% Input, function F(X,Y), evaluates f(x,y);\n%\n% Input, real X(NX), Y(NY), the mesh points.\n%\n% Input, integer SHOW11, is 1 to print out the element matrix\n% for the element in row 1, column 1.\n%\n% Output, real U(MN), the finite element coefficients, which are also\n% the value of the computed solution at the mesh points.\n%\n\n%\n% Quadrature definitions.\n%\n quad_num = 3;\n abscissa(1) = -0.774596669241483377035853079956;\n abscissa(2) = 0.000000000000000000000000000000;\n abscissa(3) = 0.774596669241483377035853079956;\n weight(1) = 0.555555555555555555555555555556;\n weight(2) = 0.888888888888888888888888888889;\n weight(3) = 0.555555555555555555555555555556;\n%\n% Make room for the matrix A and right hand side b.\n%\n mn = fem2d_bvp_serene_node_num ( nx, ny );\n\n A = zeros ( mn, mn );\n b = zeros ( mn, 1 );\n%\n% Compute the matrix entries by integrating over each element.\n%\n ex_num = ( nx - 1 ) / 2;\n ey_num = ( ny - 1 ) / 2;\n\n for ey = 1 : ey_num\n\n s = 2 * ey - 1;\n mm = 2 * ey;\n n = 2 * ey + 1;\n\n ys = y(s);\n ym = y(mm);\n yn = y(n);\n\n yy(1) = y(n);\n yy(2) = y(n);\n yy(3) = y(n);\n yy(4) = y(mm);\n yy(5) = y(s);\n yy(6) = y(s);\n yy(7) = y(s);\n yy(8) = y(mm);\n\n for ex = 1 : ex_num\n\n w = 2 * ex - 1;\n cc = 2 * ex;\n e = 2 * ex + 1;\n\n xe = x(e);\n xc = x(cc);\n xw = x(w);\n\n xx(1) = x(e);\n xx(2) = x(cc);\n xx(3) = x(w);\n xx(4) = x(w);\n xx(5) = x(w);\n xx(6) = x(cc);\n xx(7) = x(e);\n xx(8) = x(e);\n%\n% Node indices\n%\n% 3 2 1 wn cn en\n% 4 8 wm em\n% 5 6 7 ws cs es\n%\n node(1) = ( 3 * ey ) * ey_num + 2 * ey + 2 * ex + 1;\n node(2) = ( 3 * ey ) * ey_num + 2 * ey + 2 * ex;\n node(3) = ( 3 * ey ) * ey_num + 2 * ey + 2 * ex - 1;\n node(4) = ( 3 * ey - 1 ) * ey_num + 2 * ey + ex - 1;\n node(5) = ( 3 * ey - 3 ) * ey_num + 2 * ey + 2 * ex - 3;\n node(6) = ( 3 * ey - 3 ) * ey_num + 2 * ey + 2 * ex - 2;\n node(7) = ( 3 * ey - 3 ) * ey_num + 2 * ey + 2 * ex - 1;\n node(8) = ( 3 * ey - 1 ) * ey_num + 2 * ey + ex;\n\n if ( show11 )\n if ( ey == 1 && ex == 1 )\n ae = zeros(8,8);\n be = zeros(8,1);\n end\n end\n\n if ( 0 )\n fprintf ( 1, ' %2d %2d %2d %2d %2d %2d %2d %2d\\n', node(1:8) );\n end\n\n for qx = 1 : quad_num\n\n xq = ( ( 1.0 - abscissa(qx) ) * x(e) ...\n + ( 1.0 + abscissa(qx) ) * x(w) ) ...\n / 2.0;\n\n for qy = 1 : quad_num\n\n yq = ( ( 1.0 - abscissa(qy) ) * y(n) ...\n + ( 1.0 + abscissa(qy) ) * y(s) ) ...\n / 2.0;\n\n wq = weight(qx) * ( x(e) - x(w) ) / 2.0 ...\n * weight(qy) * ( y(n) - y(s) ) / 2.0;\n\n v = basis_serene ( xq, yq, xw, ys, xe, yn, xx, yy );\n [ vx, vy ] = basisd_serene ( xq, yq, xw, ys, xe, yn, xx, yy );\n\n aq = a ( xq, yq );\n cq = c ( xq, yq );\n fq = f ( xq, yq );\n%\n% Build the element matrix.\n%\n if ( show11 ) \n if ( ey == 1 && ex == 1 )\n for i = 1 : 8\n for j = 1 : 8\n ae(i,j) = ae(i,j) + wq * ( vx(i) * aq * vx(j) ...\n + vy(i) * aq * vy(j) ...\n + v(i) * cq * v(j) );\n end\n be(i) = be(i) + wq * ( v(i) * fq );\n end \n end\n end\n\n for i = 1 : 8\n ii = node(i);\n for j = 1 : 8\n jj = node(j);\n A(ii,jj) = A(ii,jj) + wq * ( vx(i) * aq * vx(j) ...\n + vy(i) * aq * vy(j) ...\n + v(i) * cq * v(j) );\n end\n b(ii) = b(ii) + wq * ( v(i) * fq );\n end\n\n end\n end \n%\n% Print a sample element matrix.\n%\n if ( show11 ) \n if ( ey == 1 && ex == 1 )\n scale = 0.5 * ae(1,3);\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The Wathen elementary mass matrix:\\n' );\n fprintf ( 1, '\\n' );\n ae / scale\n end\n end\n\n end\n end\n%\n% Where a node is on the boundary, \n% replace the finite element equation by a boundary condition.\n%\n k = 0;\n\n for y = 1 : ny\n\n if ( mod ( y, 2 ) == 1 )\n xhi = nx;\n else\n xhi = 1 + ( nx - 1 ) / 2;\n end\n\n for x = 1 : 2 : xhi\n k = k + 1;\n if ( x == 1 | x == xhi | y == 1 | y == ny )\n A(k,1:mn) = 0.0;\n A(1:mn,k) = 0.0;\n A(k,k) = 1.0;\n b(k) = 0.0;\n end\n end\n\n end\n\n if ( 0 )\n spy ( A );\n pause\n end\n%\n% Solve the linear system.\n%\n u = A \\ b;\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_bvp_serene/fem2d_bvp_serene.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6261757133832625}} {"text": "function X = calculateHuberMean(Y, rho, iters)\n% Perform a robust mean under the Huber loss function.\n% x = calculateRobust(Y, rho, iters)\n%\n% Input:\n% Y : MxN matrix over which to average (columnwise)\n% rho : augmented Lagrangian variable (default: 1)\n% iters : number of iterations to perform (default: 1000)\n%\n% Output:\n% x : 1xN vector that is the roust mean of Y\n%\n% Based on the ADMM Matlab codes also found at:\n% http://www.stanford.edu/~boyd/papers/distr_opt_stat_learning_admm.html\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2013-09-26\n\nif ~exist('rho', 'var') || isempty(rho)\n rho = 1; \nend\nif ~exist('iters', 'var') || isempty(iters)\n iters = 1000; \nend\n\nm = size(Y,1);\nif m==1\n X = Y;\nelse\n mu = sum(Y)/m;\n Z = zeros(size(Y)); U = Z;\n for k = 1:iters\n X = mu + sum(Z - U)/m;\n D = bsxfun(@minus, X, Y - U);\n Z = (rho/(1+rho) + (1/(1+rho))*max(0,(1-(1+1/rho)./abs(D)))).*D;\n U = D - Z;\n end\nend", "meta": {"author": "VisLab", "repo": "EEG-Clean-Tools", "sha": "9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e", "save_path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools", "path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools/EEG-Clean-Tools-9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e/PrepPipeline/utilities/calculateHuberMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6261757104540304}} {"text": "function d2 = dtiXformTensors(d, x)\n% dt6_new = dtiXformTensors(dt6, xform)\n% \n% Efficiently applies the 3x3 transform to a tensor volume in dt6 format.\n% dt6 is a XxYxZx3x3 array.\n%\n% This is just a matlab-efficient way to do xform*T*xform' on a\n% bunch of tensors (T) in dt6 format, a 3d array of the 6 unique\n% tensor elements in [Dxx, Dyy, Dzz, Dxy, Dxz, Dyz] order.\n% \n%\n% \n% HISTORY:\n% 2003.12.15 RFD & AHS Wrote it.\n% 2006.08.03 RFD: rewote it to be much more memory efficient. It's\n% also now ~2.5x faster.\n\nif(size(x,2)>3)\n x = x(1:3,1:3);\nend\n\nd2 = zeros(size(d));\nd2(:,:,:,1) = x(1)*(x(1).*d(:,:,:,1) + x(4).*d(:,:,:,4) + x(7).*d(:,:,:,5)) ...\n + x(4)*(x(1).*d(:,:,:,4) + x(4).*d(:,:,:,2) + x(7).*d(:,:,:,6)) ...\n\t + x(7)*(x(1).*d(:,:,:,5) + x(4).*d(:,:,:,6) + x(7).*d(:,:,:,3));\n\nd2(:,:,:,2) = x(2)*(x(2).*d(:,:,:,1) + x(5).*d(:,:,:,4) + x(8).*d(:,:,:,5)) ...\n + x(5)*(x(2).*d(:,:,:,4) + x(5).*d(:,:,:,2) + x(8).*d(:,:,:,6)) ...\n\t + x(8)*(x(2).*d(:,:,:,5) + x(5).*d(:,:,:,6) + x(8).*d(:,:,:,3));\n\nd2(:,:,:,3) = x(3)*(x(3).*d(:,:,:,1) + x(6).*d(:,:,:,4) + x(9).*d(:,:,:,5)) ...\n + x(6)*(x(3).*d(:,:,:,4) + x(6).*d(:,:,:,2) + x(9).*d(:,:,:,6)) ...\n\t + x(9)*(x(3).*d(:,:,:,5) + x(6).*d(:,:,:,6) + x(9).*d(:,:,:,3));\n\nd2(:,:,:,4) = x(2)*(x(1).*d(:,:,:,1) + x(4).*d(:,:,:,4) + x(7).*d(:,:,:,5)) ...\n + x(5)*(x(1).*d(:,:,:,4) + x(4).*d(:,:,:,2) + x(7).*d(:,:,:,6)) ...\n\t + x(8)*(x(1).*d(:,:,:,5) + x(4).*d(:,:,:,6) + x(7).*d(:,:,:,3));\n\nd2(:,:,:,5) = x(3)*(x(1).*d(:,:,:,1) + x(4).*d(:,:,:,4) + x(7).*d(:,:,:,5)) ...\n + x(6)*(x(1).*d(:,:,:,4) + x(4).*d(:,:,:,2) + x(7).*d(:,:,:,6)) ...\n\t + x(9)*(x(1).*d(:,:,:,5) + x(4).*d(:,:,:,6) + x(7).*d(:,:,:,3));\n\nd2(:,:,:,6) = x(3)*(x(2).*d(:,:,:,1) + x(5).*d(:,:,:,4) + x(8).*d(:,:,:,5)) ...\n + x(6)*(x(2).*d(:,:,:,4) + x(5).*d(:,:,:,2) + x(8).*d(:,:,:,6)) ...\n\t + x(9)*(x(2).*d(:,:,:,5) + x(5).*d(:,:,:,6) + x(8).*d(:,:,:,3));\n\nreturn;\n\n\n% OLD CODE (pre 2006.08.03 rewrite):\n\ntemp = zeros([size(d,1), size(d,2), size(d,3), 3, 3]);\ntemp(:,:,:,1,1) = x(1,1).*d(:,:,:,1) + x(1,2).*d(:,:,:,4) + x(1,3).*d(:,:,:,5);\ntemp(:,:,:,1,2) = x(1,1).*d(:,:,:,4) + x(1,2).*d(:,:,:,2) + x(1,3).*d(:,:,:,6);\ntemp(:,:,:,1,3) = x(1,1).*d(:,:,:,5) + x(1,2).*d(:,:,:,6) + x(1,3).*d(:,:,:,3);\ntemp(:,:,:,2,1) = x(2,1).*d(:,:,:,1) + x(2,2).*d(:,:,:,4) + x(2,3).*d(:,:,:,5);\ntemp(:,:,:,2,2) = x(2,1).*d(:,:,:,4) + x(2,2).*d(:,:,:,2) + x(2,3).*d(:,:,:,6);\ntemp(:,:,:,2,3) = x(2,1).*d(:,:,:,5) + x(2,2).*d(:,:,:,6) + x(2,3).*d(:,:,:,3);\ntemp(:,:,:,3,1) = x(3,1).*d(:,:,:,1) + x(3,2).*d(:,:,:,4) + x(3,3).*d(:,:,:,5);\ntemp(:,:,:,3,2) = x(3,1).*d(:,:,:,4) + x(3,2).*d(:,:,:,2) + x(3,3).*d(:,:,:,6);\ntemp(:,:,:,3,3) = x(3,1).*d(:,:,:,5) + x(3,2).*d(:,:,:,6) + x(3,3).*d(:,:,:,3);\n\ntemp = dtiXformVectors(temp, x', 'post');\nd2 = temp(:,:,:,[1 5 9 4 7 8]);\n\n% This is equivalent to:\n% dt6_new = zeros(size(dt6));\n% for (x=1:size(dt6,1)),\n% for (y=1:size(dt6,2)),\n% for (z=1:size(dt6,3)),\n% t = dti6to33(dt6_new(x,y,z,:));\n% t = xform * t * xform';\n% dt6_new(x,y,z,:) = dti33to6(t);\n% end\n% end\n% end\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/xform/dtiXformTensors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6261757091734016}} {"text": "function [y,dy] = div_sigma_gmr(Priors,Mu, Sigma_dx,Sigma, x, in, out)\n%DIV_GMR Derivative of Gaussian Mixture Regression\n%\n% Inputs -----------------------------------------------------------------\n% o Priors: 1 x K array representing the prior probabilities of the K GMM\n% components.\n% o Mu: D x K array representing the centers of the K GMM components.\n% o Sigma: D x D x K array representing the covariance matrices of the\n% K GMM components.\n% o x: P x N array representing N datapoints of P dimensions.\n% o in: 1 x P array representing the dimensions to consider as\n% inputs.\n% o out: 1 x Q array representing the dimensions to consider as\n% outputs (D=P+Q).\n% Outputs ----------------------------------------------------------------\n% o y: Q x N array representing the retrieved N datapoints of\n% Q dimensions, i.e. expected means.\n\n\nN = size(x,2);\n[D,D,K] = size(Sigma);\ntmp = zeros(1,1,K);\n\nindex = 1;\nfor i=1:K\n for j=1:D\n for l=j:D\n tmp(j,j,i) = Sigma_dx(index);%, Sigma_dx(2);Sigma_dx(3) Sigma_dx(4)];\n index = index + 1;\n end\n end\nend\nSigma_dx = tmp;\n\n%% Fast matrix computation (see the commented code for a version involving\n%% one-by-one computation, which is easier to understand).\n%%\n%% Compute the influence of each GMM component, given input x\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor i=1:K\n Pxi(:,i) = Priors(i).*gaussPDF(x, Mu(in,i), Sigma(in,in,i));\nend\nbeta = Pxi./repmat(sum(Pxi,2)+realmin,1,K);\n%% Compute expected means y, given input x\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor j=1:K\n y_tmp(:,:,j) = repmat(Mu(out,j),1,N) + Sigma_dx(:,:,j)*inv(Sigma(in,in,j)) * (x-repmat(Mu(in,j),1,N));\nend\nbeta_tmp = reshape(beta,[1 size(beta)]);\ny_tmp2 = repmat(beta_tmp,[length(out) 1 1]) .* y_tmp;\ny = sum(y_tmp2,3);\n\nif nargout > 1\n \n dy = zeros(1,K);\n \n for j=1:K\n v = inv(Sigma(in,in,j)) * (x - Mu(in,j));\n v = v(:);\n dy(j) = v;\n end\n \n dy = dy .* beta;\n \nend\n\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/gmmbox/GMMfunctions/Gaussian_derivative/GMR_derivative/div_sigma_gmr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6261566224899217}} {"text": "function p = legpoly(n, dom, normalize, method)\n%LEGPOLY Legendre polynomials.\n% P = LEGPOLY(N) computes a CHEBFUN of the Legendre polynomial of degree N on\n% the interval [-1,1]. N can be a vector of integers, in which case the output\n% is an array-valued CHEBFUN.\n%\n% P = LEGPOLY(N, D) computes the Legendre polynomials as above, but on the\n% interval given by the domain D, which must be bounded.\n%\n% P = LEGPOLY(N, D, 'norm') or P = LEGPOLY(N, 'norm') normalises so that\n% integral(P(:,j).*P(:,k)) = delta_{j,k}.\n%\n% For N <= 1000 LEGPOLY uses a weighted QR factorisation of a 2*(N+1) x\n% 2*(N+1) Chebyshev Vandermonde matrix. For scalar N > 1000 (or a short\n% vector) it uses the LEG2CHEB method and for a vector of N with any entry >\n% 1000 it uses the standard recurrence relation. This default can be\n% overwritten by passing a fourth input LEGPOLY(N, D, NORM, METHOD), where\n% METHOD is 1, 2, or 3 respectively.\n%\n% See also CHEBPOLY, LEGPTS, and LEG2CHEB.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse input:\nmethodIsSet = false;\nif ( isempty(n) )\n p = chebfun; \n return\nend\nif ( nargin < 2 || isempty(dom) )\n dom = [-1, 1];\nend\nif ( nargin < 3 || isempty(normalize) )\n normalize = 0; \nend\nif ( ischar(dom) )\n if ( nargin == 3 )\n method = normalize;\n if ( ~isempty(method) )\n methodIsSet = true;\n end\n end\n normalize = dom;\n dom = [-1,1]; \nend\nif ( strncmp(normalize, 'norm', 4) )\n normalize = 1;\nelseif ( ischar(normalize) )\n normalize = 0; \nend\nif ( (nargin == 4) && ~isempty(method) )\n methodIsSet = true;\nend\n \n% Unbounded domains aren't supported/defined.\nif ( any(isinf(dom)) )\n error('CHEBFUN:legpoly:infdomain', ...\n 'Legendre polynomials are not defined over an unbounded domain.');\nend\n\n% Force a CHEBTECH basis.\ndefaultPref = chebfunpref();\npref = defaultPref;\ntech = feval(pref.tech);\nif ( ~isa(tech, 'chebtech') )\n pref.tech = @chebtech2;\nend\n\n% Useful values:\nnMax = max(n);\nnMax1 = nMax + 1;\ndomIn = dom;\ndom = dom([1 end]);\n\n% Determine which method:\nif ( ~methodIsSet && nMax > 1000 )\n % Use LEG2CHEB():\n method = 3;\nelseif ( ~methodIsSet )\n % Use QR orthogonalization of Chebyshev polynomials for moderate nmax.\n method = 2;\nend\n\n% If the user wants most of the Legendre polynomials then it is faster to use\n% the recurrence: TODO: \"most\" is most than 20% of the [0:nMax]. Should this\n% percentage vary with nMax?\nif ( ~methodIsSet && (method == 3) && (nMax < 5000) && (numel(n) > nMax/5) ) \n method = 1; % Do not go above 5000 with the recurrence.\nend\n\nswitch method\n case 1 % Recurrence\n \n [aa, bb, cc] = unique(n); %#ok\n P = zeros(nMax1, length(n)); % Initialise storage\n x = chebpts(nMax1, 2); % Chebyshev points\n L0 = ones(nMax1, 1); L1 = x; % P_0 and P_1\n ind = 1; % Initialise counter\n for k = 2:nMax+2, % The recurrence relation (k = degree)\n if ( aa(ind) == k-2 )\n if ( normalize )\n invnrm = sqrt((2*k-3)/diff(dom));\n P(:,ind) = L0*invnrm;\n else\n P(:,ind) = L0;\n end\n ind = ind + 1;\n end\n tmp = L1;\n L1 = (2-1/k)*x.*L1 - (1-1/k)*L0;\n L0 = tmp;\n end\n C = chebtech2.vals2coeffs(P(:,cc)); % Convert to coefficients \n case 2 % QR\n\n pts = 2*nMax1; % Expand on Chebyshev grid of twice the size\n [ignored, w] = chebpts(pts, 2); % Grab the Clenshaw-Curtis weights\n theta = pi*(pts-1:-1:0)'/(pts-1);\n A = cos(theta*(0:nMax)); % Vandemonde-type matrix\n D = spdiags(sqrt(w(:)), 0, pts, pts); % C-C quad weights\n Dinv = spdiags(1./sqrt(w(:)), 0, pts, pts);\n [Q, ignored] = qr(D*A, 0); % Weighted QR\n P = Dinv*Q;\n if ( normalize )\n PP = P(:,n+1) * diag(sqrt(2/diff(dom)) * sign(P(end,n+1)));\n else\n PP = P(:,n+1) * diag(1./P(end,n+1));\n end\n C = chebtech2.vals2coeffs(PP); % Convert to coefficients\n C(nMax1+1:end,:) = []; % Trim coefficients > nMax\n \n case 3 % LEG2CHEB\n \n c_leg = zeros(nMax+1, numel(n));\n c_leg(n+1,:) = eye(numel(n)); % Legendre coefficients \n if ( normalize )\n C = leg2cheb(c_leg, 'norm'); % Chebyshev coefficients\n else\n C = leg2cheb(c_leg); % Chebyshev coefficients\n end\n \nend\n\n% Construct CHEBFUN from coeffs:\np = chebfun(C, dom, pref, 'coeffs'); \n\nif ( numel(domIn) > 2 )\n p = restrict(p, domIn);\nend\n\n% Adjust orientation:\nif ( size(n, 1) > 1 )\n p = p.'; \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/legpoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6261449087050555}} {"text": "classdef BT9 < PROBLEM\n% \n% Benchmark MOP with bias feature\n\n%------------------------------- Reference --------------------------------\n% H. Li, Q. Zhang, and J. Deng, Biased multiobjective optimization and\n% decomposition algorithm, IEEE Transactions on Cybernetics, 2017, 47(1):\n% 52-66.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 3;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n [N,D] = size(X);\n I1 = 3 : 3 : D;\n I2 = 4 : 3 : D;\n I3 = 5 : 3 : D;\n Y = X - sin(repmat(1:D,N,1)*pi/2/D);\n PopObj(:,1) = cos(0.5*X(:,1)*pi).*cos(0.5*X(:,2)*pi) + sum(Y(:,I1).^2+(1-exp(-Y(:,I1).^2/1e-9))/5,2);\n PopObj(:,2) = cos(0.5*X(:,1)*pi).*sin(0.5*X(:,2)*pi) + sum(Y(:,I2).^2+(1-exp(-Y(:,I2).^2/1e-9))/5,2);\n PopObj(:,3) = sin(0.5*X(:,1)*pi) + sum(Y(:,I3).^2+(1-exp(-Y(:,I3).^2/1e-9))/5,2);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = UniformPoint(N,3);\n R = R./repmat(sqrt(sum(R.^2,2)),1,3);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n a = linspace(0,pi/2,10)';\n R = {sin(a)*cos(a'),sin(a)*sin(a'),cos(a)*ones(size(a'))};\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/BT/BT9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6261449047576696}} {"text": "function [vert,conn,tria,tnum] = deltri2(varargin)\n%DELTRI2 compute a constrained 2-simplex Delaunay triangula-\n%tion in the two-dimensional plane.\n% [VERT,CONN,TRIA,TNUM]=DELTRI2(VERT,CONN,NODE,PSLG,PART)\n% computes the Delaunay trianguation {VERT,TRIA}, the con-\n% straints CONN, and the \"inside\" status vector TNUM. VERT\n% is an V-by-2 array of XY coordinates to be triangulated,\n% TRIA is a T-by-3 array of vertex indexing, where each\n% row defines a triangle, such that VERT(TRIA(II,1),:),\n% VERT(TRIA(II,2),:) and VERT(TRIA(II,3),:) are the coord-\n% inates of the II-TH triangle. CONN is a C-by-2 array of\n% constraining edges, where each row defines an edge, as\n% per TRIA. The additional arguments NODE,PSLG and PART\n% define a (mutliply-connected) polygonal region, where\n% NODE is an N-by-2 array of vertices and PSLG is a P-by-2\n% array of edges (a piecewise-straight-line-graph), where\n% each row defines an edge as a pair of indices into NODE.\n% PART is a cell-array of polygonal \"parts\", where each\n% element PART{KK} is an array of edge indices defining a\n% polygonal region. PSLG(PART{KK},:) is the set of edges\n% in the KK-TH part. TNUM is a T-by-1 array of part index-\n% ing, such that TNUM(II) is the index of the part in whi-\n% ch the II-TH triangle resides.\n%\n% See also DELAUNAYTRIANGULATION, DELAUNAYTRI, DELAUNAYN\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 08/07/2018\n\n vert = []; conn = []; node = []; PSLG = [];\n part = {}; kind = 'constrained';\n\n%---------------------------------------------- extract args\n if (nargin>=+1), vert = varargin{1}; end\n if (nargin>=+2), conn = varargin{2}; end\n if (nargin>=+3), node = varargin{3}; end\n if (nargin>=+4), PSLG = varargin{4}; end\n if (nargin>=+5), part = varargin{5}; end\n if (nargin>=+6), kind = varargin{6}; end\n\n%---------------------------------------------- basic checks\n if (~isnumeric(vert) || ~isnumeric(conn) || ...\n ~isnumeric(node) || ~isnumeric(PSLG) || ...\n ~iscell (part) || ~ischar (kind) )\n error('deltri2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n nvrt = size(vert,+1) ; nnod = size(node,+1) ;\n nedg = size(PSLG,+1) ;\n\n%---------------------------------------------- basic checks\n if (ndims(vert) ~= +2 || ndims(conn) ~= +2)\n error('deltri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(vert,2)~= +2 || size(conn,2)~= +2)\n error('deltri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n if (min([conn(:)])<+1 || max([conn(:)])>nvrt)\n error('deltri2:invalidInputs', ...\n 'Invalid CONN input array.') ;\n end\n\n%---------------------------------------------- basic checks\n if (nargin >= +3)\n\n if (ndims(node) ~= +2 || ndims(PSLG) ~= +2)\n error('deltri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(node,2)~= +2 || size(PSLG,2)~= +2)\n error('deltri2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n if (min([PSLG(:)])<+1 || max([PSLG(:)])>nnod)\n error('deltri2:invalidInputs', ...\n 'Invalid EDGE input array.') ;\n end\n\n pmin = cellfun(@min,part);\n pmax = cellfun(@max,part);\n\n if (min([pmin(:)])<+1 || max([pmax(:)])>nedg)\n error('deltri2:invalidInputs', ...\n 'Invalid PART input array.') ;\n end\n\n end\n\n%------------------------------------ compute Delaunay tria.\n switch (lower(kind))\n case 'constrained'\n\n if (exist( ...\n 'delaunayTriangulation') == +2 )\n %-------------------------------- use class if available\n dtri = ...\n delaunayTriangulation(vert,conn) ;\n vert = dtri.Points;\n conn = dtri.Constraints;\n tria = dtri.ConnectivityList;\n else\n if (exist('DelaunayTri') == +2 )\n %-------------------------------- use class if available\n dtri = DelaunayTri (vert,conn) ;\n vert = dtri.X;\n conn = dtri.Constraints;\n tria = dtri.Triangulation;\n else\n %-------------------------------- *fall-back* onto qhull\n [vert,conn,tria] ...\n = cfmtri2(vert,conn) ;\n end\n end\n\n case 'conforming'\n\n %-------------------------------- \"conforming\" delaunay!\n [vert,conn,tria] ...\n = cfmtri2(vert,conn) ;\n\n otherwise\n error('deltri2:invalidInputs', ...\n 'Invalid KIND selection.') ;\n\n end\n\n%------------------------------------ calc. \"inside\" status!\n tnum = zeros(size(tria,+1),+1) ;\n\n if (nargin >= +3)\n\n tmid = vert(tria(:,1),:) ...\n + vert(tria(:,2),:) ...\n + vert(tria(:,3),:) ;\n tmid = tmid / +3.0;\n\n for ppos = 1 : length(part)\n\n [stat] = inpoly2( ...\n tmid,node , ...\n PSLG(part{ppos},:)) ;\n\n tnum(stat) = ppos ;\n\n end\n\n%------------------------------------ keep \"interior\" tria's\n tria = tria(tnum>+0,:) ;\n tnum = tnum(tnum>+0,:) ;\n\n end\n\n%------------------------------------ flip for correct signs\n area = triarea(vert,tria) ;\n\n tria(area<0.,:) = ...\n tria(area<0.,[1,3,2]) ;\n\nend\n\n\n\n", "meta": {"author": "dengwirda", "repo": "mesh2d", "sha": "749a81073facc8b5db02e4f7bb0b10c9783cebd3", "save_path": "github-repos/MATLAB/dengwirda-mesh2d", "path": "github-repos/MATLAB/dengwirda-mesh2d/mesh2d-749a81073facc8b5db02e4f7bb0b10c9783cebd3/mesh-util/deltri2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6261448981069556}} {"text": "function [E, N, U] = ch_LLA2ENU(lat, lon, h, lat0, lon0, h0)\n\n% 经纬高 转 ENU\n% lat0, lon0, h0: 起始点经纬高, 经纬度为rad, 高度为m\n% lat, lon, h 终点经纬高, 经纬度为rad, 高度为m\n% E, N ,U 系下增量,单位为m\n\n%精确算法\n% XYZ0 = ch_LLA2ECEF(lat0, lon0, h0);\n% XYZ1 = ch_LLA2ECEF(lat, lon, h);\n% dXYZ = XYZ1 - XYZ0;\n% \n% [~, ~, C_ECEF2ENU, ~]= ch_earth(lat0, lon0, h0);\n% dENU = C_ECEF2ENU * dXYZ;\n% E = dENU(1);\n% N= dENU(2);\n% U = dENU(3);\n \n %近似算法\nR_0 = 6378137; %WGS84 Equatorial radius in meters\nclat = cos(lat0);\nE = (lon - lon0) * clat * R_0;\nN = (lat - lat0) * R_0;\nU = h - h0;\nend\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/lib/geo/ch_LLA2ENU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6261267003966472}} {"text": "% Author:\n% - Mehrtash Harandi (mehrtash.harandi at gmail dot com)\n%\n% This file is provided without any warranty of\n% fitness for any purpose. You can redistribute\n% this file and/or modify it under the terms of\n% the GNU General Public License (GPL) as published\n% by the Free Software Foundation, either version 3\n% of the License or (at your option) any later version.\n\nfunction [outCost,outGrad,covD_Struct] = supervised_WB_CostGrad(U,covD_Struct)\noutCost = 0;\ndF = zeros(size(U));\n\nnPoints = length(covD_Struct.y);\n\nI_r = eye(covD_Struct.r);\nUXU = zeros(covD_Struct.r,covD_Struct.r,nPoints);\ninv_UXU = zeros(covD_Struct.r,covD_Struct.r,nPoints);\nfor tmpC1 = 1:nPoints\n UXU(:,:,tmpC1) = U'*covD_Struct.X(:,:,tmpC1)*U;\n inv_UXU(:,:,tmpC1) = I_r/UXU(:,:,tmpC1);\nend\n\n\n\n\n\nfor i = 1:nPoints\n X_i = covD_Struct.X(:,:,i);\n for j = 1:nPoints\n if (covD_Struct.G(i,j) == 0)\n continue;\n end\n \n X_j = covD_Struct.X(:,:,j);\n switch (covD_Struct.Metric_Flag)\n\n case 1\n %AIRM\n outCost = outCost + covD_Struct.G(i,j)*Compute_AIRM_Metric(UXU(:,:,i) , UXU(:,:,j));\n log_XY_INV = logm(UXU(:,:,i)*inv_UXU(:,:,j));\n \n dF = dF + 4*covD_Struct.G(i,j)*((X_i*U)*inv_UXU(:,:,i) ...\n -(X_j*U)*inv_UXU(:,:,j) )*log_XY_INV;\n case 2\n %Stein metric\n outCost = outCost + covD_Struct.G(i,j)*Compute_Stein_Metric(UXU(:,:,i) , UXU(:,:,j));\n \n X_ij = 0.5*(X_i + X_j);\n dF = dF + covD_Struct.G(i,j)*(2*(X_ij*U)/(U'*X_ij*U) ...\n - (X_i*U)*inv_UXU(:,:,i) - (X_j*U)*inv_UXU(:,:,j));\n otherwise\n error('The metric is not implemented.');\n end %end switch\n \n end\nend\n\n\n\n\n\noutGrad = (eye(size(U,1)) - U*U')*dF;\n\n\nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/SPD_DR_ECCV2014/supervised_WB_CostGrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6261266913871939}} {"text": "function [ x, w ] = rule05 ( n )\n\n%*****************************************************************************80\n%\n%% RULE05 returns the rule of degree 5.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Hong Xiao, Zydrunas Gimbutas,\n% A numerical algorithm for the construction of efficient quadrature\n% rules in two and higher dimensions,\n% Computers and Mathematics with Applications,\n% Volume 59, 2010, pages 663-676.\n%\n% Parameters:\n%\n% Input, integer N, the number of nodes.\n%\n% Output, real X(2,N), the coordinates of the nodes.\n%\n% Output, real W(N), the weights.\n%\n xs = [ ...\n 0.1775868202077551E-01,-.1775868202077539E-01, ...\n 0.7788710544649639,-.7788710544649639, ...\n -.7703781288541645,0.7703781288541645, ...\n -.7490353914168658D-33 ];\n ys = [ ...\n -.9659285494001192,0.9659285494001192, ...\n -.5715708301251639,0.5715708301251639, ...\n -.5829672991828014,0.5829672991828014, ...\n 0.1356144833394667D-33 ];\n ws = [ ...\n 0.2246199725165690,0.2246199725165690, ...\n 0.3901817339168917,0.3901817339168917, ...\n 0.3953508381187504,0.3953508381187504, ...\n 0.8081220356417684 ];\n\n x(1,1:n) = xs(1:n);\n x(2,1:n) = ys(1:n);\n w(1:n) = ws(1:n);\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/square_arbq_rule/rule05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6259154411112806}} {"text": "function [dpsi, deps] = nut2000_lp (t)\n\n% low precison nutation based on iau 2000a\n\n% this function evaluates a short nutation series and returns approximate\n% values for nutation in longitude and nutation in obliquity for a given\n% tdb julian date. in this mode, only the largest 13 terms of the iau 2000a\n% nutation series are evaluated.\n\n% input\n\n% t = tdb time in julian centuries since j2000.0\n\n% output\n\n% dpsi = nutation in longitude in arcseconds\n\n% deps = nutation in obliquity in arcseconds\n\n% note: in low-accuracy mode, max error in dpsi < 0.05 arcsec,\n% max error in deps < 0.02 arcsec, average error about 1/4 of max.\n\n% ported from NOVAS 3.0\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% largest 13 terms of iau 2000a nutation series, with precision\n% of coefficients truncated\n\nx = [0.0, 0.0, 0.0, 0.0, 1.0, -17.2064,-0.01747, 9.2052, 0.00091; ...\n 0.0, 0.0, 2.0,-2.0, 2.0, -1.3171, -0.00017, 0.5730, -0.00030; ...\n 0.0, 0.0, 2.0, 0.0, 2.0, -0.2276, -0.00002, 0.0978, -0.00005; ...\n 0.0, 0.0, 0.0, 0.0, 2.0, 0.2075, 0.00002, -0.0897, 0.00005; ...\n 0.0, 1.0, 0.0, 0.0, 0.0, 0.1476, -0.00036, 0.0074, -0.00002; ...\n 0.0, 1.0, 2.0,-2.0, 2.0, -0.0517, 0.00012, 0.0224, -0.00007; ...\n 1.0, 0.0, 0.0, 0.0, 0.0, 0.0711, 0.00001, -0.0007, 0.00000; ...\n 0.0, 0.0, 2.0, 0.0, 1.0, -0.0387, -0.00004, 0.0201, 0.00000; ...\n 1.0, 0.0, 2.0, 0.0, 2.0, -0.0301, 0.00000, 0.0129, -0.00001; ...\n 0.0,-1.0, 2.0,-2.0, 2.0, 0.0216, -0.00005, -0.0096, 0.00003; ...\n 0.0, 0.0, 2.0,-2.0, 1.0, 0.0128, 0.00001, -0.0069, -0.00000; ...\n -1.0, 0.0, 2.0, 0.0, 2.0, 0.0123, 0.00000, -0.0053, 0.00000; ...\n -1.0, 0.0, 0.0, 2.0, 0.0, 0.0157, 0.00000, -0.0001, 0.00000];\n\n% transpose x matrix\n\nx = x';\n\n% ----------------------------------------------------\n% remaining terms all have amplitudes < 0.01 arcsecond\n% ----------------------------------------------------\n\n% computation of fundamental arguments\n\n[el, elp, f, d, om] = funarg (t);\n\ndpsi = 0.0d0;\n\ndeps = 0.0d0;\n\n% sum nutation series terms\n\nfor i = 13:-1:1\n\n arg = x(1, i) * el ...\n + x(2, i) * elp ...\n + x(3, i) * f ...\n + x(4, i) * d ...\n + x(5, i) * om;\n\n dpsi = (x(6, i) + x(7, i) * t) * sin(arg) + dpsi;\n\n deps = (x(8, i) + x(9, i) * t) * cos(arg) + deps;\n\nend\n\n% add in out-of-phase component of principal (18.6-year) term\n% (to avoid small but long-term bias in results)\n\ndpsi = dpsi + 0.0033d0 * cos(om);\n\ndeps = deps + 0.0015d0 * sin(om);\n\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/novas/nut2000_lp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.6258850879669164}} {"text": "function d = dirac(f, varargin)\n%DIRAC Dirac delta function.\n% D = DIRAC(F) returns a CHEBFUN D which is zero on the domain of the CHEBFUN F\n% except at the simple roots of F, where it is infinite.\n%\n% DIRAC(F, N) is the nth derivative of DIRAC(F).\n%\n% DIRAC(F) is not defined if F has a zero of order greater than one within the\n% domain of F.\n%\n% If F has break-points, they should not coincide with the roots of F. However,\n% F can have simple roots at either end points of its domain.\n%\n% See also HEAVISIDE.\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 argument:\nif ( isempty(f) )\n d = f;\n return\nend\n\n% Deal with quasimatrices:\nif ( numColumns(f) > 1 )\n f = cheb2cell(f);\n for k = 1:numel(f)\n f{k} = dirac(f{k}, varargin{:});\n end\n d = horzcat(f{:});\n return\nend\n\n% Handle the case for derivatives of delta function:\nif ( nargin > 1 )\n if ( nargin > 2 )\n error('CHEBFUN:CHEBFUN:dirac:dirac', 'Too many input arguments.');\n end\n \n % Order of the derivative of dirac delta function:\n n = varargin{1};\n if ( ~isnumeric(n) || n < 0 || round(n) ~= n || ~isscalar(n) )\n error('CHEBFUN:CHEBFUN:dirac:dirac', ...\n 'Order of the derivative must be be a non-negative integer.');\n end\n \n if ( n == 0 ) % Trivial case\n d = dirac(f);\n return\n else\n d = diff(dirac(f), n); \n return\n end\nend\n \n% Set a tolerance and get the domain of f:\ntol = eps;\ndom = f.domain;\na = dom(1);\nb = dom(end);\nvscl = vscale(f);\n\n% Extract the 'normal' roots of f:\nr = roots(f, 'nojump', 'nozerofun');\nr = sort(r(:));\n\n% Check roots at the end points of f:\nif ( isempty(r) )\n % If there are no roots, still check roots at the end points:\n if ( abs(feval(f, a, 'right')) < 100*tol*vscl )\n rootA = 1;\n r = [r; a];\n else\n rootA = 0;\n end\n \n if ( abs(feval(f, b, 'left')) < 100*tol*vscl )\n rootB = 1;\n r = [r; b];\n else\n rootB = 0;\n end \nelse \n % If there are roots, check if they are at the end points:\n if ( r(1) > a )\n rootA = 0;\n elseif ( abs(feval(f, a, 'right')) < 100*tol*vscl )\n rootA = 1;\n if ( r(1) ~= a )\n r = [a ; r];\n end\n end\n if ( r(end) < b )\n rootB = 0;\n elseif ( abs(feval(f, b, 'left')) < 100*tol*vscl )\n rootB = 1;\n if ( r(end) ~= b )\n r = [r ; b];\n end\n end\nend\n\n% Initialize a zero CHEBFUN:\nd = chebfun(0, [a, b]);\n\n% If there is no root of F within the domain or at the end points, return with a\n% zero CHEBFUN:\nif ( isempty( r ) )\n return\nend\n\n% Check if any of the roots is not simple by looking at the derivative of F:\nfp = diff(f);\nfpVals = feval(fp, r);\n \n% Check root order for interior break-points:\nif ( any(abs(fpVals) < 100*tol*vscale(fp)) )\n error('CHEBFUN:CHEBFUN:dirac:dirac', ...\n 'Function has a root which is not simple');\nelse\n % Place deltas with appropriate scaling at interior roots.\n deltaMag = 1./abs(fpVals);\nend\n\n% Use half of the strength if there is a root at the end point of the\n% domain of the input CHEBFUN and update the pointValues:\npointValues = [0; 0];\nif ( rootA )\n deltaMag(1) = deltaMag(1)/2;\n pointValues(1) = sign(deltaMag(1))*inf;\nend\nif ( rootB )\n deltaMag(end) = deltaMag(end)/2;\n pointValues(2) = sign(deltaMag(end))*inf;\nend\n\n% Call the DELTAFUN constructor directly:\ndata.deltaMag = deltaMag.';\ndata.deltaLoc = r.';\nd.funs{1} = deltafun(d.funs{1}, data);\nd.pointValues = pointValues;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/dirac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6258500437719908}} {"text": "function [flag, t, lambda, S] = ray_polygon_intersect(o,d,V,E)\n% RAY_POLYGON_INTERSECT 2D Ray/polygon intersection\n% \n% [flag, t, lambda] = ray_polygon_intersect(o,d,V,E)\n%\n% Input:\n% o 2D vector ray origin.\n% d 2D vector ray direction.\n% V #V by 2 list of vertex positions\n% E #E by 2 list of edge indices\n% Output:\n% flag #E list of bools: (false) Reject, (true) Intersect.\n% t #E list of distances from the ray origin.\n% lambda #E list of parameter of hit between E(:,1) and E(:,2)\n% S #E by #o list of signs\n%\n\n epsilon = eps;%0.00001;\n\n assert(size(V,2) == 2);\n assert(size(E,2) == 2);\n % number of edges \n m = size(E,1);\n %assert(numel(d) == 2);\n\n \n p1 = V(E(:,1),:);\n p2 = V(E(:,2),:);\n % edge vectors from 1 to 2\n e12 = p2-p1;\n % perpendiculars of edge vectors\n pe12 = perp(e12);\n \n \n if numel(d) == 2 && numel(o) == 2\n % make direction a row vector\n d = reshape(d,1,2);\n %d = normalizerow(d);\n d = d ./ sqrt(sum(d.^2,2));\n assert(numel(o) == 2);\n % make origin a row vector\n o = reshape(o,1,2);\n % p1 minus o\n p1mo = plusrow(p1,-o);\n % pe12 dot d\n pe12dd = dotrow(pe12,d);\n % perp d\n pd = perp(d);\n % project to edges\n % http://objectmix.com/graphics/132701-ray-line-segment-intersection-2d.html\n t = dot2(pe12,p1mo)./pe12dd;\n lambda = dotrow(plusrow(-p1,o+d),pd)./dotrow(e12,pd);\n %lambda = dotrow(perp(d),p1mo)./pe12dd;\n flag = true(m,1);\n flag(lambda > 1) = 0;\n flag(lambda < 0) = 0;\n flag(t < 0) = 0;\n else\n d = normalizerow(d);\n pd = perp(d);\n d = permute(d,[3 2 1]);\n pd = permute(pd,[3 2 1]);\n o = permute(o,[3 2 1]);\n p1mo = p1-o;\n pe12dd = sum(pe12.*d,2);\n % project to edges\n t = sum(pe12.*p1mo,2)./pe12dd;\n lambda = sum((o+d-p1).*pd,2)./sum(e12.*pd,2);\n n = max(size(o,3),size(d,3));\n flag = true(m,n);\n flag(lambda > 1) = 0;\n flag(lambda < 0) = 0;\n flag(t < 0) = 0;\n t = squeeze(t);\n S = sign(squeeze(pe12dd));\n end\n \n function u = perp(v)\n % [x,y] = [y,-x]\n u = [v(:,2),-v(:,1)];\n end\n \n function r = dot2(a,b)\n % Optimizes r = dot(a,b,2), that is it computes dot products per row\n % Faster than dot if I know that I'm calling it correctly\n r = sum(a.*b,2);\n end\n \n function r = dotrow(a,b)\n % Computes dot product of rows in a against b.\n % optimizes r = dot(a,repmat(b,size(a,1),1),2)\n r = a(:,1).*b(1,1) + a(:,2).*b(1,2);\n end\n \n function r = plusrow(a,b)\n % Computes sum rows in a with b.\n % optimizes r = a + repmat(b,size(a,1),1)\n r = [a(:,1)+b(1,1) a(:,2)+b(1,2)];\n end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/ray_polygon_intersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6258140996122008}} {"text": "function F = erfc(F, varargin)\n%ERFC Complementary error function of a CHEBFUN.\n% ERFC(X) is the complementary error function of the real-valued CHEBFUN X.\n% The complementary error function is defined as:\n% ERFC(X)(s) = 2/sqrt(pi) * integral from X(s) to inf of exp(-t^2) dt.\n% = 1 - ERF(X)(s).\n%\n% See also ERF, ERFCX, ERFINV, ERFCINV.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Input must be real:\nif ( ~isreal(F) )\n error('CHEBFUN:CHEBFUN:erfc:notreal', 'Input must be real.');\nend\n\n% Call the compose method:\nF = compose(F, @erfc, 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/@chebfun/erfc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6258140945387486}} {"text": "function u = poisson( f, varargin )\n%POISSON Fast Poisson solver for the rectangle.\n% POISSON(F) solves laplacian(U) = F on the domain of F with zero\n% Dirichlet boundary conditions. That is, U satisfies\n%\n% U_{x,x} + U_{y,y} = F, on [a,b]x[c,d], with U = 0 on boundary\n%\n% The equation is solved using an adaptively determined discretization\n% size.\n%\n% POISSON(F, G) solves using Dirichlet boundary conditions given by G. G\n% can be a scalar, a function handle, or any chebfun2 object satisfying\n% the Dirichlet data.\n%\n% POISSON(F, G, N) is the same as POISSON(F, G), but uses an N x N tensor\n% product discretization to solve the equation.\n%\n% POISSON(F, G, M, N) is the same as POISSON(F, G, N), but with an M x N\n% tensor product discretization, where N is the number of coeffcieints in\n% the x-direction and M is the number in the y-direction.\n%\n% POISSON(F, G, N, METHOD) or POISSON(F, G, M, N, METHOD) is the same as\n% POISSON(F, G, N) or POISSON(F, G, M, N), respectively, except the\n% underlying matrix equation is solved with METHOD. Available methods\n% are:\n%\n% 'adi' - alternating direction implicit method\n% 'fadi' - factored alternating direction implicit method\n% 'bartelsStewart' - Bartels-Stewart algorithm\n%\n% If METHOD is not supplied, then this command selects one (based on the\n% discretization size and the rank of the righthand side).\n%\n% EXAMPLE:\n% f = chebfun2( @(x,y) 1 + 0*x, [-1 2 0 1]);\n% u = chebfun2.poisson(f);\n% plot(u)\n%\n% See also DISKFUN/POISSON, SPHEREFUN/POISSON.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% DEVELOPER'S NOTE:\n%\n% METHOD: Spectral method (in coefficient space). We use a C^{(3/2)} basis\n% to discretize the equation, resulting in a discretization of the form\n% AX + XA = F, where A is a symmetric tridiagonal matrix.\n%\n% LINEAR ALGEBRA: Matrix equations. The matrix equation is solved by the\n% alternating direction implicit (ADI) method.\n%\n% SOLVE COMPLEXITY: O(M*N*log(MAX(M,N))*log(1/eps)) with M*N = total\n% degrees of freedom.\n%\n% AUTHORS: Dan Fortunato (dan.fortunato@gmail.com)\n% Alex Townsend (townsend@cornell.edu)\n%\n% The fast Poisson solver is based on:\n%\n% D. Fortunato and A. Townsend, Fast Poisson solvers for spectral methods,\n% Submitted, 2017.\n\n% Solve for u on the same domain as f, adjust diffmat to include scaling:\ndom = f.domain;\nscl_x = (2/(dom(2)-dom(1)))^2;\nscl_y = (2/(dom(4)-dom(3)))^2;\n\n% Not enough input arguments so we call chebop2 to adaptively select a\n% discretization size:\nif ( nargin == 1 )\n\n % Call is POISSON(F) so set G = 0 and use chebop2 to determine the\n % discretization size:\n g = 0;\n N = chebop2.setupLaplace( f.domain );\n N.bc = g;\n u = N \\ f;\n return\n\nelseif ( nargin == 2 )\n\n % Call is POISSON(F, G) so use chebop2 to determine the discretization\n % size:\n g = varargin{1};\n if ( ~isa(g, 'chebfun2') )\n g = chebfun2(g, f.domain);\n end\n N = chebop2.setupLaplace( f.domain );\n % Note: chebfun2/subsref (e.g. g(-1,:)) does not work here, so we use\n % feval instead. Is this a bug?\n N.lbc = feval(g, f.domain(1), ':');\n N.rbc = feval(g, f.domain(2), ':');\n N.dbc = feval(g, ':', f.domain(3));\n N.ubc = feval(g, ':', f.domain(4));\n u = N \\ f;\n return\n\nend\n\n% We are given a discretization size. It's solve time!\ng = varargin{1};\nm = varargin{2};\nmethod = '';\nif ( nargin == 3 )\n % Call must be POISSON(F, G, N) so employ an NxN discretization:\n n = m; % square discretization\nelseif ( nargin == 4 )\n\n % The user typed one of the following:\n % POISSON(F, G, N, METHOD) or POISSON(F, G, M, N).\n\n if ( ischar( varargin{3} ) )\n % Call is POISSON(F, G, N, METHOD):\n method = varargin{3};\n n = m; % square discretization\n else\n % Call is POISSON(F, G, M, N):\n n = varargin{3};\n end\n\nelseif ( nargin == 5 )\n\n % We are given a discretization size and a method. It's solve time!\n % Call must be POISSON(F, G, M, N, METHOD).\n n = varargin{3};\n method = varargin{4};\n\nelse\n error('CHEBFUN2:POISSON:NARGIN', ...\n 'Too many input arguments to chebfun2.poisson().');\nend\n\n% Set the error tolerance for solve:\ntol = chebfun2eps();\n\n% Compute the Chebyshev coefficients of rhs:\n[Cf, Df, Rf] = coeffs2(f, m, n);\n\n% Solver only deals with zero homogeneous Dirichlet conditions. Therefore,\n% if nonzero Dirichlet conditions are given, we solve lap(u) = f with u|bc = g\n% as u = v + w, where v|bc = g, and lap(w) = f - lap(v), w|bc = 0:\nif ( isa(g, 'double') || isa(g, 'chebfun2') || isa(g, 'function_handle') )\n\n % Make double or function handle into chebfun2:\n if ( isa(g, 'double') || isa(g, 'function_handle') )\n g = chebfun2(g, f.domain);\n end\n\n if ( g.domain == f.domain )\n % Adjust the rhs, if nonzero:\n lapg = lap(g);\n if ( ~iszero( lapg ) )\n [Cg, Dg, Rg] = coeffs2(lapg, m, n);\n Cf = [Cf Cg];\n Z = zeros(size(Df,1),size(Dg,1));\n Df = [Df Z ; Z' -Dg];\n Rf = [Rf Rg];\n end\n else\n error('CHEBFUN2:POISSON:BC', ...\n 'Dirichlet data should be on the same domain as F.');\n end\n\nelse\n error('CHEBFUN2:POISSON', ...\n 'Dirichlet data needs to be given as a scalar or function.')\nend\n\n% Convert rhs to C^{(3/2)} coefficients:\nCf = cheb2ultra( Cf );\nRf = cheb2ultra( Rf );\n\n% Construct M, the multiplication matrix for (1-x^2) in the C^(3/2) basis\njj = (0:n-1)';\ndsub = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj+2);\ndsup = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj);\nd = -dsub - dsup;\nMn = spdiags([dsub d dsup], [-2 0 2], n, n);\n% Construct D^{-1}, which undoes the scaling from the Laplacian identity\ninvDn = spdiags(-1./(jj.*(jj+3)+2), 0, n, n);\nTn = scl_y * invDn * Mn;\n\njj = (0:m-1)';\ndsub = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj+2);\ndsup = -1./(2*(jj+3/2)).*(jj+1).*(jj+2)*1/2./(1/2+jj);\nd = -dsub - dsup;\nMm = spdiags([dsub d dsup], [-2 0 2], m, m);\ninvDm = spdiags(-1./(jj.*(jj+3)+2), 0, m, m);\n\n% Construct T = D^{-1} * M:\nTm = scl_x * invDm * Mm;\nCf = invDm * Cf;\nRf = invDn * Rf;\n\nswitch lower(method)\n\n case 'bartelsstewart'\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%% Bartels-Stewart method %%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Solve TmX + XTn' = F using Bartels-Stewart, which requires O(n^3)\n % operations:\n\n X = chebop2.bartelsStewart(Tm, eye(n), eye(m), Tn, Cf*Df*Rf.', 0, 0);\n\n % Convert back to Chebyshev\n X = ultra1mx2cheb( ultra1mx2cheb( X ).' ).';\n u = chebfun2( X, f.domain, 'coeffs' );\n\n case {'adi', 'fadi', ''}\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %%%%%%% Alternating Direction Implicit method %%%%%%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Solve TmX + XTn' = F using ADI, which requires\n % O(n^2log(n)log(1/eps)) operations:\n\n % An ADI method will be used (either given by the user, or selected\n % by us.)\n\n % Compute ADI shifts\n a = -4/pi^2 * scl_y;\n b = -39*n^-4 * scl_y;\n c = 39*m^-4 * scl_x;\n d = 4/pi^2 * scl_x;\n [p, q] = chebop2.adiShifts(a, b, c, d, tol);\n\n if ( isempty(method) )\n % Let's go and pick a good method to use:\n % Test if we should use ADI or FADI:\n rho = size(Cf,2); % Rank of rhs\n adi_test = ( min(m,n) < rho*numel(p)/2 ); % Worth doing FADI?\n if ( adi_test )\n method = 'adi';\n else\n method = 'fadi';\n end\n end\n\n % Solve matrix equation:\n if ( strcmpi(method, 'adi') )\n % Run the ADI method:\n X = chebop2.adi(Tm, -Tn', Cf*Df*Rf.', p, q );\n\n % Convert back to Chebyshev\n X = ultra1mx2cheb( ultra1mx2cheb( X ).' ).';\n u = chebfun2( X, f.domain, 'coeffs' );\n\n else\n % Run the FADI method:\n [UX, DX, VX] = chebop2.fadi(Tm, -Tn, Cf*Df, Rf, p, q);\n\n % Convert back to Chebyshev:\n UX = ultra1mx2cheb(UX);\n VX = ultra1mx2cheb(VX);\n\n UX = chebfun(UX, dom(3:4), 'coeffs');\n VX = chebfun(VX, dom(1:2), 'coeffs');\n u = chebfun2();\n u.cols = UX;\n u.rows = VX;\n u.pivotValues = 1./diag(DX);\n u.domain = dom;\n end\n\n otherwise\n error('CHEBFUN2:POISSON:SOLVER', ...\n 'Method supplied to chebfun2.poisson() is not recognized.');\nend\n\n% Add back in the boundary data:\nu = u + g;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%% CONVERSION CODES %%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction X = cheb2ultra( X )\n% CHEB2ULTRA Convert vector of Chebyshev coefficients to C^(3/2).\n%\n% CHEB2ULTRA(X) applies the conversion to each column of X if X is a\n% matrix.\n\n% First convert the matrix of Chebyshev coefficients to a matrix of\n% Legendre coefficients:\nm = size( X, 1 );\nif ( m <= 10000 ) % Determined experimentally\n S = cheb2leg_mat( m );\n X = S * X;\nelse\n X = cheb2leg( X );\nend\n\n% Now, convert the matrix of Legendre coefficients to a matrix of\n% ultraspherical coefficients:\nS = leg2ultra_mat( m );\nX = S * X;\n\nend\n\nfunction X = ultra1mx2cheb( X )\n% ULTRA1MX2CHEB Convert vector of (1-x^2)C^(3/2) coefficients to\n% Chebyshev.\n%\n% ULTRA1MX2CHEB(X) applies the conversion each column of X if X is\n% matrix.\n\n% First, convert the matrix of (1-x^2)C^(3/2)(x) coefficients\n% to Legendre coefficients:\nm = size( X, 1 );\n\nS = ultra1mx2leg_mat( m );\nX = S * X;\n\n% Now, convert the matrix of Legendre coefficient to a matrix of Chebyshev\n% coefficients:\nif ( m <= 10000 ) % Determined experimentally\n S = leg2cheb_mat( m );\n X = S * X;\nelse\n X = leg2cheb( X );\nend\n\nend\n\nfunction S = leg2ultra_mat( n )\n% LEG2ULTRA_MAT Conversion matrix from Legendre coefficients to C^(3/2).\n%\n% Given coefficients in the Legendre basis the C^(3/2) coefficients\n% can be computed via\n%\n% c = rand(10, 1); % Legendre coefficients\n% S = leg2ultra_mat( length(c) ); % conversion matrix\n% d = S * c; % C^(3/2) coefficients\n\n% Alex Townsend, 5th May 2016\n\nlam = 1/2;\ndg = lam./(lam + (2:n-1))';\nv = [1 ; lam./(lam+1) ; dg];\nw = [0 ; 0 ; -dg];\nS = spdiags( [v w], [0 2], n, n );\n\nend\n\nfunction S = ultra1mx2leg_mat( n )\n% ULTRA1MX2LEG_MAT Conversion matrix for (1-x^2)C^(3/2) to Legendre.\n%\n% Given coefficients in the (1-x^2)C^(3/2) basis the Legendre coefficients\n% can be computed via\n%\n% c = rand(10, 1); % (1-x^2)C^(3/2) coefficients\n% S = ultra1mx2leg_mat( length(c) ); % conversion matrix\n% c_leg = S * c; % Legendre coefficients\n%\n\n% Alex Townsend, 5th May 2016\n\nd = ones(n, 1);\nS = spdiags(((1:n).*(2:(n+1))./2./(3/2:n+1/2))', 0, n, n);\nS = spdiags( [d,-d], [0,-2], n, n ) * S;\n\nend\n\nfunction L = cheb2leg_mat( N )\n% CHEB2LEG_MAT Construct the cheb2leg conversion matrix.\n\n% This for-loop is a faster and more accurate way of doing:\n% Lambda = @(z) exp(gammaln(z+1/2) - gammaln(z+1));\n% vals = Lambda( (0:2*N-1)'/2 );\nvals = zeros(2*N,1);\nvals(1) = sqrt(pi);\nvals(2) = 2/vals(1);\nfor i = 2:2:2*(N-1)\n vals(i+1) = vals(i-1)*(1-1/i);\n vals(i+2) = vals(i)*(1-1/(i+1));\nend\n\nL = zeros(N, N);\nfor j = 0:N-1\n for k = j+2:2:N-1\n L(j+1, k+1) = -k*(j+.5)*(vals((k-j-2)+1)./(k-j)).*(vals((k+j-1)+1)./(j+k+1));\n end\nend\nc = sqrt(pi)/2;\nfor j = 1:N-1\n L(j+1, j+1) = c./vals( 2*j+1 );\nend\nL(1,1) = 1;\n\nend\n\nfunction M = leg2cheb_mat( N )\n% LEG2CHEB_MAT Construct the leg2cheb conversion matrix.\n\n% This for-loop is a faster and more accurate way of doing:\n% Lambda = @(z) exp(gammaln(z+1/2) - gammaln(z+1));\n% vals = Lambda( (0:2*N-1)'/2 );\nvals = zeros(2*N,1);\nvals(1) = sqrt(pi);\nvals(2) = 2/vals(1);\nfor i = 2:2:2*(N-1)\n vals(i+1) = vals(i-1)*(1-1/i);\n vals(i+2) = vals(i)*(1-1/(i+1));\nend\n\nM = zeros(N, N);\nfor j = 0:N-1\n for k = j:2:N-1\n M(j+1, k+1) = 2/pi*vals((k-j)+1).*vals((k+j)+1);\n end\nend\nM(1,:) = .5*M(1,:);\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun2/poisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6257783214078536}} {"text": "function [FutureCF AccruedInt] = czbondfuturecf(CouponRate, Issue, Maturity, Settle, Basis, Notional)\n% =========================================================================\n% CZBONDFUTURECF generates future (and current - settlement date) cash flows,\n% cash flow dates and cash flow time fraction according to day count basis (30E/360, Actual/360)\n% for Czech Government Bonds. Further, it calculates accrued interest.\n%\n% [Yield AccruedInt] = czgbfuturecf(CouponRate, Issue, Maturity,...\n% Settle, Basis, Notional)\n% \n% INPUTS: \n% CouponRate - Coupon rate in decimal form\n% Issue - Issue Date in serial date number\n% (NOTE: convert date string using DATENUM)\n% Maturity - Maturity Date in serial date number\n% Settle - Settlment Date in serial date number\n% \n% OPTIONAL INPUT:\n% Notional - Notional of the bond (default is 100)\n% Basis - Day-count basis\n% 1 - 30E/360 (default)\n% 2 - Actual/360 \n% \n% OUTPUT: \n% FutureCF - Future cash flow matrix \n% - 1st row, nominal cash flows\n% - 2nd row, cash flow dates\n% - 3rd row, cash flow time fraction measured in years\n% \n% AccruedInt - Accrued interest since last coupon\n% \n% NOTE: \n% It doesn't work take ex-coupon date into account\n% Normally, Czech Government Bonds are traded according to 30E/360 convention! \n% \n% USES: czbondcf\n% \n% Kamil Kladivko \n% email: kladivko@gmail.com\n% December 2010 \n% Cite as: \n% Kladivko Kamil (2010). The Czech Treasury Yield Curve from 1999 to the Present, \n% Czech Journal of Economics and Finance, 60(4): 307-335\n% =========================================================================\n\n if nargin < 4, error('Need at least 4 inputs'); end\n if nargin == 4, Basis = 0; Notional = 100; end \n if nargin == 5, Notional = 100; end \n if all(Basis ~= [1, 2])\n warning('Unknown code for day count convention. Using 30E/360');\n Basis = 1;\n end\n % Generates CZGB cash flows\n CF = czbondcf(CouponRate, Issue, Maturity, Basis, Notional); \n TempCF = CF(:, 2:end); % Don't want first negative CF (notional of the bond)\n % Pick only furture and current (Settlment date) cash flows\n [SettYr, SettMo, SettDay] = datevec(Settle); \n FutureCF = TempCF(:, TempCF(2, :) >= datenum(Settle));\n % Find last cash flow date before settlment\n [junk FutureCFcount] = size(FutureCF);\n AccrualDate = CF(2, end-FutureCFcount); \n % Acrrued Interest\n switch Basis\n case 1 % 30E/360\n [AccrualYr, AccrualMo, AccrualDay] = datevec(AccrualDate);\n if SettDay == 31, SettDay = 30; end; if AccrualDay == 31, AccrualDay = 30; end\n DaysCount = 360*(SettYr - AccrualYr) + 30*(SettMo - AccrualMo) + (SettDay - AccrualDay);\n AccruedInt = CouponRate*Notional*DaysCount/360;\n case 2 % Actual/360; \n DaysCount = datenum(Settle) - AccrualDate;\n AccruedInt = CouponRate*Notional*DaysCount/360;\n end\n % Time Factor\n switch Basis\n case 1 % 30E/360\n DaysCount = zeros(1, FutureCFcount);\n for i = 1:FutureCFcount\n [NxtYr, NxtMo, NxtDay] = datevec(FutureCF(2,i));\n if NxtDay == 31, NxtDay = 30; end\n DaysCount(i) = 360*(NxtYr - SettYr) + 30*(NxtMo - SettMo) + (NxtDay - SettDay); \n end\n TimeFactor = DaysCount./360;\n case 2 % Actual/360; \n DaysCount = FutureCF(2,:) - datenum(Settle); \n TimeFactor = DaysCount./360; \n end \n FutureCF = [FutureCF; TimeFactor]; \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/37301-estimation-of-nelson-siegel-and-svensson-models/fnc/czbondfuturecf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6257771744436741}} {"text": "function pos = cartPolePosition(z,p)\n% pos = cartPolePosition(z,p)\n%\n% This function computes the position of the cart and the pole, given the\n% state of the system\n%\n% INPUTS:\n% z = [4, n] = [x;q;dx;dq] = state of the system\n% p = parameter struct\n% .g = gravity\n% .m1 = cart mass\n% .m2 = pole mass\n% .l = pendulum length\n% OUTPUTS:\n% pos = [4, n] = [x1;y1;x2;y2]; = position of [cart; pole]\n%\n\n%%%% unpack the state\nx = z(1,:); %Cart position (Not used in dynamics)\nq = z(2,:); % pendulum (pole) angle, measure from gravity vector\n\n%%%% Unpack the physical parameters\nl = p.l; %Pendulum length\n\n%%%% Position of the cart:\nx1 = x;\ny1 = zeros(size(x));\n\n%%%% Position of the pole:\nx2 = x1 + l*sin(q);\ny2 = y1 - l*cos(q);\n\n%%%% Pack up position vector:\npos = [x1;y1;x2;y2];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/MatlabAnimationTutorial/4_simple_animation/cartPolePosition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6257771690243743}} {"text": "function [ZWD] = saast_wet(T, H, h)\n\n% SYNTAX:\n% [ZWD] = saast_wet(T, H, h);\n%\n% INPUT:\n% T = air temperature\n% H = humidity\n% h = orthometric height\n%\n% OUTPUT:\n% ZWD = Zenith Wet Delay\n%\n% DESCRIPTION:\n% Zenith Wet Delay (ZWD) computation by Saastamoinen model.\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by:\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n% Convert C -> K\nT = T + 273.15;\n\n%height correction\nH = H * exp(-0.0006396 * h);\n\n% Convert humidity\nH = H./100;\n\nc = -37.2465 + 0.213166 * T - 2.56908 * (10^-4) * (T.^2);\ne = H .* exp(c);\n\n%ZWD (Saastamoinen model)\nZWD = 0.0022768 * (((1255 ./ T) + 0.05) .* e);\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/atmosphere/saast_wet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6257771640649111}} {"text": "% Modelling Nonlinear Wave Propagation Example\n%\n% This example describes the characteristics of the nonlinearity\n% encapsulated by the first-order k-Wave simulation functions. \n%\n% author: Bradley Treeby\n% date: 8th December 2011\n% last update: 6th September 2013\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% DEFINE SIMULATION PROPERTIES\n% =========================================================================\n\n% define the properties used in the simulation\np0 = 5e6; % source pressure [Pa]\nc0 = 1500; % sound speed [m/s]\nrho0 = 1000; % density [kg/m^3]\nalpha_0 = 0.25; % absorption coefficient [dB/(MHz^2 cm)]\nsigma = 1; % shock parameter\nsource_freq = 1e6; % frequency [Hz]\npoints_per_wavelength = 50; % number of grid points per wavelength at f0\nwavelength_separation = 15; % separation between the source and detector\npml_size = 64; % PML size\nCFL = 0.25; % \n\n% compute corresponding grid spacing\ndx = c0/(points_per_wavelength*source_freq); % [m]\n\n% compute corresponding grid size\nNx = wavelength_separation*points_per_wavelength + 20;\n\n% =========================================================================\n% RUN SIMULATION\n% =========================================================================\n\n% create the computational grid\nkgrid = makeGrid(Nx, dx);\n\n% assign the properties of the propagation medium\nmedium.sound_speed = c0;\nmedium.density = rho0;\nmedium.alpha_power = 2;\nmedium.alpha_coeff = alpha_0;\nmedium.alpha_mode = 'no_dispersion';\n\n% extract the maximum frequency supported by the grid\nf_max = min(medium.sound_speed)/(2*dx); % [Hz]\n\n% define a single source element\nsource.p_mask = zeros(Nx, 1);\nsource.p_mask(10) = 1;\n\n% define a single sensor position an integer number of wavelengths away\nsensor.mask = zeros(Nx, 1);\nx_px = wavelength_separation*points_per_wavelength;\nsensor.mask(10 + x_px) = 1;\nx = x_px*dx;\n\n% compute the nonlinearity coefficient required to give the correct shock\n% parameter\nmach_num = p0/(rho0*c0.^2);\nk = 2*pi*source_freq/c0;\nBonA = 2*(sigma/(mach_num*k*x) - 1);\nmedium.BonA = BonA;\n\n% set the simulation options\ninput_args = {'PlotFreq', 20, 'PlotScale', [-p0*1.05, p0*1.05],...\n 'PMLInside', false, 'PMLSize', pml_size, 'PMLAlpha', 1.5};\n\n% compute points per temporal period\npoints_per_period = round(points_per_wavelength / CFL);\n\n% compute corresponding time spacing\ndt = 1/(points_per_period*source_freq); \n\n% create the time array using an integer number of points per period\nt_end = 25e-6;\nkgrid.t_array = 0:dt:t_end; \n\n% create the source term, offset by dt/2 so there is a point that lands on the axis \nsource.p = p0*sin(2*pi*source_freq*(kgrid.t_array + dt/2));\n\n% run the simulation\nsensor_data = kspaceFirstOrder1D(kgrid, medium, source, sensor, input_args{:});\n\n% extract a single wavelength\nsensor_data = sensor_data((wavelength_separation + 4)*points_per_period:(wavelength_separation + 5)*points_per_period);\n\n% create time axis for mendousse solution\nt_axis = (0:dt:dt*(length(sensor_data) - 1)); \n\n% compute mendousse solution for comparison\np_mendousse = mendousse(x*ones(size(t_axis)), t_axis, source_freq, p0, c0, rho0, BonA, alpha_0);\n\n% =========================================================================\n% VISUALISATION\n% =========================================================================\n\n% plot the time series\nfigure; \nsubplot(2, 1, 1), plot(t_axis*1e6, p_mendousse/1e6, 'k-');\nhold on;\nplot(t_axis*1e6, sensor_data/1e6, 'kx')\nxlabel('Time [\\mus]');\nylabel('Pressure [MPa]');\nlegend('Mendousse', 'k-Wave');\n\n% get the amplitude spectra\n[f, as_mendousse] = spect(p_mendousse, 1/dt);\nf = f./1e6;\nas_kspace = spect(sensor_data, 1/dt);\n\n% extract and plot the data at the harmonics\nsubplot(2, 1, 2);\nfor harm = 1:10\n\n % find index of frequency\n [f_val, f_index] = findClosest(f, harm);\n\n % plot reference\n stem(f_val, as_mendousse(f_index)/1e6, 'Color', 'k', 'Marker', 'o');\n hold on;\n\n % plot simulation\n plot(f_val, as_kspace(f_index)/1e6, 'kx');\n\nend\n\n% annotate the plot\nxlabel('Frequency [MHz]');\nylabel('Amplitude [MPa]');\nlegend('Mendousse', 'k-Wave');\nset(gca, 'XLim', [0.5, 10.5]);", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/examples/example_na_modelling_nonlinearity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6257771640649111}} {"text": "function [soln,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)\n%% STOKESRT0 Stokes equations: the lowest order Raviart-Thomas element in 2D.\n%\n% [soln,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)\n% uses the lowest order of Raviart-Thomas element (RT0) to approximate\n% velocity u and piecewise constant element (P0) to approximate pressure\n% p, repectively.\n%\n% We solve the following equation:\n% - grad div u + curl rot u + grad p = f in \\Omega \n% - div u = 0 in \\Omega \n% u = g on \\Gamma \n%\n% ifem StokesRT0doc\n%\n% See also StokesBDM1B\n%\n% Based on a version by Ming Wang. Revised by Lin Zhong. Discussed with Jie\n% Zhou and Long Chen. Further clean up by Long Chen.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\nif ~exist('option','var'), option = []; end\n\n%% Data structure\nelemunSort = elem;\n[elem,bdFlag] = sortelem(elemunSort,bdFlag);\n[elem2edge,edge] = dofedge(elem);\n[Clambda,area,elemSign] = curlbasis(node,elem);\nN = size(node,1); NT = size(elem,1); NE = size(edge,1); \nNu = NE; Np = NT; Ndof = Nu + Np;\n\n%% Assemble matrices\nt = cputime; % record assemble time\n% Mv: Lumped mass matrix for vertex: P1 element\nvecMv = accumarray([elem(:,1);elem(:,2);elem(:,3)],[area;area;area]/3,[N,1]);\n% invMv = spdiags(1./vecMv,0,N,N);\nMv = spdiags(vecMv,0,N,N);\n\n% Me: Mass matrix for RT0 element\nMe = getmassmatvec(elem2edge,area,Clambda,'RT0');\n\n%invMt: the inverse of Mass matrix for P0 element\ninvMt = spdiags(1./area,0,NT,NT);\n\n% B: negative divergence operator\nB = -icdmat(double(elem2edge),elemSign*[1 -1 1]);\n\n% C: curl operator\nC = icdmat(double(edge),[-1 1]);\n\n% R: weak rot operator\nR = spdiags(1./vecMv,0,N,N)*C'*Me;\n\n% Vector Laplacian\nA = B'*invMt*B + R'*Mv*R;\n\n%% Assemble right hand side\nlocEdge = [2,3; 1 3; 1,2]; % ascend ordering\nfu = zeros(Nu,1);% the right hand side of u\ng = zeros(Np,1); % the right hand side of p\nif ~isfield(pde,'f') || (isfield(pde,'f') && isreal(pde.f) && all(pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order is 3\nend\nif isfield(pde,'f') && ~isempty(pde.f)\n [lambda,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n bt = zeros(NT,3);\n for p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:);\n fp = pde.f(pxy);\n for k = 1:3\n i = locEdge(k,1); j = locEdge(k,2);\n % phi_k = lambda_iClambda_j - lambda_jClambda_i;\n phi_k = lambda(p,i)*Clambda(:,:,j)-lambda(p,j)*Clambda(:,:,i);\n rhs = dot(phi_k,fp,2);\n bt(:,k) = bt(:,k) + w(p)*rhs;\n end\n end\n bt = bt.*repmat(area,1,3);\n fu = accumarray(elem2edge(:),bt(:),[Nu 1]);\nend\nclear pxy fp bt rhs phi_k psi_k\n\n%% Boundary condition and graddiv part of A\n[u,p,ufreeDof,pDof,utbd] = getbdStokesRT0;\nassembleTime = cputime - t;\n\n%% Solve the system of linear equations\n% set up solver type\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 1e5 % Direct solver for small size systems\n solver = 'direct';\n else % Multigrid-type solver for large size systems\n solver = 'mg';\n end\nelse\n solver = option.solver;\nend\n% solve the system\n% get submatrices of ufreeDof\nA0 = A(ufreeDof,ufreeDof);\nB0 = B(:,ufreeDof);\nf0 = fu(ufreeDof);\ng0 = g;\nif strcmp(solver,'direct') && ~isempty(ufreeDof)\n t = cputime;\n bigA = [A0, B0'; ...\n B0, sparse(Np,Np)];\n bigF = [f0; g0];\n bigu = [u; p];\n bigFreeDof = [ufreeDof; Nu+pDof];\n bigu(bigFreeDof) = bigA(1:end-1,1:end-1)\\bigF(1:end-1);\n u = bigu(1:Nu);\n p = bigu(Nu+1:end);\n info.solverTime = cputime - t;\nelseif strcmp(solver,'mg')\n% option.solver = 'vcycle';\n option.solver = 'WCYCLE';\n [u(ufreeDof),p,info] = mgstokesRT0(A0,B0,f0,g0,u,p,node,elemunSort,ufreeDof,option);\nend\n\n%% Post-process\nif length(pDof)~=Np % p is unique up to a constant\n % impose the condition int(p)=0\n c = sum(p.*area)/sum(area);\n p = p - c;\nend\nw = R*u + utbd./vecMv;\npsi = zeros(N,1);\n% compute streamline function\nif isfield(option,'stream') && option.stream\n [As,Ms] = assemblematrix(node,elem);\n [fixedNode,bdEdge,isBdNode] = findboundary(elem,bdFlag);\n freeNode = ~isBdNode;\n rhs = Ms*w;\n streamoption.freeDof = freeNode;\n psi(freeNode) = mg(As(freeNode,freeNode),rhs(freeNode),elemunSort,streamoption);\n % assume u\\cdot n = 0. \nend\n \n%% Output information\ninfo.assembleTime = assembleTime;\n\n%% Output\nsoln = struct('u',u,'p',p,'w',w,'psi',psi);\neqn = struct('A',A0,'B',B0,'Me',Me,'Mv',Mv,'f',f0,'g',g0,...\n 'edge',edge,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesRT0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [u,p,ufreeDof,pDof,utbd] = getbdStokesRT0\n %% Boundary condition of Stokes equation: RT0-P0 elements\n \n % Initial set up\n utbd = zeros(N,1); % the line integral of u on the boundary (u.t, tau)|_\\partial \\Omega\n u = zeros(Nu,1);\n p = zeros(Np,1);\n ufreeDof = (1:Nu)';\n pDof = (1:Np-1)';\n \n if ~exist('bdFlag','var'), bdFlag = []; end\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n if isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n bdFlag = [];\n end\n \n % Find Dirichlet boundary dof: fixedDof and pDof\n isFixedDof = false(Nu,1);\n if ~isempty(bdFlag) \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n Dirichlet = edge(isDirichlet,:);\n isFixedDof(isDirichlet) = true;\n fixedDof = find(isFixedDof);\n ufreeDof = find(~isFixedDof);\n end\n\n % Set up edge sign\n % edgeSign records the inconsistency of asecond orientation and\n % induced orientation for each boundary edges\n edgeSign = ones(NE,1);\n idx = (bdFlag(:,1) ~= 0 ) & (elemSign == -1) ; % the first edge is on boundary\n edgeSign(elem2edge(idx,1)) = -1;\n idx = (bdFlag(:,2) ~= 0 ) & (elemSign == 1) ; % the second edge is on boundary\n edgeSign(elem2edge(idx,2)) = -1;\n idx = (bdFlag(:,3) ~= 0 ) & (elemSign == -1) ; % the third edge is on boundary\n edgeSign(elem2edge(idx,3)) = -1; \n\n % Compute the boundary integral\n if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n % else no bddof or g_D = 0 (no modification needed)\n % 1. Normal component of u is imposed strongly\n if (isnumeric(pde.g_D) && length(pde.g_D) == NE)\n u(fixedDof) = pde.g_D(fixedDof);\n else\n u(fixedDof) = faceinterpolate(pde.g_D,node,edge(fixedDof,:),'RT0');\n end\n % 2. Tangential component of u is imposed weakly\n [lambdagD,wgD] = quadpts1(3);\n nQuadgD = size(lambdagD,1);\n % quadrat = cputime bases 1--3--2\n bdphi = lambdagD;\n ve = node(Dirichlet(:,2),:) - node(Dirichlet(:,1),:);\n ge = zeros(size(Dirichlet,1),2);\n int_left = zeros(size(Dirichlet,1),2);\n int_right = zeros(size(Dirichlet,1),2);\n for pp = 1:nQuadgD\n ppxy = lambdagD(pp,1)*node(Dirichlet(:,1),:) ...\n + lambdagD(pp,2)*node(Dirichlet(:,2),:);\n gDp = pde.g_D(ppxy);\n int_left = int_left + wgD(pp)*gDp*bdphi(pp,1);\n int_right = int_right + wgD(pp)*gDp*bdphi(pp,2);\n end \n ge(:,1) = dot(int_left,ve,2).*edgeSign(fixedDof);\n ge(:,2) = dot(int_right,ve,2).*edgeSign(fixedDof);\n utbd = accumarray(Dirichlet(:), [ge(:,1); ge(:,2)],[N,1]);\n end\n \n % Modify the right hand side\n fu = fu - A*u - Me*(C*(utbd./vecMv));\n g = g - B*u;\n g = g - mean(g);\n end\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/StokesRT0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6257510077527773}} {"text": "function [prob]=mhprob3(cand,lambda,sbar,eps,Finv,n);\n\n\n% compute the first part of the first exponential term\ntemp1=exp(-cand)-exp(-lambda);\n\n% compute the second part of the first exponential term\n% initiate the summation\ntemp2=0;\n% loop over variables\n for jj=1:n\n % if jj=1 (first variable), the part finv*eps_i,t does not exist\n if jj==1\n temp3=(1/sbar(jj,1))*eps(1,1)^2;\n % if any other variable is considered, the term finv*eps_i,t must be taken into account\n else\n temp3=(1/sbar(jj,1))*(eps(1,1)+Finv{jj,1}'*eps(1:jj-1,1))^2;\n end\n % increment the summation\n temp2=temp2+temp3;\n end\n% compute the (log of the) first exponential term\nterm1=-0.5*temp1*temp2;\n\n% next compute the (log of the) second exponential term\nterm2=-(n/2)*(cand-lambda); \n\n% compute the sum of the two terms to obtain the log of the acceptance prob\n% and exponentiate it to obtain the actual acceptance prob\nprob=min(1,exp(term1+term2));\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/mhprob3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6257510001490528}} {"text": "function [res] = plotBeamformer(M, f, d, bfFilter, theta)\n c = 340;\n w = bfFilter; % beamformer\n p = zeros(length(theta), length(f));\n for j=1:length(theta) %scan angles \n a=exp(-1j*[0:M-1]'*2*pi*f*cos(theta(j))*d/c);\n p(j, :) = sum(w.*a); \n end\n % p=p';\n res = p;\n \n if length(f) == 1\n subplot(1, 2, 1);\n plot(theta/pi*180, abs(p.')); grid on;\n xlabel('Degree')\n subplot(1, 2, 2);\n polar(theta,abs(p.'))\n else\n subplot(1, 2, 1);\n mesh(f, theta/pi*180, abs(p))\n xlabel('Frequency(Hz)')\n ylabel('Degree')\n title('Beamformer Directivity')\n subplot(1, 2, 2);\n imagesc(abs(p).');\n end\n\nend\n\n", "meta": {"author": "chenwj1989", "repo": "Beamforming_Examples", "sha": "403cd9e2b63310e2dfcdea5335a74c666156b53c", "save_path": "github-repos/MATLAB/chenwj1989-Beamforming_Examples", "path": "github-repos/MATLAB/chenwj1989-Beamforming_Examples/Beamforming_Examples-403cd9e2b63310e2dfcdea5335a74c666156b53c/beamformer/plotBeamformer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.625685497658824}} {"text": "function w = dualtree3D(x, J, Faf, af)\n\n% 3D Dual-Tree Discrete Wavelet Transform\n%\n% USAGE:\n% w = dualtree3D(x, J, Faf, af)\n% INPUT:\n% x - 3-D array\n% J - number of stages\n% Faf - first stage filters\n% af - filters for remaining stages\n% OUPUT:\n% w{j}{i}{d} - wavelet coefficients\n% j = 1..J, i = 1..4, d = 1..7\n% w{J+1}{i} - lowpass coefficients\n% i = 1..4\n% EXAMPLE:\n% x = rand(64,64,64);\n% J = 3;\n% [Faf, Fsf] = FSfarras;\n% [af, sf] = dualfilt1;\n% w = dualtree3D(x, J, Faf, af);\n% y = idualtree3D(w, J, Fsf, sf);\n% err = x - y;\n% max(max(max(abs(err))))\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\n\n% normalization\nx = x/2;\n\nM = [\n 1 1 1\n 2 2 1\n 2 1 2\n 1 2 2\n];\n\nfor i = 1:4\n f1 = M(i,1);\n f2 = M(i,2);\n f3 = M(i,3);\n [xi w{1}{i}] = afb3D(x, Faf{f1}, Faf{f2}, Faf{f3});\n for k = 2:J\n [xi w{k}{i}] = afb3D(xi, af{f1}, af{f2}, af{f3});\n end\n w{J+1}{i} = xi;\nend\n\nfor k = 1:J\n for m = 1:7\n [w{k}{1}{m} w{k}{2}{m} w{k}{3}{m} w{k}{4}{m}] = ...\n pm4(w{k}{1}{m}, w{k}{2}{m}, w{k}{3}{m}, w{k}{4}{m});\n end\nend\n\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/DTCWT/dualtree3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6256773283965267}} {"text": "function [cj,ier]=nufft2d2(nj,xj,yj,iflag,eps,ms,mt,fk)\n%NUFFT2D2: Nonuniform FFT in R^2 - Type 2.\n%\n% [CJ,IER] = NUFFT2D2(NJ,XJ,YJ,IFLAG,EPS,MS,MT,FK);\n%\n% cj(j) = SUM fk(k1,k2) exp(+/-i k1 xj(j)) exp(+/-i k2 yj(j)) \n% k1,k2 \n% for j = 1,...,nj\n%\n% where -ms/2 <= k1 <= (ms-1)/2, -mt/2 <= k2 <= (mt-1)/2\n%\n% If (iflag .ge.0) the + sign is used in the exponential.\n% If (iflag .lt.0) the - sign is used in the exponential.\n%\n% Input parameters:\n%\n% nj number of output values (integer)\n% xj,yj location of output values (real *8 array)\n% iflag determines sign of FFT (see above)\n% eps precision request (between 1.0e-15 and 1.0e-1)\n% ms number of Fourier modes given [ -ms/2: (ms-1)/2 ]\n% mt number of Fourier modes given [ -mt/2: (mt-1)/2 ]\n% fk Fourier coefficient values (complex *16 array)\n%\n% Output parameters:\n%\n% cj output values (complex *16 array)\n% ier error return code \n% ier = 0 => normal execution.\n% ier = 1 => precision eps requested is out of range.\n%\n%\n\ncj=zeros(nj,1)+1i*zeros(nj,1);\nier=0;\n\nmex_id_ = 'nufft2d2f90(i int[x], i double[], i double[], io dcomplex[], i int[x], i double[x], i int[x], i int[x], i dcomplex[], io int[x])';\n[cj, ier] = nufft2d(mex_id_, nj, xj, yj, cj, iflag, eps, ms, mt, fk, ier, 1, 1, 1, 1, 1, 1);\n\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openEbd/libGgNufft2D/nufft2d2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.625659492488679}} {"text": "function [ value, ifault ] = ppnd ( p )\n\n%*****************************************************************************80\n%\n%% PPND produces the normal deviate value corresponding to lower tail area = P.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by J Beasley, S Springer.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% J Beasley, S Springer,\n% Algorithm AS 111:\n% The Percentage Points of the Normal Distribution,\n% Applied Statistics,\n% Volume 26, Number 1, 1977, pages 118-121.\n%\n% Parameters:\n%\n% Input, real P, the value of the cumulative probability\n% densitity function. 0 < P < 1.\n%\n% Output, real VALUE, the normal deviate value with the property that\n% the probability of a standard normal deviate being less than or\n% equal to PPND is P.\n%\n% Output, integer IFAULT, error flag.\n% 0, no error.\n% 1, P <= 0 or P >= 1. PPND is returned as 0.\n%\n a0 = 2.50662823884;\n a1 = -18.61500062529;\n a2 = 41.39119773534;\n a3 = -25.44106049637;\n b1 = -8.47351093090;\n b2 = 23.08336743743;\n b3 = -21.06224101826;\n b4 = 3.13082909833;\n c0 = -2.78718931138;\n c1 = -2.29796479134;\n c2 = 4.85014127135;\n c3 = 2.32121276858;\n d1 = 3.54388924762;\n d2 = 1.63706781897;\n split = 0.42;\n\n ifault = 0;\n%\n% 0.08 < P < 0.92\n%\n if ( abs ( p - 0.5 ) <= split )\n\n r = ( p - 0.5 ) * ( p - 0.5 );\n\n value = ( p - 0.5 ) * ( ( ( ...\n a3 * r ...\n + a2 ) * r ...\n + a1 ) * r ...\n + a0 ) / ( ( ( ( ...\n b4 * r ...\n + b3 ) * r ...\n + b2 ) * r ...\n + b1 ) * r ...\n + 1.0 );\n%\n% P < 0.08 or P > 0.92,\n% R = min ( P, 1-P )\n%\n elseif ( 0.0 < p && p < 1.0 )\n\n if ( 0.5 < p )\n r = sqrt ( - log ( 1.0 - p ) );\n else\n r = sqrt ( - log ( p ) );\n end\n\n value = ( ( ( ...\n c3 * r ...\n + c2 ) * r ...\n + c1 ) * r ...\n + c0 ) / ( ( ...\n d2 * r ...\n + d1 ) * r ...\n + 1.0 );\n\n if ( p < 0.5 )\n value = - value;\n end\n%\n% P <= 0.0 or 1.0 <= P\n%\n else\n\n ifault = 1;\n value = 0.0;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa091/ppnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.625617889866861}} {"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction output = SA_spears(objective, inputs)\n% SIMULATED_ANNEALING_SPEARS: Function runs simulated annealing algorithm using the\n% SPEARS algorithm for optimizing binary functions (MAX-SAT). The reference with\n% the description of the algorithm and the parameters can be found in:\n%\n% An Experimental Evaluation of Fast Approximation Algorithms for the Maximum\n% Satisfiability Problem by: MATTHIAS POLOCZEK and DAVID P. WILLIAMSON\n\n% Extract n_vars\nn_vars = inputs.n_vars;\n\n% Set temperature limits\nmax_temp = 10;\nmin_temp = 0.01;\n\n% Set counter and T\ncounter = 0;\nT = max_temp;\n\n% Set initial condition and evaluate objective function\nnew_x = sample_models(1,n_vars);\nnew_obj = objective(new_x);\n\n% Set best variables\nbest_x = new_x;\nbest_obj = new_obj;\n\n% Declare vectors to save solutions\nmodel_iter = zeros(0,n_vars);\nobj_iter = zeros(0,1);\ntime_iter = zeros(0,1);\n\n% Run simulated annealing\nwhile(T >= min_temp)\n\n % Increment counter\n counter = counter + 1;\n sa_iter = tic;\n\n % Decrease T according to cooling schedule\n T = T*exp(-1/n_vars);\n\n %% Compute change from flipping each variable\n for i=1:n_vars\n\n % compute change in objective from flipping bit\n temp_x = new_x; temp_x(i) = 1 - temp_x(i);\n temp_df = objective(temp_x) - new_obj;\n\n % Compute probability of flipping variable\n p = 1/(1 + exp(-temp_df/T));\n if rand < p\n new_x = temp_x;\n end\n\n end\n\n % Evaluate objective function at current solution\n new_obj = objective(new_x);\n\n % Update best solution\n if new_obj < best_obj\n best_x = new_x;\n best_obj = new_obj;\n end \n\n % save solution\n model_iter = [model_iter; best_x];\n obj_iter = [obj_iter; best_obj];\n time_iter = [time_iter; toc(sa_iter)];\n\nend\n\n% save outputs\noutput = struct;\noutput.objVals = obj_iter; \noutput.optModel = model_iter;\noutput.runTime = time_iter;\n\nend", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/algorithms/SA_spears.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.6256178887571795}} {"text": "% cplxdual2D_plots\n% DISPLAY 2D WAVELETS OF cplxdual2D.M\n\nJ = 4;\nL = 3*2^(J+1);\nN = L/2^J;\n[Faf, Fsf] = FSfarras;\n[af, sf] = dualfilt1;\nx = zeros(2*L,6*L);\nw = cplxdual2D(x, J, Faf, af);\nw{J}{1}{2}{2}(N/2,N/2+0*N) = 1;\nw{J}{1}{1}{3}(N/2,N/2+1*N) = 1;\nw{J}{1}{2}{1}(N/2,N/2+2*N) = 1;\nw{J}{1}{1}{1}(N/2,N/2+3*N) = 1;\nw{J}{1}{2}{3}(N/2,N/2+4*N) = 1;\nw{J}{1}{1}{2}(N/2,N/2+5*N) = 1;\nw{J}{2}{2}{2}(N/2+N,N/2+0*N) = 1;\nw{J}{2}{1}{3}(N/2+N,N/2+1*N) = 1;\nw{J}{2}{2}{1}(N/2+N,N/2+2*N) = 1;\nw{J}{2}{1}{1}(N/2+N,N/2+3*N) = 1;\nw{J}{2}{2}{3}(N/2+N,N/2+4*N) = 1;\nw{J}{2}{1}{2}(N/2+N,N/2+5*N) = 1;\ny = icplxdual2D(w, J, Fsf, sf);\ny = [y; sqrt(y(1:L,:).^2+y(L+[1:L],:).^2)];\nfigure(1)\nclf\nimagesc(y);\ntitle('2D Dual-Tree Complex Wavelets')\naxis image\naxis off\ncolormap(gray(128))\nprint -djpeg95 cplxdual2D_plots", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/DTCWT/cplxdual2D_plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.625606320933794}} {"text": "function [u,p,w,edge,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)\n%% STOKESRT0 Stokes equations: the lowest order Raviart-Thomas element in 2D.\n%\n% [u,p,w,rotuI,Me,Mv,eqn,info] = StokesRT0(node,elem,bdFlag,pde,option)\n% uses the lowest order of Raviart-Thomas element (RT0) to approximate\n% velocity u and piecewise constant element (P0) to approximate pressure\n% p, repectively.\n%\n% We solve the following equation:\n% - grad div u + curl rot u + grad p = f in \\Omega \n% - div u = 0 in \\Omega \n% u = g on \\Gamma \n%\n% ifem StokesRT0doc\n%\n% See also StokesBDM1B\n%\n% Based on a version by Ming Wang. Revised by Lin Zhong. Discussed with Jie\n% Zhou and Long Chen. Further clean up by Long Chen.\n\n\nif ~exist('option','var'), option = []; end\n\n%% Data structure\nelemunSort = elem;\n[elem,bdFlag] = sortelem(elemunSort,bdFlag);\n[elem2edge,edge] = dofedge(elem);\n[Clambda,area,elemSign] = curlbasis(node,elem);\nN = size(node,1); NT = size(elem,1); NE = size(edge,1); \nNu = NE; Np = NT; Ndof = Nu + Np;\n\n%% Assemble matrix\ntic; % record assemble time\n% Mv: Lumped mass matrix for vertex: P1 element\nvecMv = accumarray([elem(:,1);elem(:,2);elem(:,3)],[area;area;area]/3,[N,1]);\n% invMv = spdiags(1./vecMv,0,N,N);\nMv = spdiags(vecMv,0,N,N);\n\n% Me: Mass matrix for RT0 element\nMe = getmassmatvec(elem2edge,area,Clambda,'RT0');\n\n%invMt: the inverse of Mass matrix for P0 element\ninvMt = spdiags(1./area,0,NT,NT);\n\n% B: negative divergence operator\nB = -icdmat(double(elem2edge),elemSign*[1 -1 1]);\n\n% C: curl operator\nC = icdmat(double(edge),[-1 1]);\n\n% R: weak rot operator\nR = spdiags(1./vecMv,0,N,N)*C'*Me;\n\n% Vector Laplacian\nA = B'*invMt*B + R'*Mv*R;\n\n%% Assemble right hand side\nlocEdge = [2,3; 1 3; 1,2]; % ascend ordering\nfu = zeros(Nu,1);% the right hand side of u\ng = zeros(Np,1); % the right hand side of p\nif ~isfield(pde,'f') || (isfield(pde,'f') && isreal(pde.f) && all(pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order is 3\nend\nif isfield(pde,'f') && ~isempty(pde.f)\n [lambda,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n bt = zeros(NT,3);\n for p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:);\n fp = pde.f(pxy);\n for k = 1:3\n i = locEdge(k,1); j = locEdge(k,2);\n % phi_k = lambda_iClambda_j - lambda_jClambda_i;\n phi_k = lambda(p,i)*Clambda(:,:,j)-lambda(p,j)*Clambda(:,:,i);\n rhs = dot(phi_k,fp,2);\n bt(:,k) = bt(:,k) + w(p)*rhs;\n end\n end\n bt = bt.*repmat(area,1,3);\n fu = accumarray(elem2edge(:),bt(:),[Nu 1]);\nend\nclear pxy fp bt rhs phi_k psi_k\n\n%% Boundary condition and graddiv part of A\n[u,p,ufreeDof,pDof,utbd] = getbdStokesRT0;\nassembleTime = toc;\n\n%% Solve the system of linear equations\n% set up solver type\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 1e5 % Direct solver for small size systems\n solver = 'direct';\n else % Multigrid-type solver for large size systems\n solver = 'mg';\n end\nelse\n solver = option.solver;\nend\n% solve the system\n% get submatrices of ufreeDof\nA0 = A(ufreeDof,ufreeDof);\nB0 = B(:,ufreeDof);\nf0 = fu(ufreeDof);\ng0 = g;\nif strcmp(solver,'direct') && ~isempty(ufreeDof)\n tic;\n bigA = [A0, B0'; ...\n B0, sparse(Np,Np)];\n bigF = [f0; g0];\n bigu = [u; p];\n bigFreeDof = [ufreeDof; Nu+pDof];\n bigu(bigFreeDof) = bigA(1:end-1,1:end-1)\\bigF(1:end-1);\n u = bigu(1:Nu);\n p = bigu(Nu+1:end);\n info.solverTime = toc;\nelseif strcmp(solver,'mg')\n% option.solver = 'vcycle';\n option.solver = 'WCYCLE';\n [u(ufreeDof),p,info] = mgstokesRT0(A0,B0,f0,g0,u,p,node,elemunSort,ufreeDof,option);\nend\n\n%% Post-process\nif length(pDof)~=Np % p is unique up to a constant\n % impose the condition int(p)=0\n c = sum(p.*area)/sum(area);\n p = p - c;\nend\n% w = invMv*(C'*Me*u + utbd);\nw = R*u + utbd./vecMv;\n\n%% Output information\neqn = struct('A',A0,'B',B0,'f',f0,'g',g0,'ufreeDof',ufreeDof,'pDof',pDof,'Me',Me,'Mv',Mv);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesRT0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [u,p,ufreeDof,pDof,utbd] = getbdStokesRT0\n %% Boundary condition of Stokes equation: RT0-P0 elements\n \n % Initial set up\n utbd = zeros(N,1); % the line integral of u on the boundary (u.t, tau)|_\\partial \\Omega\n u = zeros(Nu,1);\n p = zeros(Np,1);\n ufreeDof = (1:Nu)';\n pDof = (1:Np-1)';\n \n if ~exist('bdFlag','var'), bdFlag = []; end\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n if isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n bdFlag = [];\n end\n \n % Find Dirichlet boundary dof: fixedDof and pDof\n isFixedDof = false(Nu,1);\n if ~isempty(bdFlag) \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n Dirichlet = edge(isDirichlet,:);\n isFixedDof(isDirichlet) = true;\n fixedDof = find(isFixedDof);\n ufreeDof = find(~isFixedDof);\n end\n\n % Set up edge sign\n % edgeSign records the inconsistency of asecond orientation and\n % induced orientation for each boundary edges\n edgeSign = ones(NE,1);\n idx = (bdFlag(:,1) ~= 0 ) & (elemSign == -1) ; % the first edge is on boundary\n edgeSign(elem2edge(idx,1)) = -1;\n idx = (bdFlag(:,2) ~= 0 ) & (elemSign == 1) ; % the second edge is on boundary\n edgeSign(elem2edge(idx,2)) = -1;\n idx = (bdFlag(:,3) ~= 0 ) & (elemSign == -1) ; % the third edge is on boundary\n edgeSign(elem2edge(idx,3)) = -1; \n\n % Compute the boundary integral\n if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n % else no bddof or g_D = 0 (no modification needed)\n % 1. Normal component of u is imposed strongly\n if (isnumeric(pde.g_D) && length(pde.g_D) == NE)\n u(fixedDof) = pde.g_D(fixedDof);\n else\n u(fixedDof) = faceinterpolate(pde.g_D,node,edge(fixedDof,:),'RT0');\n end\n % 2. Tangential component of u is imposed weakly\n [lambdagD,wgD] = quadpts1(3);\n nQuadgD = size(lambdagD,1);\n % quadratic bases 1--3--2\n bdphi = lambdagD;\n ve = node(Dirichlet(:,2),:) - node(Dirichlet(:,1),:);\n ge = zeros(size(Dirichlet,1),2);\n int_left = zeros(size(Dirichlet,1),2);\n int_right = zeros(size(Dirichlet,1),2);\n for pp = 1:nQuadgD\n ppxy = lambdagD(pp,1)*node(Dirichlet(:,1),:) ...\n + lambdagD(pp,2)*node(Dirichlet(:,2),:);\n gDp = pde.g_D(ppxy);\n int_left = int_left + wgD(pp)*gDp*bdphi(pp,1);\n int_right = int_right + wgD(pp)*gDp*bdphi(pp,2);\n end \n ge(:,1) = dot(int_left,ve,2).*edgeSign(fixedDof);\n ge(:,2) = dot(int_right,ve,2).*edgeSign(fixedDof);\n utbd = accumarray(Dirichlet(:), [ge(:,1); ge(:,2)],[N,1]);\n end\n \n % Modify the right hand side\n fu = fu - A*u - Me*(C*(utbd./vecMv));\n g = g - B*u;\n g = g - mean(g);\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/StokesRT0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6256063071850589}} {"text": "function [X, A] = PCA_stochastic(A, k)\n% Example of stochastic gradient algorithm in Manopt on a PCA problem.\n% \n% PCA (principal component analysis) on a dataset A of size nxd consists\n% in solving\n% \n% minimize_X f(X) = -.5*norm(A*X, 'fro')^2 / n,\n% \n% where X is a matrix of dimension dxk with orthonormal columns. This\n% is equivalent to finding k dominant singular vectors of A, or k top\n% eigenvectors of A'*A.\n% \n% If n is large, this computation can be expensive. Thus, stochastic\n% gradient algorithms take the point of view that f(X) is a sum of many (n)\n% terms: each term involves only one of the n rows of A.\n%\n% To make progress, it may be sufficient to optimize with respect to a\n% subset of the terms at each iteration. This way, each individual\n% iteration can be very cheap. In particular, individual operations have\n% cost independent of n, because f or its gradient need never be evaluated\n% completely (or at all in the case of f.)\n%\n% Stochastic gradient algorithms (this implementation in particular) are\n% sensitive to proper parameter tuning. See in code.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Bamdev Mishra and Nicolas Boumal, Sept. 6, 2017\n% Contributors:\n% \n% Change log:\n% \n\n\n % If none is given, generate a random data set: n samples in R^d\n if ~exist('A', 'var') || isempty(A)\n d = 1000;\n n = 100000;\n fprintf('Generating data...');\n A = randn(n, d)*diag([[15 10 5], ones(1, d-3)]);\n fprintf(' done (size: %d x %d).\\n', size(A));\n else\n [n, d] = size(A);\n end\n\n % Pick a number of component to compute\n if ~exist('k', 'var') || isempty(k)\n k = 3;\n end\n \n % We are looking for k orthonormal vectors in R^d: Stiefel manifold.\n problem.M = stiefelfactory(d, k);\n \n % The cost function to minimize is a sum of n terms. This parameter\n % must be set for stochastic algorithms.\n problem.ncostterms = n;\n \n % We do not need to specify how to compute the value of the cost\n % function (stochastic algorithms never use this). All we need is to\n % specify how to compute the gradient of the cost function, where the\n % sum is restricted to a subset of the terms (a sample). Notice that we\n % specify a partial Euclidean gradient (hence the 'e' in partialegrad).\n % This way, Manopt will automatically convert the Euclidean vector into\n % a proper Riemannian partial gradient, in the tangent space at X.\n % In particular, if sample = 1:n, then the partial gradient corresponds\n % to the actual (complete) gradient.\n problem.partialegrad = @partialegrad;\n function G = partialegrad(X, sample)\n \n % X is an orthonormal matrix of size dxk\n % sample is a vector if indices between 1 and n: a subset\n % Extract a subset of the dataset\n Asample = A(sample, :);\n \n % Compute the gradient of f restricted to that sample\n G = -Asample'*(Asample*X);\n G = G / n;\n \n end\n\n % If one wants to use checkgradient to verify one's work, then it is\n % necessary to specify the cost function as well, as below.\n % problem.cost = @(X) -.5*norm(A*X, 'fro')^2 / n;\n % checkgradient(problem); pause;\n\n % To have the solver record statistics every x iterations, set\n % options.checkperiod to x. This will record simple quantities which\n % are almost free to compute (namely, elapsed time and step size of the\n % last step.) To record more sophisticated quantities, you can use\n % options.statsfun as usual. Time spent computing these statistics is\n % not counted in times reported in the info structure returned by the\n % solver.\n options.checkperiod = 10;\n options.statsfun = statsfunhelper('metric', @(X) norm(A*X, 'fro'));\n \n % Set the parameters for the solver: stochastic gradient algorithms\n % tend to be quite sensitive to proper tuning, especially regarding\n % step size selection. See the solver's documentation for details.\n options.maxiter = 200;\n options.batchsize = 10;\n % options.stepsize_type = 'decay';\n options.stepsize_init = 1e2;\n options.stepsize_lambda = 1e-3;\n options.verbosity = 2;\n \n % Run the solver\n [X, info] = stochasticgradient(problem, [], options);\n \n \n % Plot the special metric recorded by options.statsfun\n plot([info.iter], [info.metric], '.-');\n xlabel('Iteration #');\n ylabel('Frobenius norm of A*X');\n title('Convergence of stochasticgradient on stiefelfactory for PCA');\n \n % Add to that plot a reference: the globally optimal value attained if\n % the true dominant singular vectors are computed.\n fprintf('Running svds... ');\n t = tic();\n [V, ~] = svds(A', k);\n fprintf('done: %g [s] (note: svd may be faster)\\n', toc(t));\n hold all;\n bound = norm(A*V, 'fro');\n plot([info.iter], bound*ones(size([info.iter])), '--');\n hold off;\n \n legend('Algorithm', 'SVD bound', 'Location', 'SouthEast');\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/examples/PCA_stochastic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6255628871130401}} {"text": "function [Tx,Ty,Tz,nr,A] = surfcv(x,y,z,f,const);\n%SURFCV 3-D surface of constant value plot.\n% SURFCV(X,Y,Z,F,CONST) draws a surface of constant value\n% for a function of three variables: F(X,Y,Z) = CONST .\n% The arrays X,Y,Z define the coordinates for F and must\n% be monotonic and 3-D plaid (as if produced by meshgrid).\n% The surface is calculated by linear interpolation of the\n% values of F and is drawn with triangular patches using\n% FILL3. The color of each patch is determined by its\n% orientation with respect to a specified direction.\n% F must be an M-by-N-by-P volume array.\n%\n% SURFCV(F,CONST) assumes X=1:N, Y=1:M, Z=1:P.\n%\n% H = SURFCV(...) returns a column vector of handles \n% to PATCH objects, one handle per patch.\n%\n% [TX,TY,TZ] = SURFCV(X,Y,Z,F,CONST); returns 3-by-K\n% arrays specifying x,y,z coordinates of the vertices\n% of the triangular patches, where K is the number\n% of patches. FILL3(TX,TY,TZ,C) can be used to draw\n% the surface.\n%\n% [TX,TY,TZ,NR] = SURFCV(...) also returns 3-by-K\n% arrays of normal vectors for each patch which\n% can be used to compute lighting conditions of the\n% surface. Vectors are normalized to unity and\n% point in the direction of increasing F.\n%\n% [TX,TY,TZ,NR,A] = SURFCV(...) returns the area\n% of each patch.\n%\n% Example 1: To visualize the surface \n% 1./(X.^2+Y.^2) + 1./(Y.^2+Z.^2) + 1./(Z.^2+X.^2) = 2\n% over the range -3 < X < 3, -3 < Y < 3, -3 < Z < 3: \n%\n% [x,y,z] = meshgrid(-3:.4:3, -3:.4:3, -3:.4:3);\n% f = 1./(x.^2+y.^2) + 1./(y.^2+z.^2) + 1./(z.^2+x.^2);\n% const = 2;\n% surfcv(x,y,z,f,const);\n%\n% Example 2: The routine does not require the grid to be Cartesian\n% and can handle a more general problem of the form:\n% F(U(X,Y,Z),V(X,Y,Z),W(X,Y,Z)) = CONST\n% This allows to change surface appearance not only \n% by modifying the function F, but also by deforming\n% the grid:\n%\n% [x,y,z] = meshgrid(-3:.4:3, -3:.4:3, -3:.4:3);\n% f = 1./(x.^2+y.^2) + 1./(y.^2+z.^2) + 1./(z.^2+x.^2);\n% const = 2;\n% z = z + 0.2.*(x.^2 - y.^2); % Grid deformation\n% surfcv(x,y,z,f,const);\n%\n\n\n% Copyright (c) 1997 Ruslan L. Davidchack\n% University of Kansas, Lawrence, KS\n% e-mail: ruslan@ukans.edu\n% URL: http://www.ukans.edu/home/ruslan\n% created: Sep 29, 1997; \n% modified: Dec 23, 1998;\n\n%Short description of the algorithm.\n% Function F is defined on the M-by-N-by-P 3-D grid which \n% divides the space into (M-1)*(N-1)*(P-1) cubes. \n% F specifies values of the function at the vertices.\n% The surface of constant value cuts a patch through a \n% cube if F < CONST for some vertices of the cube and \n% F > CONST for others. \n% Note: F is slightly modified on the input to assure \n% that it does not exactly equal CONST on a vertex,\n% and thus a vertex of a surface element belongs to\n% only one edge (see below). \n% Every vertex of the patch lays on the edge of the \n% cube and its coordinates can be determined by linear \n% interpolation between the values of the function on the\n% ends of the edge. Two vertices of a patch are connected \n% if they lay on the edges that belong to the same face of\n% a cube. If a patch has more than three vertices, it is\n% subdivided into triangular elements by additional \n% connections between vertices that do not belong to the\n% same face. \n% The idea of the algorithm is to group the edges which\n% contain vertices of the surface patches into pairs according \n% to their affiliation with the faces (there can be only 2 or 4 \n% patch vertices on a face). Then the edge pairs are grouped\n% according to their affiliation with the cubes. The \"cube-edge\" \n% array, thus created, is then decomposed into triplets of patch\n% vertices. There can be more than one patch per cube and \n% the algorithm handles this case as well.\n%Naming convensions\n% ve - vertex, ed - edge, fa - face, cu - cube\n% nv - number of vertices, ne - number of edges, etc.\n% ce - coordinates of edges, cf - coordinates of faces, etc.\n% ie - indices of edges, ia - indices of faces, etc.\n\n%Simple case to follow the algorithm\n% [x,y,z] = meshgrid(1:4, 1:3, 1:2); const = 15;\n% f = x.^2 + y.^2 + z.^2; \n%Different cool surfaces:\n% 1. [x,y,z] = meshgrid(-3:.2:3, -3:.2:3, -3:.2:1.6); const = 7;\n% f = 1./(x.^2+y.^2)+1./(y.^2+z.^2)+1./(z.^2+x.^2)+x.^2+y.^2+z.^2;\n% \n% 2. [x,y,z] = meshgrid(-2:.2:2, -2:.2:2, -2:.2:2); const = 0;\n% f = (x.^2 + y.^2 + z.^2).^2 - 4*(x.^2 - y.^2 - z.^2);\n%\n% 3. [x,y,z] = meshgrid(-2:.2:2, -2:.2:2, -2:.2:2); const = 0;\n% f = x.^2 + y.^2 - z.^2.*(2 - z)./(2 + z); \n\n if nargin == 2,\n f = x; const = y;\n [x,y,z] = meshgrid(1:size(f,2),1:size(f,1),1:size(f,3));\n elseif nargin ~=5\n disp('Wrong number of input arguments'); return;\n end, \n\n%Make sure F == CONST is never true on the grid\n f1 = f; rngf = max(max(max(f))) - min(min(min(f))); \n if ~isfinite(rngf), rngf = 1; end, \n f1(find(f == const)) = const + 1e-12*rngf;\n\n%Number of vertices in each direction: nv = [M N P]\n% Total number of vertices = prod(nv) \n nv = size(f1); iv = reshape(1:prod(nv),nv);\n [ix,iy,iz] = meshgrid(1:nv(2),1:nv(1),1:nv(3));\n\n%Number of edges of each orientation: \n%\t\t\tne = [(M-1)*N*P M*(N-1)*P M*N*(P-1)]\n% Total number of edges = sum(ne)\n ne = prod(nv) - prod(nv([2 1 1;3 3 2]));\n\n%Determine indices of vertices that belong to each edge\n% Indexing of vertices is the same as in f(:)\n ed = zeros(sum(ne),2);\n% Edges parallel to y-axis\n ed((1:ne(1)),1) = reshape(iv(1:nv(1)-1,:,:),ne(1),1); \n ed((1:ne(1)),2) = ed((1:ne(1)),1) + 1;\n% Edges parallel to x-axis\n ie = (1:ne(2)) + ne(1);\n ed(ie,1) = reshape(iv(:,1:nv(2)-1,:),ne(2),1);\n ed(ie,2) = ed(ie,1) + nv(1); \n% Edges parallel to z-axis\n ie = (1:ne(3)) + ne(1) + ne(2);\n ed(ie,1) = (1:ne(3))';\n ed(ie,2) = ed(ie,1) + nv(1)*nv(2); \n\n%Select edges crossed by the surface \n se = find(prod(f1(ed)' - const) < 0)'; \n if isempty(se), \n disp('There is no surface in the specified range');\n if nargout > 0, Tx = []; end;\n if nargout > 2, Ty = []; Tz = []; end;\n if nargout > 3, nr = []; end;\n if nargout > 4, A = []; end;\n return; end;\n ed = ed(se,:);\n\n%Restore coordinates of the selected edges \n ce = zeros(length(se),4);\n ce(:,1:3) = [ix(ed(:,1)) iy(ed(:,1)) iz(ed(:,1))];\n ce(:,4) = (se > ne(1)) + (se > ne(1)+ne(2)) + 1;\n \n%Determine coordinates of the patch vertices \n dd = diff(f1(ed)')'; i1 = find(dd < 0);\n dd = (const - f1(ed(:,1)))./dd;\n np = zeros(3,length(se)); np(1,:) = diff(x(ed)'); \n np(2,:) = diff(y(ed)'); np(3,:) = diff(z(ed)');\n xv = np(1,:)'.*dd + x(ed(:,1));\n yv = np(2,:)'.*dd + y(ed(:,1));\n zv = np(3,:)'.*dd + z(ed(:,1));\n np(:,i1) = -np(:,i1); \n\n ie1 = find(ce(:,4) == 1); ie2 = find(ce(:,4) == 2); \n ie3 = find(ce(:,4) == 3); \n ie = cumsum([length(ie1); length(ie2); length(ie3)]);\n\n%Find faces containing the selected edges (maximum of 4 faces per edge)\n cf = repmat([(1:length(se))' ce],1,4);\n%Edge-to-face coordinate transformation matrix\n etof = [0 0 0 0 0 0 -1 0 0 0 0 0 0 0 2 0 0 0 -1 2;...\n\t 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 -1 0 -1;...\n 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 -1 0 -1 0 0 -1];\n ie = diff([0;ie]);\n cf = cf + [repmat(etof(1,:),ie(1),1);repmat(etof(2,:),ie(2),1);...\n repmat(etof(3,:),ie(3),1)];\n cf = reshape(cf',5,4*length(se));\n\n%Discard faces that are outside the range of x,y,z \n cf(:,find(prod(cf) == 0)) = []; cf = cf';\n i1 = find(cf(:,5) ~= 2); cf(i1(find(cf(i1,3) > nv(1)-1)),:) = []; \n i2 = find(cf(:,5) < 3); cf(i2(find(cf(i2,2) > nv(2)-1)),:) = []; \n i3 = find(cf(:,5) > 1); cf(i3(find(cf(i3,4) > nv(3)-1)),:) = [];\n\n%Find indices of the selected faces\n i1 = find(cf(:,5)==1); i2 = find(cf(:,5)==2); i3 = find(cf(:,5)==3);\n%Number of faces of each orientation:\n% ne = [(M-1)*(N-1)*P M*(N-1)*(P-1) (M-1)*N*(P-1)]\n nf = [nv(3)*(nv(2)-1)*(nv(1)-1) nv(1)*(nv(2)-1)*(nv(3)-1)...\n nv(2)*(nv(3)-1)*(nv(1)-1)];\n fa = zeros(size(cf,1),1); \n fa(i1) = cf(i1,3)+((cf(i1,2)-1)+(cf(i1,4)-1)*(nv(2)-1))*(nv(1)-1);\n fa(i2) = cf(i2,3)+((cf(i2,2)-1)+(cf(i2,4)-1)*(nv(2)-1))*nv(1)+nf(1);\n fa(i3) = cf(i3,3)+((cf(i3,2)-1)+(cf(i3,4)-1)*nv(2))*(nv(1)-1)+...\n\t nf(1) + nf(2);\n [fa ia] = sort(fa);\n\n%!!!!!!!! Check whether fac values come in pairs.\n% Each face can have only 2 or 4 selected edges.\n% The check below can be removed after debugging process \n% is completed\nif mod(length(fa),2) ~= 0,\n disp('Odd number!'); return,\nelse \n if sum(diff(reshape(fa,2,length(fa)/2))) > 0,\n disp('Odd number!'); return, end, end;\n%!!!!!!!!\n\n%Combine face coord. with indices of edges that belong to the faces\n cf = [fa(1:2:end) reshape(cf(ia,1),2,length(fa)/2)' ...\n cf(ia(1:2:end),2:5)];\n\n%Find cubes containing selected faces\n i1 = find(cf(:,7)==1); i2 = find(cf(:,7)==2); i3 = find(cf(:,7)==3);\n cc = repmat(cf(:,2:6),1,2);\n ftoc = [zeros(3,7) [0 0 -1;0 -1 0;-1 0 0]];\n cc = cc + [repmat(ftoc(1,:),length(i1),1);...\n repmat(ftoc(2,:),length(i2),1);repmat(ftoc(3,:),length(i3),1)];\n cc = reshape(cc',5,size(cf,1)*2);\n cc(:,find(prod(cc) == 0 | cc(4,:) > nv(1)-1 | cc(3,:) > nv(2)-1 |...\n cc(5,:) > nv(3)-1)) = []; cc = cc';\n\n cu = cc(:,4) + ((cc(:,3)-1) + (cc(:,5)-1)*(nv(2)-1))*(nv(1)-1);\n [cu ic] = sort(cu); \n%Combine indices of selected cubes with indices of edges that belong\n% to them into a cube-edge index array\n cc = [cu cc(ic,1:2)];\n\n%Combine edges into triplets composing surface patches\n ip = []; cc = sortrows(cc);\n while 1,\n%Indices of patches\n ic = find(diff([0;cc(:,1);0]) ~= 0);\n%Indices of triangular patches\n ic3 = ic(find(diff(ic) == 3));\n%Indices of patches with more than 3 vertices\n icm = ic(find(diff(ic) > 3)); \n \n%Select triangular patches and take them out of the cube-edge array\n ic(end) = []; ip = [ip [cc(ic,2:3)';cc(ic+1,3)']];\n if ~isempty(ic3),\n irm = repmat(ic3,1,3) + repmat(0:2,length(ic3),1);\n else irm = []; end,\n irm = [irm(:);icm]; cc(icm+1,2) = cc(icm,3); cc(irm,:) = [];\n\n%Sort new cube-edge index array or quit if it is empty\n if ~isempty(cc), cc = sortrows(cc); else, \n disp(['Number of patches = ' num2str(size(ip,2))]); \n break; end\n\n%Find cases when there is more than one patch per cube \n irm = find(sum(abs(diff(cc)')) == 0);\n if ~isempty(irm),\n %disp(['More than one patch in ' int2str(length(irm)) ' cubes']);\n irm = repmat(irm,2,1)+repmat([0;1],1,length(irm)); irm = irm(:);\n cc(irm,:) = []; end,\n\n end; \n\n Tx = xv(ip); Ty = yv(ip); Tz = zv(ip);\n\n%This is to compute area of each patch and the normal vector\n x2 = Tx(2,:)-Tx(1,:); y2 = Ty(2,:)-Ty(1,:); z2 = Tz(2,:)-Tz(1,:); \n x3 = Tx(3,:)-Tx(1,:); y3 = Ty(3,:)-Ty(1,:); z3 = Tz(3,:)-Tz(1,:);\n if nargout == 5\n A = sqrt((x2.*y3-x3.*y2).^2 + (y2.*z3-y3.*z2).^2 +...\n (z2.*x3-z3.*x2).^2)./2; end\n nr = [y2.*z3-y3.*z2; z2.*x3-z3.*x2; x2.*y3-x3.*y2]; \n nr = nr./repmat(sqrt(sum(nr.^2)),3,1); \n i1 = find(sum(nr.*np(:,ip(1,:))) < 0);\n nr(:,i1) = -nr(:,i1);\n i2 = ip(2,i1); ip(2,i1) = ip(3,i1); ip(3,i1) = i2; \n Tx = xv(ip); Ty = yv(ip); Tz = zv(ip);\n if nargout < 3,\n va = [-2 3 1]; \n% Colored according to the patch orientation \n C = va*nr; \n% Colored according to the patch distance from the origin\n% C = sqrt(Tx.^2 + Ty.^2 + Tz.^2); \n clf; H = fill3(Tx,Ty,Tz,C); axis image;\n set(gca,'xlim',[min(min(Tx)) max(max(Tx))],...\n 'ylim',[min(min(Ty)) max(max(Ty))],...\n 'zlim',[min(min(Tz)) max(max(Tz))],'box','on'); \n view(va); \n Tx = H; \n end\n if nargout == 0, clear Tx, end\n if nargout < 4, clear nr, end\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/327-surfcv-m/surfcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6255628793261823}} {"text": "function u = u_function ( time )\n\n%*****************************************************************************80\n%\n%% U_FUNCTION evaluates the time-dependent boundary values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real TIME, the current time.\n%\n% Output, real U(2), the boundary values at the left and right endpoints.\n%\n ua = sin ( pi * time );\n ub = - sin ( pi * time );\n\n u = [ ua; ub ];\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/heat_oned/u_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.6255628655191084}} {"text": "function om_constants\n\n% astrodynamic and utility constants\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal dtr rtd mu mmu smu omega req flat j2 aunit\n\ndtr = pi / 180.0;\n\nrtd = 180.0 / pi;\n\n% earth gravitational constant (km**3/sec**2)\n\nmu = 398600.436233;\n\n% moon gravitational constant (km**3/sec**2)\n\nmmu = 4902.800076;\n\n% sun gravitational constant (km**3/sec**2)\n\nsmu = 132712440040.944;\n\n% earth inertial rotation rate (radians/second)\n\nomega = 7.292115486e-5;\n\n% earth equatorial radius (kilometers)\n\nreq = 6378.1363;\n\n% earth flattening factor (non-dimensional)\n\nflat = 1.0 / 298.257;\n\n% earth oblateness gravity coefficient (non-dimensional)\n\nj2 = 0.00108263;\n\n% astronomical unit (kilometers)\n\naunit = 149597870.691;\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/39178-circular-orbit-plane-change/om_constants.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6254351934412894}} {"text": "function featuresS = ngtdmToScalarFeatures(s,p,numVoxels)\n% function featuresS = ngtdmToScalarFeatures(s,p,numVoxels)\n% \n% APA, 3/15/2017\n\n% Coarseness\nfeaturesS.coarseness = 1/(sum(s .* p) + 1e-6);\n\n% Contrast\nNg = sum(p > 0);\nnumLevels = length(p);\nindV = (1:numLevels)';\nterm1 = 0;\nterm2 = 0;\nfor lev = 1:numLevels\n term1 = term1 + ...\n sum(p .* circshift(p,lev) .* (indV-circshift(indV,lev)).^2);\n term2 = term2 + s(lev);\nend\nfeaturesS.contrast = 1/Ng/(Ng-1) * term1 * term2 / numVoxels;\n\n% Busyness\ndenom = 0;\nfor lev = 1:numLevels\n pShiftV = circshift(p,lev);\n indShiftV = circshift(indV,lev); \n usePv = p > 0;\n usePshiftV = pShiftV > 0;\n denom = denom + ...\n sum(usePv .* usePshiftV .* abs(p .* indV - pShiftV .* indShiftV));\nend\nfeaturesS.busyness = sum(p .* s) / denom;\n\n% Complexity\ncomplxty = 0;\nfor lev = 1:numLevels\n pShiftV = circshift(p,lev);\n sShiftV = circshift(s,lev);\n indShiftV = circshift(indV,lev);\n usePv = p > 0;\n usePshiftV = pShiftV > 0; \n term1 = abs(indV - indShiftV);\n term2 = usePv .* usePshiftV .* (p .* s + pShiftV .* sShiftV)...\n ./ (p + pShiftV + eps);\n complxty = complxty + sum(term1 .* term2);\nend\nfeaturesS.complexity = complxty / numVoxels;\n\n% Texture strength\nstrength = 0;\nfor lev = 1:numLevels\n pShiftV = circshift(p,lev);\n indShiftV = circshift(indV,lev);\n usePv = p > 0;\n usePshiftV = pShiftV > 0; \n term = sum(usePv .* usePshiftV .* (p + pShiftV) .* (indV - indShiftV).^2);\n strength = strength + term;\nend\nfeaturesS.strength = strength / sum(s);\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/ngtdmToScalarFeatures.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6254351824032334}} {"text": "function [B,twom]=multicatdir_f(A,gamma,omega)\n%MULTICATDIR_F returns multilayer Leicht-Newman modularity matrix for categorical directed layers, function handle version\n%\n% Version: 2.2.0\n% Date: Thu 11 Jul 2019 12:25:42 CEST\n%\n% Input: A: Cell array of NxN adjacency matrices for each layer of a\n% categorical directed multilayer network\n% gamma: intralayer resolution parameter\n% omega: interlayer coupling strength\n%\n% Output: B: function handle where B(i) returns the ith column of\n% [NxT]x[NxT] flattened modularity tensor for the\n% multilayer network with uniform ordinal coupling (T is\n% the number of layers of the network)\n% twom: normalisation constant\n%\n% Example of usage: [B,twom]=multicatdir_f(A,gamma,omega);\n% [S,Q]= genlouvain(B); % see iterated_genlouvain.m and\n% postprocess_categorical_multilayer.m for how to improve output\n% multilayer partition\n% Q=Q/twom;\n% S=reshape(S,N,T);\n%\n% [B,twom] = MULTICATDIR_F(A,GAMMA, OMEGA) with A a cell array of square\n% matrices of equal size each representing an directed network \"layer\"\n% computes the Leicht-Newman multilayer modularity matrix B using the\n% quality function described in Mucha et al. 2010, with intralayer\n% resolution parameter GAMMA, and with interlayer coupling OMEGA\n% connecting all-to-all categorical layers. Once the mulilayer modularity\n% matrix is computed, optimization can be performed by the generalized\n% Louvain code GENLOUVAIN or ITERATED_GENLOUVAIN. The output B can be used\n% with other heuristics, provided the same mapping is used to go from the\n% multilayer tensor to the multilayer flattened matrix. That is, the\n% node-layer tuple (i,s) is mapped to i + (s-1)*N. [Note that we can\n% define a mapping between a multilayer partition S_m stored as an N by T\n% matrix and the corresponding flattened partition S stored as an NT by 1\n% vector. In particular S_m = reshape(S,N,T) and S = S_m(:).]\n%\n% See also\n% genlouvain heuristics: GENLOUVAIN, ITERATED_GENLOUVAIN\n% multilayer wrappers: MULTICAT, MULTICAT_F, MULTIORD\n% other heuristics: SPECTRAL23\n% Kernighan-Lin improvement: KLNB\n%\n% Notes:\n% The matrices in the cell array A are assumed to be square,\n% and of equal size. These assumptions are not checked here.\n%\n% For smaller systems, it is potentially more efficient (and easier) to\n% directly use the sparse quality/modularity matrix B in MULTICAT. For\n% large systems with undirected layer networks, use MULTICAT_F.\n%\n% This code serves as a template and can be modified for situations\n% with other wrinkles (e.g., different intralayer null models,\n% different numbers of nodes from layer-to-layer, or systems which are\n% both multiplex and longitudinal). That is, this code is only a\n% starting point; it is by no means exhaustive.\n%\n% By using this code, the user implicitly acknowledges that the authors\n% accept no liability associated with that use. (What are you doing\n% with it anyway that might cause there to be a potential liability?!?)\n%\n% References:\n% Blondel, Vincent D., Jean-Loup Guillaume, Renaud Lambiotte, and\n% Etienne Lefebvre, \"Fast unfolding of communities in large networks,\"\n% Journal of Statistical Mechanics: Theory and Experiment, P10008\n% (2008).\n%\n% Fortunato, Santo, \"Community detection in graphs,\" Physics Reports\n% 486, 75-174 (2010).\n%\n% Good, Benjamin H., Yves-Alexandre de Montjoye, and Aaron Clauset,\n% \"Performance of modularity maximization in practical contexts,\"\n% Physical Review E 81, 046106 (2010).\n%\n% Mucha, Peter J., Thomas Richardson, Kevin Macon, Mason A. Porter, and\n% Jukka-Pekka Onnela. \"Community Structure in Time-Dependent,\n% Multiscale, and Multiplex Networks,\" Science 328, 876-878 (2010).\n%\n% Elizabeth A. Leicht and Mark E. J. Newman. \"Community structure in\n% Directed Networks\", Physical Review Letters 100, 118703 (2008).\n%\n% Porter, M. A., J. P. Onnela, and P. J. Mucha, \"Communities in\n% networks,\" Notices of the American Mathematical Society 56, 1082-1097\n% & 1164-1166 (2009).\n%\n% Acknowledgments:\n% Thank you to Dani Bassett, Jesse Blocher, Bruce Rogers, and Simi Wang\n% for their collaborative help which led to significant cleaning up\n% of earlier versions of our multilayer community detection codes.\n\n\n\nif nargin<2||isempty(gamma)\n gamma=1;\nend\n\nif nargin<3||isempty(omega)\n omega=1;\nend\n\nN=length(A{1});\nT=length(A);\n\nif length(gamma)==1\n gamma=repmat(gamma,T,1);\nend\n\nm=zeros(T,1);\nfor i=1:T\n m(i)=sum(A{i}(:));\nend\nA=blkdiag(A{:});\nkout=sum(A,1);\nkoutmat=sparse(1:(N*T),kron(1:T,ones(1,N)),kout);\nkin=sum(A,2);\nkinmat=sparse(1:(N*T),kron(1:T,ones(1,N)),kin);\nA=(A+A')./2;\nall2all = N*[(-T+1):-1,1:(T-1)];\nA = A + omega*spdiags(ones(N*T,2*T-2),all2all,N*T,N*T);\n\nB=@(i) A(:,i)-gamma(ceil(i./(N+eps))).*(kout(i).*kinmat(:,ceil(i./(N+eps)))+kin(i).*koutmat(:,ceil(i./(N+eps))))./(2*m(ceil(i./(N+eps))));\n\ntwom=sum(m)+omega*2*N*(T-1);\nend\n", "meta": {"author": "GenLouvain", "repo": "GenLouvain", "sha": "5688f219baa726988a2faa19cf00d63159fa4ff9", "save_path": "github-repos/MATLAB/GenLouvain-GenLouvain", "path": "github-repos/MATLAB/GenLouvain-GenLouvain/GenLouvain-5688f219baa726988a2faa19cf00d63159fa4ff9/HelperFunctions/multicatdir_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6253358382020187}} {"text": "% VL_PEGASOS PEGASOS linear SVM solver\n% W = VL_PEGASOS(X, Y, LAMBDA) learns a linear SVM W given training\n% vectors X, their labels Y, and the regularization parameter LAMBDA\n% using the PEGASOS [1] solver. The algorithm finds a minimizer W of\n% the objective function\n%\n% LAMBDA/2 |W|^2 + 1/N SUM_i LOSS(W, X(:,i), Y(i))\n%\n% where LOSS(W,X,Y) = MAX(0, 1 - Y W'X) is the hinge loss and N is\n% the number of training vectors in X.\n%\n% [W B INFO] = VL_SVMPEGASOS(X, Y, LAMBDA) learns a linear SVM W\n% and a bias B given training vectors X, their labels Y, and the\n% regularization parameter LAMBDA using the PEGASOS [1]\n% solver. INFO is a struct containing the input parameters plus\n% diagnostic informations:\n% \n% energy::\n% SVM energy value.\n% \n% iterations::\n% Number of iterations performed.\n% \n% elapseTime::\n% Elapsed time since the start of the SVM learning.\n% \n% regulizerTerm::\n% Value of the SVM regulizer term.\n% \n% lossPos::\n% Value of loss function only for data points labeled positives.\n% \n% lossNeg::\n% Value of loss function onlt for data points labeled negatives.\n% \n% hardLossPos::\n% Number of mislabeled positive points.\n% \n% hardLossNeg::\n% Number of mislabeled negative points.\n% \n% ALGORITHM. PEGASOS is an implementation of stochastic subgradient\n% descent. At each iteration a data point is selected at random, the\n% subgradient of the cost function relative to that data point is\n% computed, and a step is taken in that direction. The step size is\n% inversely proportional to the iteration number. See [1] for\n% details.\n%\n% VL_SVMPEGASOS() accepts the following options:\n% \n% Epsilon:: [empty]\n% Specify the SVM stopping criterion threshold. If not\n% specified VL_SVMPEGASOS will finish when the maximum number\n% of iterations is reached. The stopping criterion is tested\n% after each ENERGYFREQ iteration. \n% \n% MaxIterations:: [10 / LAMBDA]\n% Sets the maximum number of iterations.\n%\n% BiasMultiplier:: [0]\n% Appends to the data X the specified scalar value B. This\n% approximates the training of a linear SVM with bias. \n%\n% StartingModel:: [null vector]\n% Specify the initial value for the weight vector W.\n%\n% StartingIteration:: [1]\n% Specify the iteration number to start from. The only effect\n% is to change the step size, as this is inversely proportional\n% to the iteration number.\n%\n% StartingBias:: [0]\n% Specify the inital bias value.\n% \n% BiasLearningRate:: [1]\n% Specify the frequency of the bias learning. The default\n% setting updates the bias at each iteration.\n% \n% Permutation:: [empty]\n% Specify a permutation PERM to be used to sample the data (this\n% disables random sampling). Specifically, at the T-th iteration\n% the algorithm takes a step w.r.t. the PERM[T']-th data point,\n% where T' is T modulo the number of data samples\n% (i.e. MOD(T'-1,NUMSAMPLES)+1). PERM needs not to be\n% bijective. This allows specifying certain data points more or\n% less frequently, implicitly increasing their relative weight in\n% the error term. A common application is to balance an unbalanced\n% dataset.\n%\n% DiagnosticFunction:: [empty]\n% Specify a function handle to be called every ENERGYFREQ iterations.\n% \n% DiagnosticCallRef:: [empty]\n% Specify a paramater to be passed to the DIAGNOSTICFUNCTION handle.\n% \n% EnergyFreq:: [100]\n% Specify how often the SVM energy is computed.\n% \n% HOMKERMAP:: [empty]\n% Specify the use of an Homogeneus Kernel map for the training\n% data (See [2],[3]). The passed value N is such that a 2*N+1\n% dimensional approximated kernel map is computed. Each\n% training data point is expanded online into a vector of\n% dimension 2*N+1.\n% \n% KChi2::\n% Compute the map for the Chi2 kernel.\n%\n% KINTERS::\n% Compute the map for the intersection kernel.\n%\n% KL1::\n% Same as KINTERS, but deprecated as the name is not fully\n% accurate.\n%\n% KJS::\n% Compute the map for the JS (Jensen-Shannon) kernel.\n%\n% Period:: [automatically tuned]\n% Set the period of the kernel specturm. The approximation is\n% based on periodicizing the kernel specturm. If not specified,\n% the period is automatically set based on the heuristic described\n% in [2].\n%\n% Window:: [RECTANGULAR]\n% Set the window used to truncate the spectrum before The window\n% can be either RECTANGULAR or UNIFORM window. See [2] and the API\n% documentation for details.\n%\n% Gamma:: [1]\n% Set the homogeneity degree of the kernel. The standard kernels\n% are 1-homogeneous, but sometimes smaller values perform better\n% in applications. See [2] for details.\n% \n% Verbose::\n% Be verbose.\n%\n% Example::\n% The options StartingModel and StartingIteration can be used\n% to continue training. I.e., the command\n%\n% vl_twister('state',0) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',1000) ;\n%\n% produces the same result as the sequence\n%\n% vl_twister('state',0) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',500) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',500, ...\n% 'StartingIteration', 501, ...\n% 'StartingModel', w) ;\n%\n% REFERENCES::\n% [1] S. Shalev-Shwartz, Y. Singer, N. Srebro, and\n% A. Cotter. Pegasos: Primal Estimated sub-GrAdient SOlver for\n% SVM. MBP, 2010.\n% \n% [2] A. Vedaldi and A. Zisserman\n% `Efficient Additive Kernels via Explicit Feature Maps',\n% Proc. CVPR, 2010.\n%\n% [3] A. Vedaldi and A. Zisserman\n% `Efficient Additive Kernels via Explicit Feature Maps',\n% PAMI, 2011 (submitted).\n%\n% See also: VL_HOMKERMAP(), VL_HELP().\n\n% AUTHORIGHTS\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/dependencies/vlfeat-0.9.16/toolbox/misc/vl_pegasos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6251601878779536}} {"text": "function a = i4mat_elim ( m, n, a )\n\n%*****************************************************************************80\n%\n%% I4MAT_ELIM carries out exact Gauss elimination on an I4MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows in A.\n%\n% Input, integer N, the number of columns in A.\n%\n% Input, integer A(M,N), the matrix to be Gauss eliminated. \n%\n% Output, integer A(M,N), the Gauss-eliminated matrix.\n%\n\n%\n% Initialize the swap parity counter.\n%\n iswap = 1;\n%\n% For each column JCOL...\n%\n for jcol = 1 : min ( m, n )\n%\n% Find the maximum element in rows JCOL through M.\n%\n amax = abs ( a(jcol,jcol) );\n imax = jcol;\n\n for i = jcol + 1 : m\n if ( amax < abs ( a(i,jcol) ) )\n amax = abs ( a(i,jcol) );\n imax = i;\n end\n end\n%\n% If the maximum entry is nonzero, then...\n%\n if ( amax ~= 0 )\n%\n% If the maximum entry does not occur in row JCOL, then swap rows.\n%\n if ( imax ~= jcol )\n iswap = -iswap;\n temp(1:n) = a(jcol,1:n);\n a(jcol,1:n) = a(imax,1:n);\n a(imax,1:n) = temp(1:n);\n end\n%\n% Eliminate all nonzero entries in column JCOL, below the diagonal entry.\n%\n for i = jcol+1 : m\n\n if ( a(i,jcol) ~= 0 )\n\n jmult = a(i,jcol);\n imult = a(jcol,jcol);\n ifact = i4_gcd ( imult, jmult );\n imult = imult / ifact;\n jmult = jmult / ifact;\n\n for j = jcol : n\n a(i,j) = jmult * a(jcol,j) - imult * a(i,j);\n end\n\n end\n\n end\n%\n% Remove any row or column factors.\n%\n [ a, irow, icol ] = i4mat_red ( m, n, a );\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4mat_elim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6250300007623718}} {"text": "%A 2D uniform PDF function. \n%xrange and yrange are inclusive limits of region\n%z is a 2D sample point.\nfunction val = unifpdf_2d(xrange, yrange, z)\n minX = xrange(1);\n maxX = xrange(2);\n minY = yrange(1);\n maxY = yrange(2);\n evalX = z(1);\n evalY = z(2);\n if(evalX < minX)\n val = 0;\n return;\n elseif(evalX > maxX)\n val = 0;\n return\n elseif (evalY < minY)\n val = 0;\n return;\n elseif(evalY > maxY)\n val = 0;\n return;\n else\n val = 1 / ((maxX - minX) * (maxY - minY));\n end\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/42769-gaussian-mixture-probability-hypothesis-density-filter-gm-phd/GM_PHD_Filter_v104/GM_PHD_Filter/unifpdf_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6249808991576832}} {"text": "function plane = createPlane(varargin)\n%CREATEPLANE Create a plane in parametrized form.\n%\n% PLANE = createPlane(P1, P2, P3) \n% creates a plane containing the 3 points\n%\n% PLANE = createPlane(PTS) \n% The 3 points are packed into a single 3x3 array.\n%\n% PLANE = createPlane(P0, N);\n% Creates a plane from a point and from a normal to the plane. The\n% parameter N is given either as a 3D vector (1-by-3 row vector), or as\n% [THETA PHI], where THETA is the colatitute (angle with the vertical\n% axis) and PHI is angle with Ox axis, counted counter-clockwise (both\n% given in radians).\n% \n% PLANE = createPlane(P0, Dip, DipDir);\n% Creates a plane from a point and from a dip and dip direction angles \n% of the plane. Parameters Dip and DipDir angles are given as numbers.\n% Dip : maximum inclination to the horizontal.\n% DipDir : direction of the horizontal trace of the line of dip, \n% measured clockwise from north.\n%\n% The created plane data has the following format:\n% PLANE = [X0 Y0 Z0 DX1 DY1 DZ1 DX2 DY2 DZ2], with\n% - (X0, Y0, Z0) is a point belonging to the plane\n% - (DX1, DY1, DZ1) is a first direction vector\n% - (DX2, DY2, DZ2) is a second direction vector\n% The 2 direction vectors are normalized and orthogonal.\n%\n% See also \n% planes3d, medianPlane\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-02-18\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\nif length(varargin) == 1\n var = varargin{1};\n \n if iscell(var)\n plane = zeros([length(var) 9]);\n for i=1:length(var)\n plane(i,:) = createPlane(var{i});\n end\n elseif size(var, 1) >= 3\n % 3 points in a single array\n p1 = var(1,:);\n p2 = var(2,:);\n p3 = var(3,:);\n \n % create direction vectors\n v1 = p2 - p1;\n v2 = p3 - p1;\n\n % create plane\n plane = normalizePlane([p1 v1 v2]);\n return;\n end\n \nelseif length(varargin) == 2\n % plane origin\n p0 = varargin{1};\n \n % second parameter is either a 3D vector or a 3D angle (2 params)\n var = varargin{2};\n if size(var, 2) == 2\n % normal is given in spherical coordinates\n n = sph2cart2([var ones(size(var, 1))]);\n elseif size(var, 2)==3\n % normal is given by a 3D vector\n n = normalizeVector3d(var);\n else\n error ('wrong number of parameters in createPlane');\n end\n \n % ensure same dimension for parameters\n if size(p0, 1)==1\n p0 = repmat(p0, [size(n, 1) 1]);\n end\n if size(n, 1)==1\n n = repmat(n, [size(p0, 1) 1]);\n end\n\n % find a vector not colinear to the normal\n v0 = repmat([1 0 0], [size(p0, 1) 1]);\n inds = vectorNorm3d(cross(n, v0, 2))<1e-14;\n v0(inds, :) = repmat([0 1 0], [sum(inds) 1]);\n% if abs(cross(n, v0, 2))<1e-14\n% v0 = repmat([0 1 0], [size(p0, 1) 1]);\n% end\n \n % create direction vectors\n v1 = normalizeVector3d(cross(n, v0, 2));\n v2 = -normalizeVector3d(cross(v1, n, 2));\n\n % concatenate result in the array representing the plane\n plane = [p0 v1 v2];\n return;\n \nelseif length(varargin)==3\n var1 = varargin{1};\n var2 = varargin{2};\n var3 = varargin{3};\n \n if size(var1, 2) == 3 && size(var2, 2) == 3 && size(var3, 2) == 3\n p1 = var1; \n p2 = var2;\n p3 = var3;\n\n % create direction vectors\n v1 = p2 - p1;\n v2 = p3 - p1;\n\n plane = normalizePlane([p1 v1 v2]);\n return;\n elseif size(var1, 2) == 3 && size(var2, 2) == 1 && size(var3, 2) == 1\n p0 = var1;\n n = [sin(var2)*sin(var3) sin(var2)*cos(var3) cos(var2)];\n \n % find a vector not colinear to the normal\n v0 = repmat([1 0 0], [size(p0, 1) 1]);\n inds = vectorNorm3d(cross(n, v0, 2))<1e-14;\n v0(inds, :) = repmat([0 1 0], [sum(inds) 1]);\n\n % create direction vectors\n v1 = normalizeVector3d(cross(n, v0, 2));\n v2 = -normalizeVector3d(cross(v1, n, 2));\n\n % concatenate result in the array representing the plane\n plane = [p0 v1 v2]; \n return;\n else\n error('Wrong argument in \"createPlane\".');\n end \nelse\n error('Wrong number of arguments in \"createPlane\".');\nend\n\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/createPlane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6249672013253007}} {"text": "function [ n_data, x, fx ] = normal_01_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_CDF_VALUES returns some values of the Normal 01 CDF.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`ContinuousDistributions`\"]\n% dist = NormalDistribution [ 0, 1 ]\n% CDF [ dist, x ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 17;\n\n fx_vec = [ ...\n 0.5000000000000000E+00, ...\n 0.5398278372770290E+00, ...\n 0.5792597094391030E+00, ...\n 0.6179114221889526E+00, ...\n 0.6554217416103242E+00, ...\n 0.6914624612740131E+00, ...\n 0.7257468822499270E+00, ...\n 0.7580363477769270E+00, ...\n 0.7881446014166033E+00, ...\n 0.8159398746532405E+00, ...\n 0.8413447460685429E+00, ...\n 0.9331927987311419E+00, ...\n 0.9772498680518208E+00, ...\n 0.9937903346742239E+00, ...\n 0.9986501019683699E+00, ...\n 0.9997673709209645E+00, ...\n 0.9999683287581669E+00 ];\n\n x_vec = [ ...\n 0.0000000000000000E+00, ... \n 0.1000000000000000E+00, ...\n 0.2000000000000000E+00, ...\n 0.3000000000000000E+00, ...\n 0.4000000000000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.6000000000000000E+00, ...\n 0.7000000000000000E+00, ...\n 0.8000000000000000E+00, ...\n 0.9000000000000000E+00, ...\n 0.1000000000000000E+01, ...\n 0.1500000000000000E+01, ...\n 0.2000000000000000E+01, ...\n 0.2500000000000000E+01, ...\n 0.3000000000000000E+01, ...\n 0.3500000000000000E+01, ...\n 0.4000000000000000E+01 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/normal_01_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6249129203879925}} {"text": "% effOFexpDesignsNoOverlap2\n% ER-fMRI data analysis\n% script:\n% throughout we assume TR=2.\n\nloadDataYes=1; % =1 -> loads existing data file\n\n%cd /home/giedrius/giedrius/projects/matlab/erfmri\npluginCorrYes=0;\noverlapYes=0;\nnReps=10000; %\nnVals=3;\nn2=12; % assumed # TRs to cover HDR fn\npwRange=6:10;\n\ndaleYes=1; % 1-usual Dale efficiency. 0-Fisher\n% event matrices are defined based on vectors with the average\n% energy removed\n\ncutEndPad=1; %cutting reduces efficiency!\n\nif ~loadDataYes,\nrndEffAll=[];\nmEffAll=[];\n\ntic\nfor pwr=pwRange,\n% creating event vectors\nms=m2bin([mseq(2,pwr,0,1)])'; % fixing to the length of 2^n\nn=length(ms) % scan duration in TRs\nif pluginCorrYes\n b=[0.406;0.8825]; % parameters from SPG fMRI data\n fittedACorr=autocorrFnct(b,1:n+(n2-1)*rem(cutEndPad+1,2));\n Cninv=inv(toeplitz(fittedACorr));\nelse\n Cninv=eye(n+(n2-1)*rem(cutEndPad+1,2));\nend;\n\nmRange=(2^pwRange(1)-2);\nmEff=zeros(1,mRange);\n\n%shift1=ceil(2^pwRange(1)/2);\n%XXXXXXXXXXXXXXXXXXXXX\nfor shift=1:mRange,\n\t%shift=2^(pwr-1)+5;\n\tfoo=[ms(shift+1:end) ms(1:shift)];%shifted version\n\t%foo1=[ms(shift1+1:end) ms(1:shift1)];%shifted version\n\tfoo=ms+foo*2; %+foo1*4;\n\n\tmEvent=zeros(nVals,n);\n\tfor k=1:nVals,\n \t ind=find(foo==k);\n \t mEvent(k,ind)=1;\n\tend;\n\n\t% defining event matrix as convolution matrix\n\t%eventMatrix=makeEventMtrx(mEvent-(ones(length(mEvent),1)*...\n\t%sum(mEvent'))'/length(mEvent),n2); \n\t\n\teventMatrix=makeEventMtrx(mEvent,n2); \n\t\n if cutEndPad, eventMatrix=eventMatrix(1:n,:); end;\n\teventMatrix=eventMatrix-ones(size(eventMatrix,1),1)* ...\n\t sum(eventMatrix)/size(eventMatrix,1);\n\n if daleYes,\n\t designEff=1/trace(inv(eventMatrix'*Cninv*eventMatrix));\n\telse\n\t designEff=trace(eventMatrix'*Cninv*eventMatrix);\n\tend;\n\t\n\tmEff(shift)=designEff;\nend;\n\n%mProbab=sum(mEvent'); mProbab=mean(mProbab)/n;\nplot(mEff,'k','LineWidth',2); \nset(gca,'FontSize',12);\nxlabel('Cyclical shift of event vector #3','FontSize',16)\nylabel('Efficiency','FontSize',16)\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,5,4]);\n%axis([0 n 0 .5])\ndrawnow;\n%print -dpsc2 cyclingNonOverlapping\npause\n\nmEffAll=[mEffAll, max(mEff)];\n\n% for simply randomized designs:\nnVals=size(mEvent,1);\n%n=n+1\nif pluginCorrYes\n b=[0.406;0.8825]; % parameters from SPG fMRI data\n fittedACorr=autocorrFnct(b,1:n+(n2-1)*rem(cutEndPad+1,2));\n Cninv=inv(toeplitz(fittedACorr));\nelse\n Cninv=eye(n+(n2-1)*rem(cutEndPad+1,2));\nend;\n\nif pwr<8, correction=0.02; \nelseif pwr<9, correction=0.005;\nelseif pwr==10, correction=0.001;\nend;\ncorrection=0;\n\npEv=nVals/(nVals+1)+correction; %\n\nrndEff=zeros(1,nReps);\nfor k=1:nReps;\n rndEvent=balancedRnd(n,nVals,pEv,overlapYes);%sum(rndEvent')\n\n % defining event matrix as convolution matrix\n %eventMatrix=makeEventMtrx(rndEvent-(ones(length(rndEvent),1)*...\n %sum(rndEvent'))'/length(rndEvent),n2); \n\t\n eventMatrix=makeEventMtrx(rndEvent,n2); \n \n if cutEndPad, eventMatrix=eventMatrix(1:n,:); end;\n eventMatrix=eventMatrix-ones(size(eventMatrix,1),1)* ...\n sum(eventMatrix)/size(eventMatrix,1);\n \n if daleYes,\n\t designEff=1/trace(inv(eventMatrix'*Cninv*eventMatrix));\n else\n\t designEff=trace(eventMatrix'*Cninv*eventMatrix);\n end;\n rndEff(k)=designEff;\nend;\n \n\nrndEffAll=[rndEffAll;rndEff];\nend;\ntoc;\n\nelse \n eval(['load dataEffNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh']);\nend %fi loadDataYes\n\n\nnn=2.^[pwRange]-1;\n\n%[b,a]=hist(rndEff,20); \n%bar(a,b/nReps); hold on;\n%plot(max(mEff),0,'k*'); \n\nfigure(1); clf;\nloglog(nn,mEffAll,'r*');hold on;\n\n% theoretical max -- only for one event type:\n%theoMax=(nn+1)/n2/4;\n%loglog(nn,theoMax,'g+');hold on;\n\np99=prctile(rndEffAll',99.9);\np00=prctile(rndEffAll',0.1);\nmed=median(rndEffAll');\nloglog(nn,med,'k.-','LineWidth',2);\nloglog([nn;nn],[p00;p99],'k')\nloglog([nn*.93;nn*1.1],[p00;p00],'k')\nloglog([nn*.93;nn*1.1],[p99;p99],'k')\n\naxis([50 10^3*1.2 10^-2 10^1]);\n%set(gca,'YTick',[0.003 .01 .1 .3 1 3 10 30]);\nset(gca,'XTick',nn);\nset(gca,'LineWidth',2,'FontSize',12);\n\nxlabel('Sequence length','FontSize',12);\nylabel('Efficiency','FontSize',12);\ntitle(['No Overlap: n_e=',num2str(nVals),' p=',num2str(pEv),' n_h=',num2str(n2)]);\n\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,4,3]);\neval(['print -dpsc2 effNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh']);\ndisp(['print -dpsc2 effNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh']);\n\nfigure(2); clf;\nsemilogx(nn,mEffAll./max(rndEffAll'),'-ok','LineWidth',2); hold on;\nsemilogx(nn,mEffAll./med,':+k','LineWidth',2)\nset(gca,'Position',[.2,.15,.7,.7]);\nxlabel('Sequence length','FontSize',12);\nylabel('m-seq/random efficiency ratio','FontSize',12);\ntitle(['No Overlap: n_e=',num2str(nVals),' p=',num2str(pEv),' n_h=',num2str(n2)]);\nset(gca,'XTick',nn)\nset(gca,'LineWidth',2,'FontSize',12);\nset(gca,'Position',[.2,.15,.7,.7]);\nset(gcf,'PaperPosition',[1,1,4,3]);\naxis([50 10^3*1.2 .9 2.5]);\neval(['print -dpsc2 effNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nhRATIO']);\ndisp(['print -dpsc2 effNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nhRATIO']);\n\neval(['save dataEffNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh rndEffAll p99 p00 med mEffAll']);\ndisp(['save dataEffNOV',num2str(nVals),'ev',num2str(nReps),'reps',num2str(n2),'nh rndEffAll p99 p00 med mEffAll']);\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/M-sequence/mseq/effOFexpDesignsNoOverlap2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6247585232609865}} {"text": "%% Lucas-Kanade Optical Flow\n%\n% In this demo, we will:\n%\n% * understand the concepts of optical flow and its estimation using\n% Lucas-Kanade method.\n% * use functions like |cv.calcOpticalFlowPyrLK| to track feature points\n% in a video.\n%\n% Sources:\n%\n% * \n%\n\n%% Optical Flow\n%\n% Optical flow is the pattern of apparent motion of image objects between two\n% consecutive frames caused by the movemement of object or camera. It is 2D\n% vector field where each vector is a displacement vector showing the movement\n% of points from first frame to second. Consider the image below:\n%\n% <>\n%\n% It shows a ball moving in 5 consecutive frames. The arrow shows its\n% displacement vector. Optical flow has many applications in areas like:\n%\n% * Structure from Motion\n% * Video Compression\n% * Video Stabilization\n% * etc.\n%\n% Optical flow works on several assumptions:\n%\n% # The pixel intensities of an object do not change between consecutive frames\n% # Neighbouring pixels have similar motion\n%\n% Consider a pixel $I(x,y,t)$ in first frame. It moves by distance $(dx,dy)$\n% in next frame taken after $dt$ time. So since those pixels are the same and\n% intensity does not change, we can say,\n%\n% $$I(x,y,t) = I(x+dx, y+dy, t+dt)$$\n%\n% Then take taylor series approximation of right-hand side, remove common\n% terms and divide by $dt$ to get the following equation:\n%\n% $$f_x u + f_y v + f_t = 0$$\n%\n% where\n%\n% $$f_x = \\frac{\\partial f}{\\partial x} \\quad ; \\quad\n% f_y = \\frac{\\partial f}{\\partial y}$$\n%\n% $$u = \\frac{dx}{dt} \\quad ; \\quad\n% v = \\frac{dy}{dt}$$\n%\n% Above equation is called Optical Flow equation. In it, we can find $f_x$ and\n% $f_y$, they are image gradients. Similarly $f_t$ is the gradient along time.\n% But $(u,v)$ is unknown. We cannot solve this one equation with two unknown\n% variables. So several methods are provided to solve this problem and one of\n% them is Lucas-Kanade.\n%\n\n%% Lucas-Kanade method\n%\n% We have seen an assumption before, that all the neighbouring pixels will\n% have similar motion. Lucas-Kanade method takes a 3x3 patch around the point.\n% So all the 9 points have the same motion. We can find $(f_x, f_y, f_t)$ for\n% these 9 points. So now our problem becomes solving 9 equations with two\n% unknown variables which is over-determined. A better solution is obtained\n% with least square fit method. Below is the final solution which is two\n% equation-two unknown problem and solve to get the solution:\n%\n% $$\n% \\left[\\matrix{u \\cr v}\\right] =\n% \\left[\\matrix{\n% \\sum_{i}{f_{x_i}}^2 & \\sum_{i}{f_{x_i} f_{y_i}} \\cr\n% \\sum_{i}{f_{x_i} f_{y_i}} & \\sum_{i}{f_{y_i}}^2\n% }\\right]^{-1}\n% \\left[\\matrix{\n% - \\sum_{i}{f_{x_i} f_{t_i}} \\cr\n% - \\sum_{i}{f_{y_i} f_{t_i}}\n% }\\right]\n% $$\n%\n% (Note similarity of inverse matrix with Harris corner detector. It denotes\n% that corners are better points to be tracked.)\n%\n% So from user point of view, idea is simple, we give some points to track,\n% we receive the optical flow vectors of those points. But again there are\n% some problems. Until now, we were dealing with small motions. So it fails\n% when there is large motion. So again we go for pyramids. When we go up in\n% the pyramid, small motions are removed and large motions becomes small\n% motions. So applying Lucas-Kanade there, we get optical flow along with the\n% scale.\n%\n\n%% Lucas-Kanade Optical Flow in OpenCV\n%\n% OpenCV provides all these in a single function, |cv.calcOpticalFlowPyrLK|.\n% Here, we create a simple application which tracks some points in a video.\n% To decide the points, we use |cv.goodFeaturesToTrack|. We take the first\n% frame, detect some Shi-Tomasi corner points in it, then we iteratively track\n% those points using Lucas-Kanade optical flow. For the function\n% |cv.calcOpticalFlowPyrLK| we pass the previous frame, previous points and\n% next frame. It returns next points along with some status numbers which has\n% a value of 1 if next point is found, else zero. We iteratively pass these\n% next points as previous points in next step. See the code below.\n%\n% This code doesn't check how correct are the next keypoints. So even if any\n% feature point disappears in image, there is a chance that optical flow finds\n% the next point which may look close to it. So actually for a robust tracking,\n% corner points should be detected in particular intervals. OpenCV samples\n% comes up with such a sample which finds the feature points at every 5 frames.\n% It also run a backward-check of the optical flow points got to select only\n% good ones.\n%\n\n%% Video\n% Prepare video source\nif mexopencv.require('vision')\n vid = fullfile(toolboxdir('vision'), 'visiondata', 'visiontraffic.avi');\n %cap.PosFrames = 80; % skip first few seconds with no motion\nelseif true\n vid = fullfile(mexopencv.root(), 'test', '768x576.avi');\nelse\n vid = fullfile(mexopencv.root(), 'test', 'sparse_optical_flow.avi');\n if exist(vid, 'file') ~= 2\n disp('Downloading video...')\n url = 'https://cdn.rawgit.com/opencv/opencv_extra/3.2.0/gpu_demos_pack/demos/sparse_optical_flow/data/sparse_optical_flow.avi';\n urlwrite(url, vid);\n end\nend\nif exist(vid, 'file') ~= 2, vid = 0; end\ncap = cv.VideoCapture(vid);\nassert(cap.isOpened(), 'Failed to initialize capturing');\n\n%% First frame\n% Grab first frame\nframe = cap.read();\nassert(~isempty(frame), 'Failed to read frame');\nprev = cv.cvtColor(frame, 'RGB2GRAY');\n\n%%\n% Detect corners using Shi-Tomasi method (performed only once at the start)\npts0 = cv.goodFeaturesToTrack(prev, ...\n 'MaxCorners',100, 'QualityLevel',0.3, 'MinDistance',7, 'BlockSize',7);\npts0 = cat(1, pts0{:});\nassert(~isempty(pts0), 'No corners found');\nfprintf('%d points\\n', size(pts0,1));\n\n%%\n% Initialize a mask image for drawing purposes\n% (on which point tracks are drawn and remembered)\nmask = zeros(size(frame), class(frame));\n\n%%\n% Some random colors for plotting\nN = 64;\nclrs = uint8(hsv(N) * 255); % randi([0 255], [N 3])\nclrs(:,4) = 0;\n\n%%\n% Plot\nhImg = imshow(frame);\ntitle('PyrLK [Sparse]')\n\n%% Main loop\nwhile ishghandle(hImg)\n % Grab next frame\n frame = cap.read();\n if isempty(frame), break; end\n next = cv.cvtColor(frame, 'RGB2GRAY');\n\n % Calculate sparse optical flow using Lucas-Kanade method to track points\n [pts1, status] = cv.calcOpticalFlowPyrLK(prev, next, pts0, ...\n 'WinSize',[15 15], 'MaxLevel',2, ...\n 'Criteria',struct('type','Count+EPS', 'maxCount',10, 'epsilon',0.03));\n pts1 = cat(1, pts1{:});\n status = logical(status);\n\n % Keep good points (points for which the flow has been found)\n if ~any(status)\n break;\n elseif ~all(status)\n fprintf('%d points\\n', nnz(status));\n end\n pts0 = pts0(status,:);\n pts1 = pts1(status,:);\n\n % Draw latest locations of tracked points\n clr = clrs(rem((1:size(pts1,1))-1,N)+1,:); % cycle through colors\n frame = cv.circle(frame, pts1, 5, 'Colors',clr, 'Thickness','Filled');\n\n % Draw point tracks (comet-like plot)\n mask = cv.line(mask, pts1, pts0, 'Colors',clr, 'Thickness',2);\n frame = cv.addWeighted(frame, 0.5, mask, 0.5, 0.0);\n\n % Display result\n set(hImg, 'CData',frame);\n drawnow;\n\n % Next iteration: update the previous frame and previous points\n prev = next;\n pts0 = pts1;\nend\ncap.release();\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/lucas_kanade_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6247108536941531}} {"text": "%% OPTI Toolbox Global Nonlinear Program Demo\n%\n% This file contains a number of Global NLP problems and demonstrates how \n% to solve them using the OPTI Toolbox. You should read and complete\n% Basic_demo.m & LP_demo.m BEFORE running the below examples.\n%\n% Copyright (C) 2012 Jonathan Currie (I2C2)\n\n%% Determing which Solver to Use\n% OPTI Toolbox comes with a number of NLP solvers, thus to determine which\n% ones are available on your system you can type:\n\ncheckSolver('NLP')\n\n% Note the columns DR and GL. A cross in DR indicates the solver requires\n% 1st (and perhaps 2nd) derivatives, while a cross in GL indicates the\n% solver can solve Global Optimization problems. For noisy problems unless\n% you have exact derivatives, avoid solvers with a cross in DR.\n\n%% Typical Global Optimization Problems\n% Global optimization problems result from any of the following circumstances:\n%\n% - Objectives containing noise / a stochastic element\n% - Non-convex functions (functions which are not a bowl / hill in 2D)\n% - Objectives that include periodic functions (sin, cos)\n% - Parameter estimation of ODEs solved with adaptive step integrators\n% - Any problem that contains multiple local minima.\n%\n% An extreme example from Wolfram is shown below:\n\n%Objective\nfun = @(x) norm([x(1) - sin(2*x(1) + 3*x(2)) - cos(3*x(1) - 5*x(2));\n x(2) - sin(x(1) - 2*x(2)) + cos(x(1) + 3*x(2))]);\nlb = [-4;-4]; ub = [4;4];\nx0 = [-4;-4];\n\n%Plot \nn = 1e2;\nx = linspace(-4,4,n); y = linspace(-4,4,n); Z = zeros(n,n);\nfor i = 1:n\n for j = 1:n\n Z(j,i) = fun([x(i),y(j)]);\n end\nend\nsurfc(x,y,Z)\ncolormap summer; shading interp; lighting phong; view(-38,58);\nxlabel('x1'); ylabel('x2'); zlabel('obj'); title('Wolfram Global Optimization Problem'); \n\n%% Example 1 - Basic Setup\n% The main difference when solving a Global NLP is that OPTI treats Global\n% and Local NLP problems identically, and therefore you will have to specify\n% a Global solver. For this example we will build 4 OPTI objects with 4\n% different solvers:\n\n%Build OPTI Problem\nprob = optiprob('fun',fun,'bounds',lb,ub);\n%Choose Global Solver\nopts1 = optiset('solver','nomad');\nopts2 = optiset('solver','pswarm');\nopts3 = optiset('solver','nlopt','solverOpts',nloptset('algorithm','GN_DIRECT'));\nopts4 = optiset('solver','ipopt','warnings','off');\n\n%Pass to OPTI Constructor for Error Checking + Setup\nOpt1 = opti(prob,opts1); \nOpt2 = opti(prob,opts2); \nOpt3 = opti(prob,opts3); \nOpt4 = opti(prob,opts4); \n\n%% Example 1 - Solving the Problem\n% Call solve to solve the problem. Check the plot for a comparison of the\n% solution points. Note NOMAD and NLOPT are deterministic with the current\n% settings, PSWARM includes random elements, and IPOPT is for comparison of\n% a local solution.\n\n[x1,fval1] = solve(Opt1,x0);\n[x2,fval2] = solve(Opt2,x0);\n[x3,fval3] = solve(Opt3,x0);\n[x4,fval4] = solve(Opt4,x0);\n\nview(0,90); hold on;\nplot3(x0(1),x0(2),10,'kx','markersize',10);\nplot3(x1(1),x1(2),10,'ro'); text(x1(1)+0.1,x1(2)+0.1,10,sprintf('NOMAD: %f',fval1));\nplot3(x2(1),x2(2),10,'ro'); text(x2(1)+0.1,x2(2)-0.1,10,sprintf('PSWARM: %f',fval2));\nplot3(x3(1),x3(2),10,'ro'); text(x3(1)+0.1,x3(2)+0.2,10,sprintf('NLOPT: %f',fval3));\nplot3(x4(1),x4(2),10,'ro'); text(x4(1)+0.1,x4(2)+0.1,10,sprintf('IPOPT: %f',fval4));\nhold off;\n\n%% Problem 2 - Quartic\n% Includes Linear and Nonlinear Constraints\n\n%Problem\nfun = @(x) x(1)^4 - 14*x(1)^2 + 24*x(1) - x(2)^2;\n\n%Linear Constraints\nA = [-1 1]; b = 8;\n%Nonlinear Constraints\nnlcon = @(x) (-x(1)^2) - 2*x(1) + x(2);\nnlrhs = -2;\nnle = -1;\n%Bounds + Starting Guess\nlb = [-8;0];\nub = [10;10];\nx0 = [0;0];\n\n%% Example 2\n% Solving a constrained global optimization problem. Note linear\n% constraints will be converted to nonlinear ones for this solver\n\nopts = optiset('solver','nomad','solverOpts',nomadset('direction_type','lt 2n')); \nOpt = opti('fun',fun,'ineq',A,b,'nlmix',nlcon,nlrhs,nle,'bounds',lb,ub,'options',opts)\n\n%% Example 2 - Problem Solved\n% This will take 5-7 seconds...\n\n[x,fval,exitflag,info] = solve(Opt,x0) \n\n%% Problem 3 - Saddle Point\n% Note x0 is on the local minima side of the saddle\n\n%Problem\nfun = @(x) -2*x(1)*x(2);\n\n%Constraints\nlb = [-0.5;-0.5];\nub = [1;1];\nx0 = [-0.3;-0.3]; \n\n%Plot \nn = 1e2;\nx = linspace(-0.5,1,n); y = linspace(-0.5,1,n); Z = zeros(n,n);\nfor i = 1:n\n for j = 1:n\n Z(j,i) = fun([x(i),y(j)]);\n end\nend\nsurfc(x,y,Z); hold on; plot3(x0(1),x0(2),fun(x0),'r.','markersize',20); hold off;\ncolormap winter; shading flat; lighting gouraud; view(18,28);\nxlabel('x1'); ylabel('x2'); zlabel('obj'); title('Saddle Point Optimization Problem'); \n\n\n%% Example 3 - Solving with PSwarm\n% PSwarm solves bounded and linearly constrained global problems\n\nOpt = opti('fun',fun,'bounds',lb,ub,'options',optiset('solver','pswarm'))\n\n%% Example 3 - Problem Solved.\n% Note the PSwarm found the solution of the otherside of the saddle, check\n% the OPTI solution plot\n\n[x,fval,exitflag,info] = solve(Opt,x0) \nplot(Opt,3)\n\n%% Problem 4 - White Box Quartic\n% The following problem is the same as problem 2, however this time we are\n% going to solve it using a white box solver (SCIP). The SCIP interface\n% will parse the following functions into an algebraic description,\n% allowing SCIP to find a global solution to this problem.\n\n%Problem\nfun = @(x) x(1)^4 - 14*x(1)^2 + 24*x(1) - x(2)^2;\n\n%Linear Constraints\nA = [-1 1]; b = 8;\n%Nonlinear Constraints\nnlcon = @(x) (-x(1)^2) - 2*x(1) + x(2);\nnlrhs = -2;\nnle = -1;\n%Bounds + Starting Guess\nlb = [-8;0];\nub = [10;10];\nx0 = [0;0];\n\n%% Example 4 - Solving with SCIP\n% SCIP solves a subset of nonlinear and mixed integer problems, provided\n% the problem is deterministics and constains a subset of allowable functions.\n\nOpt = opti('fun',fun,'ineq',A,b,'nlmix',nlcon,nlrhs,nle,'bounds',lb,ub,...\n 'options',optiset('solver','scip'))\n\n%% Example 4 - Problem Solved.\n% Solution returned is guaranteed (within numerical tolerances) to be the\n% global solution. Note you must have an academic version of OPTI to use\n% SCIP.\n\n[x,fval,exitflag,info] = solve(Opt,x0) \n\n%% Summary\n% While Global Optimization solvers may take longer, many real engineering\n% problems result in noisy or non-convex objectives and local solvers will\n% often struggle to return a result, or fall into the closest local\n% optima. OPTI provides a range of competitive blackbox global optimization\n% solvers which can return much better results, as well as a white box\n% solver for academic users which guarantees a global solution.", "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/Demos/GNLP_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6247108302831164}} {"text": "function Wgrid = Fdirs2grid(W, aziRes, polarRes, CLOSED)\n%FDIRS2GRID Replicate vector function values on a regular grid\n%\n% Fdirs2grid takes a vector of values of function evaluated at a \n% spherical grid with the grid2dirs function, and convert it back to a \n% 2D grid. Useful for plotting with functions such as surf, or for \n% numerical integration numerically spherical functions.\n%\n% W: column vector of function values evaluated at each grid direction,\n% with the direction ordering given by grid2dirs. If W is a matrix\n% then each column is considered as a separate function to be\n% converted\n% aziRes: azimuth resolution of the grid in degrees (should be the same\n% as the one used in the grid2dirs function\n% polarRes: inclination resolution of the grid in degrees (should be \n% the same as the one used in the grid2dirs function\n% CLOSED: {0,1} if true then the returned matrix replicates the first\n% column of function values at 0deg azimuth also at 360deg,\n% useful for 3D plotting so that the shape does not have a\n% hole in the end (see plotSphFunction test script)\n%\n% Wgrid: if W is a vector then Wgrid is the 2D matrix of the function\n% values replicated on the grid points. If W is a matrix, then\n% Wgrid is a 3D matrix with one grid per column of W, on the 3rd\n% dimension.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Archontis Politis, 10/10/2013\n% archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif mod(360, aziRes) ~= 0 || mod(180, polarRes) ~= 0\n error('azimuth or elevation resolution should divide exactly 360 and 180deg')\nend\n\nif nargin<4\n CLOSED = 0;\nend\n\nNphi = 360/aziRes;\nNtheta = 180/polarRes+1;\n\nNf = size(W, 2);\nWgrid = zeros(Nphi, Ntheta, Nf);\nfor i = 1:Nf\n \n Wgrid(:, 2:end-1, i) = reshape(W(2:end-1, i), Nphi, Ntheta-2);\n Wgrid(:, 1, i) = ones(Nphi, 1) * W(1, i);\n Wgrid(:, end, i) = ones(Nphi, 1) * W(end, i);\nend\n\nif Nf~=1\n Wgrid = permute(Wgrid, [2 1 3]);\nelse\n Wgrid = Wgrid.';\nend\n\nif CLOSED\n Wgrid = horzcat(Wgrid, Wgrid(:,1,:));\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Harmonic-Transform", "sha": "ef8a69aedbaf467e2fccb50c810564d747ce3409", "save_path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform", "path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform/Spherical-Harmonic-Transform-ef8a69aedbaf467e2fccb50c810564d747ce3409/Fdirs2grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6247074854585671}} {"text": "function [ a, ipvt, info ] = dgefa ( a, lda, n )\n\n%*****************************************************************************80\n%\n%% DGEFA factors a real matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the matrix to be factored.\n%\n% Input, integer LDA, the leading dimension of A.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Output, real A(LDA,N), an upper triangular matrix and the multipliers \n% used to obtain it. The factorization can be written A=L*U, where L is \n% a product of permutation and unit lower triangular matrices, and U is \n% upper triangular.\n%\n% Output, integer IPVT(N), the pivot indices.\n%\n% Output, integer INFO, singularity indicator.\n% 0, normal value.\n% K, if U(K,K) == 0. This is not an error condition for this subroutine,\n% but it does indicate that DGESL or DGEDI will divide by zero if called.\n% Use RCOND in DGECO for a reliable indication of singularity.\n%\n\n%\n% Gaussian elimination with partial pivoting.\n%\n info = 0;\n\n for k = 1 : n - 1\n%\n% Find L = pivot index.\n%\n l = idamax ( n-k+1, a(k:n,k), 1 ) + k - 1;\n ipvt(k) = l;\n%\n% Zero pivot implies this column already triangularized.\n%\n if ( a(l,k) == 0.0 )\n info = k;\n continue\n end\n%\n% Interchange if necessary.\n%\n if ( l ~= k )\n [ a(l,k), a(k,k) ] = r8_swap ( a(l,k), a(k,k) );\n end\n%\n% Compute multipliers.\n%\n a(k+1:n,k) = - a(k+1:n,k) / a(k,k);\n%\n% Row elimination with column indexing.\n%\n for j = k+1 : n\n t = a(l,j);\n if ( l ~= k )\n a(l,j) = a(k,j);\n a(k,j) = t;\n end\n a(k+1:n,j) = daxpy ( n-k, t, a(k+1:n,k), 1, a(k+1:n,j), 1 );\n end\n\n end\n\n ipvt(n) = n;\n\n if ( a(n,n) == 0.0 )\n info = n;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dgefa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.7662936537604181, "lm_q1q2_score": 0.6247074760498406}} {"text": "function P = pu2_encode( L )\n% Perceptually uniform luminance encoding using the CSF from HDR-VDP-2\n%\n% P = pu2_encode( L )\n%\n% Transforms absolute luminance values L into approximately perceptually \n% uniform values P. \n%\n% This is meant to be used with display-referred quality metrics - the\n% image values much correspond to the luminance emitted from the target \n% HDR display.\n%\n% This is an improved encoding described in detail in the paper:\n%\n% Aydin, T. O., Mantiuk, R., & Seidel, H.-P. (2008). Extending quality\n% metrics to full luminance range images. Proceedings of SPIE (p. 68060B–10). \n% SPIE. doi:10.1117/12.765095\n%\n% Note that the P-values can be negative or greater than 255. Most metrics\n% can deal with such values.\n%\n% Copyright (c) 2014, Rafal Mantiuk \n\npersistent P_lut;\npersistent l_lut;\n\nl_min = -5;\nl_max = 10;\n\n\nif( isempty( P_lut ) ) % caching for better performance\n \n metric_par.csf_sa = [30.162 4.0627 1.6596 0.2712]; \n l_lut = linspace( l_min, l_max, 2^12 );\n S = hdrvdp_joint_rod_cone_sens( 10.^l_lut, metric_par );\n \n [~, P_lut] = build_jndspace_from_S(l_lut,S);\nend\n\n\nl = log10(max(min(L,10^l_max),10^l_min));\n\npu_l = 31.9270;\npu_h = 149.9244;\n\nP = 255 * (interp1( l_lut, P_lut, l ) - pu_l) / (pu_h-pu_l);\n\nend\n\nfunction S = hdrvdp_joint_rod_cone_sens( la, metric_par )\n% Copyright (c) 2011, Rafal Mantiuk \n\n% Permission to use, copy, modify, and/or distribute this software for any\n% purpose with or without fee is hereby granted, provided that the above\n% copyright notice and this permission notice appear in all copies.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\ncvi_sens_drop = metric_par.csf_sa(2); % in the paper - p6\ncvi_trans_slope = metric_par.csf_sa(3); % in the paper - p7\ncvi_low_slope = metric_par.csf_sa(4); % in the paper - p8\n\nS = metric_par.csf_sa(1) * ( (cvi_sens_drop./la).^cvi_trans_slope+1).^-cvi_low_slope;\n\nend\n\nfunction [Y jnd] = build_jndspace_from_S(l,S)\n\nL = 10.^l;\ndL = zeros(size(L));\n\nfor k=1:length(L)\n thr = L(k)/S(k);\n\n % Different than in the paper because integration is done in the log\n % domain - requires substitution with a Jacobian determinant\n dL(k) = 1/thr * L(k) * log(10);\nend\n\nY = l;\njnd = cumtrapz( l, dL );\n\nend\n\n\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Metrics/util/pu2_encode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6246505555291891}} {"text": "function [fMc, fBvalue, fAvalue, mu, fSigma] = calc_McEMR(catalog, binInterval)\n % Determine Mc using Entire Magnitude Range (EMR)-method. Calculates also a- and b-value.\n % [fMc, fBvalue, fAvalue, mu, fSigma] = calc_McEMR(catalog, binInterval);\n % -----------------------------------------------------------------------------------------------------\n % Determine Mc using EMR-method. Calculates also a- and b-value.\n % Fitting non-cumulative frequency magnitude distribution above and below Mc:\n % below: Cumulative NORMAL distribution function\n % above: Gutenberg-Richter law\n %\n % Incoming variables:\n % catalog : EQ catalog\n % binInterval : Binning interval, usually 0.1\n %\n % Outgoing variables:\n % fMc : Best estimated magnitude of completeness\n % fBvalue : b-value\n % fAvalue : a-value\n % mu : mu-value of the normal CDF\n % fSigma : sigma-values of the normal CDF\n %\n % J. Woessner: woessner@seismo.ifg.ethz.ch\n \n narginchk(2,2);\n \n % Initialize\n vProbability = [];\n vMc = [];\n vABValue =[];\n mFitRes = [];\n vDeltaBest = [];\n vX_res = [];\n vNmaxBest = [];\n mResult=[];\n \n % Determine exact time period\n timespan = years(max(catalog.Date) - min(catalog.Date)); % guessing it should be years\n \n % Set starting value for Mc loop and LSQ fitting procedure\n fMcTry= calc_Mc(catalog, McMethods.MaxCurvature);\n fSmu = abs(fMcTry / 2);\n fSSigma = abs(fMcTry / 4);\n if (fSmu > 1)\n fSmu = fMcTry / 10;\n fSSigma = fMcTry / 20;\n end\n fMcBound = fMcTry;\n \n % Calculate FMD for original catalog\n [vFMDorga, vNonCFMDorg, fmdbins] = calc_FMD(catalog.Magnitude);\n % convert answer back to this file's expectations...\n vFMDorg = [fmdbins'; vFMDorga']; % as rows\n vNonCFMDorg = [fmdbins'; vNonCFMDorg'];\n\n fMinMag = min(vNonCFMDorg(1,:));\n \n % %% Shift to positive values\n % if fMinMag ~= 0\n % fMcBound = fMcTry-fMinMag;\n % end\n % Loop over Mc-values\n for fMc = round(fMcBound-0.4 : 0.1 : fMcBound+0.4, -1)\n vFMD = vFMDorg;\n vNonCFMD = vNonCFMDorg;\n vNonCFMD = fliplr(vNonCFMD);\n % Calculate a and b-value for GR-law and distribution vNCum\n [~, ~, vSel, ~] = fMagToFitBValue(catalog, vFMD, fMc);\n if (length(catalog.Longitude(vSel)) >= 20)\n %[ fBValue, fStdDev, fAValue] = calc_bmemag(catalog.Magnitude(vSel), binInterval);\n [fBValue, ~, fAValue] = calc_bmemag(catalog.Magnitude(vSel), binInterval);\n % Normalize to time period\n vFMD(2,:) = vFMD(2,:)./timespan; % ceil taken out\n vNonCFMD(2,:) = vNonCFMD(2,:)./timespan; % ceil removed\n % Compute quantity of earthquakes by power law\n fMaxMagFMD = max(vNonCFMD(1,:));\n fMinMagFMD = min(vNonCFMD(1,:));\n vMstep = fMinMagFMD:0.1:fMaxMagFMD;\n vNCum = 10.^(fAValue-fBValue.*vMstep); % Cumulative number\n \n % Compute non-cumulative numbers vN\n fNCumTmp = 10^(fAValue - fBValue * (fMaxMagFMD + 0.1));\n vNCumTmp = [vNCum, fNCumTmp ];\n vN = abs(diff(vNCumTmp));\n \n % Normalize vN\n vN = vN./timespan;\n % Data selection\n % mData = Non-cumulative FMD values from GR-law and original data\n mData = [vN' vNonCFMD'];\n vSel = (mData(:,2) >= fMc);\n mDataTest = mData(~vSel,:);\n mDataTmp = mData(vSel,:);\n % Check for zeros in observed data\n vSelCheck = (mDataTest(:,3) == 0);\n mDataTest = mDataTest(~vSelCheck,:);\n % Choices of normalization\n fNmax = mDataTmp(1,3); % Frequency of events in Mc bin\n \n if (~isempty(isempty(fNmax)) && ~isnan(fNmax) & fNmax ~= 0 & length(mDataTest(:,1)) > 4)\n mDataTest(:,3) = mDataTest(:,3)/fNmax; % Normalize datavalues for fitting with CDF\n % Move to M=0 to fit with lsq-algorithm\n fMinMagTmp = min(mDataTest(:,2));\n mDataTest(:,2) = mDataTest(:,2)-fMinMagTmp;\n % Curve fitting: Non cumulative part below Mc\n options = optimset('Display','off',...\n 'Tolfun' , 1e-5,...\n 'TolX' , 0.001,...\n 'MaxFunEvals' , 1000,...\n 'MaxIter' , 1000);\n [vX, resnorm, resid, exitflag, output, lambda, jacobian] = lsqcurvefit(...\n @calc_normalCDF,[fSmu fSSigma], mDataTest(:,2), mDataTest(:,3),[],[], options);\n mDataTest(:,1) = normcdf(mDataTest(:,2), vX(1), vX(2))*fNmax;\n if (length(mDataTest(:,2)) > length(vX(1,:)))\n %% Confidence interval determination\n % vPred : Predicted values of lognormal function\n % vPred+-delta : 95% confidence level of true values\n [vPred,delta] = nlpredci(@calc_normalCDF, mDataTest(:,2), vX, resid, jacobian);\n else\n vPred = NaN;\n delta = NaN;\n end % END: This section is due for errors produced with datasets less long than amount of parameters in vX\n % Results of fitting procedure\n mFitRes = [mFitRes; vX resnorm exitflag];\n % Move back to original magnitudes\n mDataTest(:,2) = mDataTest(:,2)+fMinMagTmp;\n % Set data together\n mDataTest(:,3) = mDataTest(:,3)*fNmax;\n mDataPred = [mDataTest; mDataTmp];\n % Denormalize to calculate probabilities\n mDataPred(:,1) = round(mDataPred(:,1).*timespan);\n mDataPred(:,3) = mDataPred(:,3).*timespan;\n vProb_ = calc_log10poisspdf2(mDataPred(:,3), mDataPred(:,1)); % Non-cumulative\n \n % Sum the probabilities\n fProbability = (-1) * sum(vProb_,'omitnans');\n vProbability = [vProbability; fProbability];\n % Move magnitude back\n mDataPred(:,2) = mDataPred(:,2)+fMinMag;\n vMc = [vMc; fMc];\n vABValue = [vABValue; fAValue fBValue];\n \n % Keep values\n vDeltaBest = [vDeltaBest; delta];\n vX_res = [vX_res; vX resnorm exitflag];\n vNmaxBest = [vNmaxBest; fNmax];\n \n % Keep best fitting model\n if (fProbability == min(vProbability))\n vDeltaBest = delta;\n vPredBest = [mDataTest(:,2) vPred*fNmax*timespan delta*fNmax*timespan]; % Gives back uncertainty\n mDatPredBest = [mDataPred];\n end\n else\n %disp('Not enough data');\n % Setting values\n fProbability = NaN;\n fMc = NaN;\n vX(1) = NaN;\n vX(2) = NaN;\n resnorm = NaN;\n exitflag = NaN;\n delta = NaN;\n vPred = [NaN NaN NaN];\n fNmax = NaN;\n fAValue = NaN;\n fBValue = NaN;\n vProbability = [vProbability; fProbability];\n vMc = [vMc; fMc];\n vX_res = [vX_res; vX resnorm exitflag];\n % vDeltaBest = [vDeltaBest; NaN];\n % vPredBest = [vPredBest; NaN NaN NaN];\n vNmaxBest = [vNmaxBest; fNmax];\n vABValue = [vABValue; fAValue fBValue];\n end % END of IF fNmax\n end % END of IF length(catalog.Longitude(vSel))\n \n end % END of FOR fMc\n % Result matrix\n mResult = [mResult; vProbability vMc vX_res vNmaxBest vABValue];\n \n % Find best estimate, excluding the case of mResult all NAN\n if ~isempty(min(mResult)) && ~isnan(min(mResult(:,1)))\n vSel = find(min(mResult(:,1)) == mResult(:,1));\n fMc = min(mResult(vSel,2));\n %fMls = min(mResult(vSel,1));\n mu = min(mResult(vSel,3));\n fSigma = min(mResult(vSel,4));\n fAvalue = min(mResult(vSel,8));\n fBvalue = min(mResult(vSel,9));\n else\n fMc = NaN;\n %fMls = NaN;\n mu = NaN;\n fSigma = NaN;\n fAvalue = NaN;\n fBvalue = NaN;\n end\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/jochen/seisvar/calc/calc_McEMR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.624650547584565}} {"text": "function x = mono_next_grlex ( m, x )\n\n%*****************************************************************************80\n%\n%% MONO_NEXT_GRLEX: grlex next monomial.\n%\n% Discussion:\n%\n% Example:\n%\n% M = 3\n%\n% # X(1) X(2) X(3) Degree\n% +------------------------\n% 1 | 0 0 0 0\n% |\n% 2 | 0 0 1 1\n% 3 | 0 1 0 1\n% 4 | 1 0 0 1\n% |\n% 5 | 0 0 2 2\n% 6 | 0 1 1 2\n% 7 | 0 2 0 2\n% 8 | 1 0 1 2\n% 9 | 1 1 0 2\n% 10 | 2 0 0 2\n% |\n% 11 | 0 0 3 3\n% 12 | 0 1 2 3\n% 13 | 0 2 1 3\n% 14 | 0 3 0 3\n% 15 | 1 0 2 3\n% 16 | 1 1 1 3\n% 17 | 1 2 0 3\n% 18 | 2 0 1 3\n% 19 | 2 1 0 3\n% 20 | 3 0 0 3\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer X(M), the current monomial.\n% The first item is X = [ 0, 0, ..., 0, 0 ].\n%\n% Output, integer X(M), the next monomial.\n%\n\n%\n% Ensure that 1 <= M.\n%\n if ( m < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_NEXT_GRLEX - Fatal error!' );\n fprintf ( 1, ' M < 1\\n' );\n error ( 'MONO_NEXT_GRLEX - Fatal error!' );\n end\n%\n% Ensure that 0 <= XC(I).\n%\n for i = 1 : m\n if ( x(i) < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_NEXT_GRLEX - Fatal error!' );\n fprintf ( 1, ' X(I) < 0\\n' );\n error ( 'MONO_NEXT_GRLEX - Fatal error!' );\n end\n end\n%\n% Find I, the index of the rightmost nonzero entry of X.\n%\n i = 0;\n for j = m : -1 : 1\n if ( 0 < x(j) )\n i = j;\n break\n end\n end \n%\n% set T = X(I)\n% set X(I) to zero,\n% increase X(I-1) by 1,\n% increment X(M) by T-1.\n%\n if ( i == 0 )\n x(m) = 1;\n return\n elseif ( i == 1 )\n t = x(1) + 1;\n im1 = m;\n elseif ( 1 < i )\n t = x(i);\n im1 = i - 1;\n end\n\n x(i) = 0;\n x(im1) = x(im1) + 1;\n x(m) = x(m) + t - 1;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polynomial/mono_next_grlex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6245340769250909}} {"text": "% Figure 10.45 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% fig10_45.m is a script to generate Fig. 10.45 the step response for the SRL\n% design for the aircraft with state feedback augmenting the\n% inner loop stabilization\nclf;\n%system matrices\nftq =[-0.0064 0.0263 0 -32.2000 0;\n -0.0941 -0.6240 761.1400 -196.2000 0;\n -0.0002 -0.0015 -4.4120 -12.4800 0;\n 0 0 1.0000 0 0;\n 0 -1.0000 0 830.0000 0];\ng=[0; -32.7; -2.08; 0; 0];\nh=[0 0 0 0 1];\nj=0;\nk=[-.0011 .0016 -.0833 -1.613 -.0010];\nfc=ftq-g*k;\n% dc gain\ndcgain=-h*inv(fc)*g;\nr=100/dcgain;\nt=0:.3:30;\n% step response\ny=step(fc,g*r,h,j,1,t);\nplot(t,y);\nv=[0, 30, 0, 100];\naxis(v);\nxlabel('Time (sec)');\nylabel('Altitude, h (ft)');\ngrid;\n\ntitle( 'Fig. 10.45 Step response of the altitude autopilot')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_45.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.624503870191048}} {"text": "function [dynpcm2] = MPa2dynpcm2(MPa)\n% Convert pressure from megapascals to dyn per sq-cm\n% Chad Greene 2012\ndynpcm2 = MPa*1.00000e+7;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/MPa2dynpcm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6245034603564104}} {"text": "function [distances,v,w] = convolutionalDistance(p0,p1,areaWeights,kernel,kernelTranspose,options)\n\n% convolutionalDistance - compute entropy-OT ditance and rescaling factors\n% [distances,v,w] = convolutionalDistance(p0,p1,kernel,kernelTranspose, options)\n%\n% The normalized coupling reads\n% pi = diag(v)*K*diag(w)\n% and it should satisfy\n% pi*a = p1\n% and pi'*a = p0\n\nn = size(p0,1);\noptions.null = 0;\nniter = getoptions(options, 'niter', 100);\ntol = getoptions(options, 'tol', 1e-6);\nverb = getoptions(options, 'verb', 1);\ndisplayFunction = getoptions(options, 'disp', @(x,y) disp(''));\ndisp_rate = getoptions(options, 'disp_rate', 10);\ndisp_time = getoptions(options, 'disp_time', 0);\n\nif nargin<5 || isempty(kernelTranspose);\n kernelTranspose = kernel; % assume symmetry\nend\n\nif isempty(areaWeights)\n areaWeights = ones(n,1);\nend\n\np0 = p0+eps;\np1 = p1+eps;\n\nv = ones(size(p0));\nw = ones(size(p1));\n\ndistances = zeros(size(v,2),1);\n\nA = sum(areaWeights);\naw = bsxfun(@times,areaWeights,w);\n\nfor i=1:niter\n if disp_time\n tic\n end\n \n v = p1 ./ kernel(aw);\n av = bsxfun(@times,areaWeights,v);\n w = p0 ./ kernelTranspose(av);\n aw = bsxfun(@times,areaWeights,w);\n \n oldDistances = distances;\n \n ll = @(x) real(log(x));\n lv = av.*ll(v);\n lw = aw.*ll(w);\n distances = sum((log(A)*av+lv).*kernel(aw),2) + sum(av.*kernel(lw),2);\n \n change = norm(oldDistances-distances,'fro');\n \n if verb==1, fprintf('Iteration %d: %g\\n', i, change);\n elseif verb==2, progressbar(i,niter); end\n \n if isa(displayFunction,'function_handle') && mod(i,disp_rate)==1\n displayFunction(v,w); drawnow;\n end\n \n if change 2\n if verb==2, progressbar(niter,niter); end\n break;\n end\n \n if disp_time, toc, end\nend\n\ndistances = sqrt(max(distances,0));\nfprintf('\\n');", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/convolutional_wasserstein/convolutionalDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6245034398071618}} {"text": "function [i1_rect,i2_rect] = rect_pollefeys(F,i1,i2)\n\n% function [i1_rect,i2_rect] = rect_pollefeys(i1,i2,F,P1,P2)\n%\n%\t[i1_rect,i2_rect]=rect_pollefeys(i1,i2,F,P1,P2)\n%\n%\n%Rectifies a pair of images related by fundamental F\n%\n%IN:\n%\ti1 - Matlab image\n%\ti2 - Matlab image\n%\tF - Fundamental matrix (p1'*F*p2=0). Assumes that image coordiantes\n%\t\tare 1..width where pixel centers are at integer locations.\n%\n%OUT:\n%\tfig - handle to the figure\n[w,h,~] = size(i1);\nline = 0;\n\n% C1 = null(P1);\n% e2 = P2*C1;\ne1 = null(F);\ne2 = null(F');\ne2 = e2/e2(3);\n% C2 = null(P2);\n% e1 = P1*C2;\ne1 = e1/e1(3);\nthetas = get_theta_bounds(e1,e2,F,[w,h]);\ntheta = thetas(1);\nif 0,\n h0 = my_figure(gr1,gr2,F);\n ud = get(gcf, 'UserData');\nend\n\nwhile theta=1) (xf<=w & xf>=1) (ys<=h & ys>=1) (yf<=h & yf>=1)];\nv = w2>0;\npts = [m1(:,v)];", "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/42209-image-rectification/rect_pollefeys.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.624503434686543}} {"text": "function [ly] = pm2ly(pm)\n% Convert length from picometers to light years.\n% Never know when you might need this. \n% Chad A. Greene 2012\nly = pm*1.05702341e-28;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/pm2ly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6245034294991504}} {"text": "% GET THE QUATERNION BETWEEN TWO VECTORS\nfunction [q] = qArgument(u,v)\nq = zeros(4,1);\n% Normalise the quaternion\nu = u/norm(u);\nv = v/norm(v);\n% Get the axis vector\nq(2:4) = cross(u,v);\n% Define the rotation about that vector\nq(1) = sqrt((norm(u)^2)*(norm(v)^2)) + dot(u,v);\n% Normalise the quaternion\n[q] = unit(q);\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/common/qArgument.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6244873523916983}} {"text": "function [s] = gsp_filter_synthesis(G, filters, c, param)\n%GSP_FILTER_SYNTHESIS Synthesis operator of a gsp filterbank\n% Usage: s = gsp_filter_synthesis(G, filters, c);\n% s = gsp_filter_synthesis(G, filters, c, param);\n%\n% Input parameters:\n% G : Graph structure.\n% filters : Set of spectral graph filters.\n% c : Transform coefficients\n% param : Optional parameter\n% Output parameters:\n% signal : sythesis signal\n%\n% 'gsp_filter_synthesis(G,filters,c)' computes the synthesis\n% operator for coefficient $c$, where the atoms of the transform \n% dictionary are generalized translations of each graph spectral filter\n% to each vertex on the graph.\n%\n% .. f = D * c \n%\n% .. math:: f = D c\n%\n% where the columns of $D$ are $g_{i,m}=T_i g_m$, and $T_i$ is a\n% generalized translation operator applied to each filter \n% $\\hat{g}_m(\\cdot)$. \n%\n% Each column of *c* is the response of the signal to one filter.\n%\n% Example:::\n%\n% Nf = 4;\n% G = gsp_sensor(30);\n% G = gsp_estimate_lmax(G);\n% G = gsp_estimate_lmax(G);\n% g = gsp_design_mexican_hat(G, Nf); \n% f = zeros(G.N,1);\n% f(1) = 1;\n% f = G.L^2*f;\n% ff = gsp_filter_analysis(G,g,f);\n% f2 = gsp_filter_synthesis(G,g,ff);\n% paramplot.show_edges = 1;\n% figure()\n% subplot(211)\n% gsp_plot_filter(G,g)\n% subplot(223)\n% gsp_plot_signal(G,f,paramplot);\n% subplot(224)\n% gsp_plot_signal(G,f2,paramplot); \n%\n% Additional parameters\n% ---------------------\n% \n% * *param.method* : Select the method to be used for the computation.\n% * 'exact' : Exact method using the graph Fourier matrix\n% * 'cheby' : Chebyshev polynomial approximation\n% * 'lanczos' : Lanczos approximation\n% Default: if the Fourier matrix is present: 'exact' otherwise 'cheby'\n% * *param.order* : Degree of the Chebyshev approximation\n% (default=30). \n% * *param.verbose* : Verbosity level (0 no log - 1 display warnings)\n% (default 1). \n%\n% See also: gsp_filter_analysis gsp_filter_inverse\n% \n% References: hammond2011wavelets\n%\n\n% Author: Nathanael Perraudin\n% Testing: test_filter\n% Date: 19 March 2014\n\n% TODO: Perfect\n \n% Read input parameters\nif nargin < 4\n param = struct;\nend\n\nif iscell(G)\n NG = numel(G);\n s = cell(NG,1);\n for ii = 1:NG\n warning('Check what happen here')\n s{ii} = gsp_filter_synthesis(G{ii}, filters{ii}, c{ii}, param);\n% if iscell(s)\n% c{ii} = gsp_filter_analysis(G{ii}, fi{ii}, s{ii}, param);\n% else\n% c{ii} = gsp_filter_analysis(G{ii}, fi{ii}, s, param);\n% end\n end\n return\nend\n\n\nif isnumeric(filters)\n Nf = size(filters,2);\nelse \n Nf = numel(filters);\nend\n\nif isfield(param, 'exact')\n warning('param.exact is not used anymore. Please use param.method instead');\n if param.exact\n param.method = 'exact';\n else\n param.method = 'cheby';\n end\nend\n\nif ~isfield(param,'method')\n if gsp_check_fourier(G)\n param.method = 'exact';\n else\n param.method = 'cheby';\n end\nend\n\nif ~isfield(param,'order'); param.order = 30; end\nif ~isfield(param,'verbose'); param.verbose = 1; end\n\nif isfield(param, 'cheb_order')\n param.order = param.cheb_order;\n warning('param.cheb_order is not used anymore. Please use param.order instead');\nend\n\n\n\nswitch param.method\n case 'exact' \n\n if ~gsp_check_fourier(G)\n if param.verbose\n warning(['GSP_FILTER_SYNTHESIS: The Fourier matrix is not ',...\n 'available. The function will compute it for you. ',...\n 'However, if you apply many time this function, you ',...\n 'should precompute it using the function: ',...\n 'gsp_compute_fourier_basis']);\n end\n G=gsp_compute_fourier_basis(G);\n end\n if isnumeric(filters)\n fie = filters;\n else\n fie = gsp_filter_evaluate(filters,G.e);\n end\n% Nv = size(c,2);\n% s =zeros(G.N,size(c,2));\n% for ii=1:Nf\n% s = s + G.U * ...\n% (repmat(fie(:,ii),1,Nv) ...\n% .* (G.U' * c((1:G.N)+G.N * (ii-1),:)));\n% end\n\n chat = gsp_gft(G,gsp_vec2mat(c,numel(filters)));\n shat = squeeze(sum(bsxfun(@times, fie, chat), 2));\n s = gsp_igft(G, shat);\n\n case 'cheby'\n if ~isfield(G,'lmax');\n G = gsp_estimate_lmax(G);\n if param.verbose\n warning(['GSP_FILTER_ANALYSIS: The variable lmax is not ',...\n 'available. The function will compute it for you. ',...\n 'However, if you apply many time this function, you ',...\n 'should precompute it using the function: ',...\n 'gsp_estimate_lmax']);\n end\n end\n\n\n cheb_coeffs = gsp_cheby_coeff(G, filters,...\n param.order, param.order +1); \n\n s=zeros(G.N,size(c,2));\n\n for ii=1:Nf\n s = s + gsp_cheby_op(G,cheb_coeffs(:,ii),c((1:G.N)+G.N * (ii-1),:));\n end\n\n \n case 'lanczos'\n s=zeros(G.N,size(c,2));\n if ~iscell(filters)\n filters = {filters};\n end\n for ii=1:Nf\n s = s + gsp_lanczos_op(G, filters{ii}, c((1:G.N)+G.N * (ii-1),:), param);\n end\n \n otherwise\n error('Unknown method: please select exact, cheby or lanczos');\nend\n\nend\n\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/filters/gsp_filter_synthesis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6244696085415861}} {"text": "%DEMO_BAYESIANOPTIMIZATION3 A demonstration program for Bayesian\n% optimization with constraints\n%\n% The set of BO demos\n% Part 1: see demo_bayesoptimization1\n% One dimensional example \n%\n% Part 2: see demo_bayesoptimization3\n% Two dimensional example \n%\n% Part 3: this file\n% Two dimensional example with constraints \n% * The implementation of constraints follows Gelbart et al. (2014)\n% \n% References:\n% Jones, D., Schonlau, M., & Welch, W. (1998). Efficient global\n% optimization of expensive black-box functions. Journal of Global\n% Optimization, 13(4), 455-492. doi:10.1023/a:1008306431147 \n%\n% Michael A. Gelbart, Jasper Snoek, and Ryan P. Adams\n% (2014). Bayesian Optimization with Unknown Constraints.\n% http://arxiv.org/pdf/1403.5607v1.pdf\n%\n% Snoek, J., Larochelle, H, Adams, R. P. (2012). Practical Bayesian\n% Optimization of Machine Learning Algorithms. NIPS 25 \n%\n% Copyright (c) 2015 Jarno Vanhatalo\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%% Part 3:\n% Two dimensional example with constraints \n% For testing purposes:\nstack = dbstack;\nif (~isempty(stack) && (strcmp(stack(end).name, 'runtestset') || strcmp(stack(end).name, 'runtests'))) test = 1; else test = 0; end;\n\nrng(3)\n% Construct function handles to objective function (fx) and two constraint\n% functions (fxc, fxc2)\nfx = @(x) -log( (mvnpdf([x(:,1) x(:,2)],[3.5 2.5], [1 0.3; 0.3 1]) + 0.3*mvnpdf([x(:,1) x(:,2)],[7 8], [3 0.5; 0.5 4])).*...\n mvnpdf([x(:,1) x(:,2)],[5 5], [100 0; 0 100])) ./15 -1;\nfxc = @(x) ((x(:,1)-5) .^2 + (x(:,2)-5).^2 -1)/30;\nfxc2 = @(x) ( (x(:,1)-5) .^2)./30 - 0.5;\n\n% The upper and lower limits for the constraints\nconst = [0 0.8 ; -10 0.1];\n\n% Help variables for visualization\nlb=0;\nub=10;\n[X,Y] = meshgrid(linspace(lb,ub,100),linspace(lb,ub,100));\nxl = [X(:) Y(:)];\nZ = reshape(fx(xl),100,100);\nZc1 = fxc(xl); Zc1(Zc1const(1,2)) = nan; \nZc1(~isnan(Zc1))=1; Zc1 = reshape(Zc1,100,100);\nZc2 = fxc2(xl); Zc2(Zc2const(2,2)) = nan;\nZc2(~isnan(Zc2))=1; Zc2 = reshape(Zc2,100,100);\n\n% ----- conduct Bayesian optimization -----\n\n% construct GP models for the objective function and constraint functions\ncfc = gpcf_constant('constSigma2',10,'constSigma2_prior', prior_fixed);\ncfse = gpcf_sexp('lengthScale',[1 1]);\ncfl = gpcf_linear('coeffSigma2', 10); \ncfl2 = gpcf_squared('coeffSigma2', 10, 'interactions', 'on');\nlik = lik_gaussian('sigma2', 0.001, 'sigma2_prior', prior_fixed);\n% GP model for objective function\n%gp1 = gp_set('cf', {cfc, cfl, cfl2, cfse}, 'lik', lik);cfl, cfl2, \ngp1 = gp_set('cf', {cfc, cfse}, 'lik', lik);\n% GP models for constraint functions\ngpc1 = {gp_set('cf', {cfc, cfse}, 'lik', lik, 'jitterSigma2', 1e-6),...\n gp_set('cf', {cfc, cfse}, 'lik', lik, 'jitterSigma2', 1e-6)};\n\n% Set the options for optimizer of the acquisition function\noptimf = @fmincon;\noptdefault=struct('GradObj','on','LargeScale','on','Algorithm','interior-point','TolFun',1e-9,'TolX',1e-6, 'Display', 'iter');\nopt=optimset(optdefault);\nlb=[0 0]; % lower bound of the input space\nub=[10 10]; % upper bound of the input space\n\n% draw initial points\n% we assume that at first we don't have any observation from the objective\n% function but only observations from constraint functions. Hence x and y\n% are initialized to zero\nx = [];\ny = [];\nxc1 = 10*rand(2,2);\nyc1 = fxc(xc1);\nxc2 = 10*rand(5,2);\nyc2 = fxc2(xc2);\n\nfigure, % figure for visualization\ni1 = 1;\nmaxiter = 25;\nimprov = inf; % improvement between two successive query points\nwhile i1 < maxiter && improv>1e-6\n%while i1 < maxiter\n % Train the GP models and calculate variables that are needed when\n % calculating the Expected improvement (Acquisition function) \n % Objective function\n if ~isempty(x)\n gp = gp_optim(gp1,x,y);\n [K, C] = gp_trcov(gp,x);\n invC = inv(C);\n a = C\\y;\n fmin = min( fx(x) );\n else\n a=[];\n x=[];\n invC=[];\n fmin=[];\n gp=gp1;\n end\n % constrain function 1\n gpct = gp_optim(gpc1{1},xc1,yc1);\n [~, Cct] = gp_trcov(gpct,xc1);\n const1.gpc = gpct;\n const1.invCc = inv(Cct);\n const1.ac = Cct\\yc1;\n const1.const = const(1,:);\n const1.xc = xc1;\n % constrain function 2\n gpct = gp_optim(gpc1{2},xc2,yc2);\n [~, Cct] = gp_trcov(gpct,xc2);\n const2.gpc = gpct;\n const2.invCc = inv(Cct);\n const2.ac = Cct\\yc2;\n const2.const = const(2,:);\n const2.xc = xc2;\n \n % Calculate EI and the posterior of the functions for visualization\n if ~isempty(x)\n [Ef,Varf] = gp_pred(gp, x, y, xl);\n EI = expectedimprovement_eg(xl, gp, x, a, invC, fmin, const1, const2);\n else\n Ef = zeros(size(xl,1),1);\n Varf = zeros(size(xl,1),1);\n EI = zeros(size(xl,1),1);\n end\n [Efc1] = gp_pred(const1.gpc, xc1, yc1, xl);\n [Efc2] = gp_pred(const2.gpc, xc2, yc2, xl);\n\n % optimize acquisition function\n % * Note! Opposite to the standard notation we minimize negative Expected\n % Improvement since Matlab optimizers seek for functions minimum\n % * Note! We alternate the acquisition function between Expected\n % Improvement and expected variance. The latter helps the\n % optimization so that it does not get stuck in local mode\n % Here we use multiple starting points for the optimization so that we\n % don't crash into suboptimal mode of acquisition function\n% if mod(i1,5)==0 %Do just exploration by finding the maimum variance location \n% fh_eg = @(x_new) expectedvariance_eg(x_new, gp, x, [], invC);\n% else\n fh_eg = @(x_new) expectedimprovement_eg(x_new, gp, x, a, invC, fmin, const1, const2);\n% end\n nstarts = 20;\n xstart = [repmat(lb,nstarts,1) + repmat(ub-lb,nstarts,1).*rand(nstarts,2) ]; %; repmat(x(indbest,:),2,1)+0.1*randn(2,size(x,2))\n for s1=1:nstarts\n x_new(s1,:) = optimf(fh_eg, xstart(s1,:), [], [], [], [], lb, ub, [], opt);\n end\n xnews = x_new;\n EIs = fh_eg(x_new);\n x_new = x_new( find(EIs==min(EIs),1), : );\n \n % New sample point\n x(end+1,:) = x_new;\n y(end+1,:) = fx(x(end,:));\n xc1(end+1,:) = x_new;\n yc1(end+1,:) = fxc(x(end,:));\n xc2(end+1,:) = x_new;\n yc2(end+1,:) = fxc2(x(end,:));\n\n % visualize\n clf\n % Plot the objective function\n subplot(2,4,1),hold on, title('Objective, query points')\n pcolor(X,Y,Z),shading flat\n clim = caxis;\n plot(x(1:end-1,1),x(1:end-1,2), 'rx', 'MarkerSize', 10),\n plot(x(end,1),x(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3)\n % Plot the posterior mean of the GP model\n subplot(2,4,2),hold on, title(sprintf('GP prediction, mean, iter: %d',i1))\n pcolor(X,Y,reshape(Ef,100,100)),shading flat\n caxis(clim)\n % Plot the posterior variance of GP model\n subplot(2,4,6),hold on, title('GP prediction, variance')\n pcolor(X,Y,reshape(Varf,100,100)),shading flat\n plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10)\n plot(x(end,1),x(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3)\n plot(x(1:end-1,1),x(1:end-1,2), 'rx', 'MarkerSize', 10),\n \n % The expected information \n subplot(2,4,5), hold on, title(sprintf('Expected improvement %.2e', min(EIs)))\n pcolor(X,Y,reshape(EI,100,100)),shading flat\n plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10)\n plot(x(end,1),x(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3)\n plot(x(1:end-1,1),x(1:end-1,2), 'rx'),\n \n % constraint 1\n subplot(2,4,3), hold on, title(sprintf('constraint 1'))\n pcolor(X,Y,Zc1),shading flat \n plot(xc1(1:end-1,1),xc1(1:end-1,2), 'rx', 'MarkerSize', 10);\n plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10);\n plot(xc1(end,1),xc1(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3);\n % constraint 2\n subplot(2,4,4), hold on, title(sprintf('constraint 2'))\n pcolor(X,Y,Zc2),shading flat \n l1= plot(xc2(1:end-1,1),xc2(1:end-1,2), 'rx', 'MarkerSize', 10);\n l2=plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10);\n l3=plot(xc2(end,1),xc2(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3);\n legend([l1,l2,l3], {'function evaluation points','local modes of acquisition function','The next query point'})\n \n % prediction of constraint 1\n subplot(2,4,7), hold on, title(sprintf('prediction for const 1'))\n Efc1(Efc1const(1,2)) = nan; \n Efc1(~isnan(Efc1))=1; Efc1 = reshape(Efc1,100,100);\n pcolor(X,Y,reshape(Efc1,100,100)),shading flat\n plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10)\n plot(xc1(end,1),xc1(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3)\n plot(xc1(1:end-1,1),xc1(1:end-1,2), 'rx'), \n % prediction of constraint 2\n subplot(2,4,8), hold on, title(sprintf('prediction for const 2'))\n Efc2(Efc2const(2,2)) = nan; \n Efc2(~isnan(Efc2))=1; Efc2 = reshape(Efc2,100,100);\n pcolor(X,Y,reshape(Efc2,100,100)),shading flat\n plot(xc2(1:end-1,1),xc2(1:end-1,2), 'rx', 'MarkerSize', 10),\n plot(xnews(:,1),xnews(:,2), 'ro', 'MarkerSize', 10)\n plot(xc2(end,1),xc2(end,2), 'ro', 'MarkerSize', 10, 'linewidth', 3)\n \n \n if length(y)>1\n improv = abs(y(end) - y(end-1));\n end\n i1=i1+1;\n \n if test == 0\n pause\n end\nend\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/demo_bayesoptimization3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6244696010167861}} {"text": "function [ fea, out ] = ex_planestress6( varargin )\n%EX_PLANESTRESS6 Plane stress analysis of a pressure vessel.\n%\n% [ FEA, OUT ] = EX_PLANESTRESS6( VARARGIN ) Model example for plain stress\n% approximation of a pressure vessel (annular cross section with symmetry).\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% E scalar {207e9} Modulus of elasticity\n% nu scalar {0.27} Poissons ratio\n% sfun string {sflag1} Shape function for displacements\n% iplot scalar 0/{1} Plot solution (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'E', 207e9; ...\n 'nu', 0.27; ...\n 'sfun', 'sflag1'; ...\n 'iplot', 1; ...\n 'igrid', 1; ...\n 'tol', 0.1; ...\n 'fid', 1 };\n[got,opt] = parseopt( cOptDef, varargin{:} );\nfid = opt.fid;\n\n\n% Geometry and grid.\nfea.sdim = { 'x' 'y' }; % Coordinate names.\nfea.grid = ringgrid( 12, 216, 100e-3, 120e-3 );\nfea.grid = delcells( fea.grid, selcells( fea.grid, '(x<=eps) | (y<=eps)') );\nif( opt.igrid~=1 )\n fea.grid = quad2tri( fea.grid );\nend\nn_bdr = max(fea.grid.b(3,:)); % Number of boundaries.\n\n\n% Problem definition.\nfea = addphys( fea, @planestress );\nfea.phys.pss.eqn.coef{1,end} = { opt.nu };\nfea.phys.pss.eqn.coef{2,end} = { opt.E };\nfea.phys.pss.sfun = { opt.sfun opt.sfun };\n\n\n% Boundary conditions.\nbctype = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\nbctype{1,4} = 1;\nbctype{2,3} = 1;\nfea.phys.pss.bdr.coef{1,5} = bctype;\n\nbccoef = mat2cell( zeros(2,n_bdr), [1 1], ones(1,n_bdr) );\nbccoef{1,1} = '-nx*1e4';\nbccoef{2,1} = '-ny*1e4';\nfea.phys.pss.bdr.coef{1,end} = bccoef;\n\n\n% Parse and solve problem.\nfea = parsephys( fea );\nfea = parseprob( fea ); % Check and parse problem struct.\nfea.sol.u = solvestat( fea, 'fid', fid, 'icub', 1+str2num(strrep(opt.sfun,'sflag','')) ); % Call to stationary solver.\n\n\n% Postprocessing.\ns_disp = fea.phys.pss.eqn.vars{2,end};\nif( opt.iplot>0 )\n figure\n postplot( fea, 'surfexpr', s_disp )\n title( 'Total displacement' )\nend\n\n\n% Error checking.\ns_sx = fea.phys.pss.eqn.vars{5,end};\ns_sy = fea.phys.pss.eqn.vars{6,end};\ns_sxy = fea.phys.pss.eqn.vars{7,end};\ns_sp1 = fea.phys.pss.eqn.vars{8,end};\ns_sp3 = fea.phys.pss.eqn.vars{10,end};\ns_ez = fea.phys.pss.eqn.vars{13,end};\ns_ep1 = fea.phys.pss.eqn.vars{15,end};\ns_ep2 = fea.phys.pss.eqn.vars{16,end};\ns_ep3 = fea.phys.pss.eqn.vars{17,end};\nv_disp = evalexpr( s_disp, [100e-3 120e-3-2*sqrt(eps);0 0]+sqrt(eps), fea )';\nv_dref = [2.809e-8 2.635e-8];\n[v_sx(1),v_sx(2)] = minmaxsubd( s_sx, fea );\nv_sxref = [-10000 55454];\n[v_sy(1),v_sy(2)] = minmaxsubd( s_sy, fea );\nv_syref = [-10000 55454];\n[v_sxy(1),v_sxy(2)] = minmaxsubd( s_sxy, fea );\nv_sxyref = [-32730 0];\n[v_sp1(1),v_sp1(2)] = minmaxsubd( s_sp1, fea );\nv_sp1ref = [4.5e4 55454];\n[v_sp3(1),v_sp3(2)] = minmaxsubd( s_sp3, fea );\nv_sp3ref = [-1e4 0];\n[v_ez(1),v_ez(2)] = minmaxsubd( s_ez, fea );\nv_ezref = [-5.929e-8 -5.929e-8];\n[v_ep1(1),v_ep1(2)] = minmaxsubd( s_ep1, fea );\nv_ep1ref = [2.196e-7 2.809e-7];\n[v_ep2(1),v_ep2(2)] = minmaxsubd( s_ep2, fea );\nv_ep2ref = [-5.929e-8 -5.929e-8];\n[v_ep3(1),v_ep3(2)] = minmaxsubd( s_ep3, fea );\nv_ep3ref = [-1.206e-7 -5.929e-8];\nout.err = [ abs([v_dref-v_disp])./v_dref ;\n abs([v_sxref-v_sx])./v_sxref ;\n abs([v_syref-v_sy])./v_syref ;\n abs([v_sxyref(1)-v_sxy(1)])./v_sxyref(1) 0 ;\n abs([v_sp1ref(2)-v_sp1(2)])./v_sp1ref(2) 0 ;\n abs([v_sp3ref(1)-v_sp3(1)])./v_sp3ref(1) 0 ;\n abs([v_ezref(1)-v_ez(1)])./v_ezref(1) 0 ;\n abs([v_ep1ref(1)-v_ep1(1)])./v_ep1ref(1) 0 ;\n abs([v_ep2ref(1)-v_ep2(1)])./v_ep2ref(1) 0 ;\n abs([v_ep3ref(1)-v_ep3(1)])./v_ep3ref(1) 0 ];\nout.pass = all( out.err(:) <= opt.tol );\n\n\nif( nargout==0 )\n clear fea out\nend\n", "meta": {"author": "precise-simulation", "repo": "featool-multiphysics", "sha": "861c771adda317a9f091263d16dca060116bd516", "save_path": "github-repos/MATLAB/precise-simulation-featool-multiphysics", "path": "github-repos/MATLAB/precise-simulation-featool-multiphysics/featool-multiphysics-861c771adda317a9f091263d16dca060116bd516/examples/ex_planestress6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6244341268126425}} {"text": "close all\nclear all\n\nN=5;\nnames={'A','B','C','D','E'};\ndag=zeros(N);\ndag(1,2)=1;\ndag(2,[3 4])=1;\ndag([3 4],5)=1;\n[xx yy] = draw_graph(dag,names,ones(N,1));\ntitle('Cheng example.');\n\nnode_sizes=2*ones(1,N);\nbnet=mk_bnet(dag,node_sizes);\n\nif 1\n disp('Generating DataSet');\n bnet.CPD{1} = tabular_CPD(bnet, 1, [0.4 0.6]);\n bnet.CPD{2} = tabular_CPD(bnet, 2, [0.2 0.3 0.8 0.7]);\n bnet.CPD{3} = tabular_CPD(bnet, 3, [0.1 0.2 0.9 0.8]);\n bnet.CPD{4} = tabular_CPD(bnet, 4, [0.6 0.8 0.4 0.2]);\n bnet.CPD{5} = tabular_CPD(bnet, 5, [0.9 0.8 0.7 0.6 0.1 0.2 0.3 0.4]);\n m=10000;\n cheng = cell(N,m);\n for i=1:m\n cheng(:,i)=sample_bnet(bnet);\n end\n cheng = cell2num(cheng);\n %save -ascii cheng cheng\nelse\n load -ascii cheng.mat\nend\n\n% profile clear\n% profile on\n [Phase_3, Phase_2, Phase_1, UPhase_3] = learn_struct_bnpc(cheng, node_sizes, 0.05, 0)\n% profile off\n% profile report report_cheng\n\nfigure\ndraw_graph(Phase_1,names,ones(N,1),xx,yy);\ntitle('PhaseI');\nfigure\ndraw_graph(Phase_2,names,ones(N,1),xx,yy);\ntitle('PhaseII');\n%figure\n%draw_graph(UPhase_3,names,ones(N,1),xx,yy);\n%title('undirected PhaseIII');\nfigure\ndraw_graph(Phase_3,names,ones(N,1),xx,yy);\ntitle('PhaseIII');\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/SLP/examples/test_bnpc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6243340620782408}} {"text": "% ir_example_ct_lir1\n% example of local impulse response (LIR) in CT\n% Copyright 2012-07-28, Jeff Fessler, University of Michigan\n\nif ~isvar('A'), printm 'setup geometry, image, sinogram'\n\tf.down = 4;\n\tig = image_geom('nx', 512, 'fov', 30, 'down', f.down);\n\tig.mask = ig.circ > 0;\n\tsg = sino_geom('par', 'nb', ig.nx, 'na', ig.nx, ...\n\t\t\t'dr', ig.dx, 'strip_width', 'd');\n\tsg.plot(ig);\n\n\tell = [0 0 10 10 0 0.2;\n 0 6 3 3 0 0.2;\n 6 0 3 3 0 0.1\n 0 -6 3 3 0 -0.1;\n -6 0 3 3 0 -0.2;\n\t\t];\n xtrue = ellipse_im(ig, ell, 'oversample', 2);\n\n%\tA = Gtomo2_dscmex(sg, ig);\n\tA = Gtomo2_wtmex(sg, ig, 'nthread', jf('ncore'));\n\tytrue = A * xtrue;\n\twi = exp(-ytrue); % ideal Poisson weighting\n\n\tim plc 2 3\n\tclim = [0 0.4];\n\tim(1, xtrue, 'x', clim), cbar\n\tim(2, ytrue, 'y: ideal sinogram'), cbar\n\tim(3, wi, 'w: ideal weighting'), cbar\n%\tir_savefig ir_example_ct_lir1_x_y_w\nprompt\nend\n\n\nif ~isvar('yp'), printm 'yp'\n\tix = round(ell(2:end, 1) / ig.dx + (ig.nx-1)/2);\n\tiy = round(ell(2:end, 2) / ig.dy + (ig.ny-1)/2);\n\txp = ig.zeros;\n\tfor ii=1:numel(ix)\n\t\txp = xp + ig.unitv(ix(ii), iy(ii));\n\tend\n\tf.amp = 0.1;\n\txp = f.amp * xp ;\n\tim(2, xtrue + xp)\n\n\typ = A * xp;\n\tclimp = [0 f.amp];\n\tim(3, xp, climp), cbar\n\tim(4, yp)\nend\n\nif ~isvar('fbp'), printm 'fbp'\n\ttmp = fbp2(sg, ig);\n\tfbp = fbp2(yp, tmp, 'window', 'boxcar,0.8');\n\tim(2, fbp, 'FBP', climp), cbar\nprompt\nend\n\nif ~isvar('fw.fbp'), printm 'fw.fbp'\n\tox = [-9:9]; oy = ox;\n\tfw.fun = @(x, ii) fwhm2(x(ix(ii)+ox, iy(ii)+oy));\n\tfor ii=1:numel(ix)\n\t\tfw.fbp(ii) = fw.fun(fbp, ii);\n\tend\n\tpr fw.fbp\nend\n\nif ~isvar('kappa'), printm 'kappa: try to make resolution approximately uniform'\n\tkappa = sqrt( div0(A' * wi, A' * ones(size(wi))) );\n\tim(4, kappa), cbar\nprompt\nend\n\n% use local psf to help select beta\nif ~isvar('R1'), printm 'R1, R2'\n\tf.l2b = 0;\n\tW = Gdiag(wi);\n\tR1 = Reg1(ig.mask * kappa(end/2+1,end/2+1), 'beta', 2^f.l2b); % usual\n%\tqpwls_psf(A, R1, 1, ig.mask, W, 'loop', 1); % choose beta\n\tR2 = Reg1(kappa, 'beta', 2^f.l2b); % kappa\n\tqpwls_psf(A, R2, 1, ig.mask, W, 'loop', 1); % choose beta\nprompt\nend\n\n%\tpsf = qpwls_psf(A, R1, 1, ig.mask, W);\n%\tinit = conv2(psf, xp, 'same');\n\tinit = fbp;\n\tim(init, climp)\n\nif ~isvar('xpwls1'), printm 'pwls1'\n\tf.niter = 300;\n\txpwls1 = pwls_pcg1(init(ig.mask), A, W, yp(:), R1, 'niter', f.niter);\n\txpwls1 = ig.embed(xpwls1);\n\tim(3, xpwls1, 'PWLS R1'), cbar\nend\n\nif ~isvar('xpwls2'), printm 'pwls2'\n\txpwls2 = pwls_pcg1(init(ig.mask), A, W, yp(:), R2, 'niter', f.niter);\n\txpwls2 = ig.embed(xpwls2);\n\tim(4, xpwls2, 'PWLS R2'), cbar\nend\n\nif 1\n\tfor ii=1:numel(ix)\n\t\tfw.pwls1(ii) = fw.fun(xpwls1, ii);\n\t\tfw.pwls2(ii) = fw.fun(xpwls2, ii);\n\tend\n\tpr fw.fbp\n\tpr fw.pwls1\n\tpr fw.pwls2\nend\n\nif 1\n\tclimp = [-0.004 0.05];\n%\tclimp = []\n\tim plc 1 3\n\tax = [18 110 20 120];\n\tim(1, fbp, 'FBP', climp), axis(ax)%, cbar h\n\tfun = @(fw, ii) text(ix(ii), iy(ii)+15, ...\n\t\tsprintf('%3.1f', fw(ii)), 'horiz', 'center', 'color', 'green');\n\tfor ii=1:numel(ix), fun(fw.fbp, ii); end\n\tim(2, xpwls1, 'PWLS standard R', climp), axis(ax)%, cbar h\n\tfor ii=1:numel(ix), fun(fw.pwls1, ii); end\n\tim(3, xpwls2, 'PWLS modified R', climp), axis(ax)%, cbar h\n\tfor ii=1:numel(ix), fun(fw.pwls2, ii); end\n\n%\tir_savefig eps_c ir_example_ct_lir1_fwhm\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/ir_example_ct_lir1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522813, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6243340502294249}} {"text": "function [ a, ipvt, rcond ] = r8mat_geco ( a, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_GECO factors a real matrix and estimates its condition number.\n%\n% Discussion:\n%\n% For the system A * X = B, relative perturbations in A and B\n% of size EPSILON may cause relative perturbations in X of size\n% EPSILON/RCOND.\n%\n% If RCOND is so small that the logical expression\n% 1.0 + RCOND == 1.0\n% is true, then A may be singular to working precision. In particular,\n% RCOND is zero if exact singularity is detected or the estimate\n% underflows.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 June 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Cleve Moler.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, real A(N,N), a matrix to be factored.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Output, real A(LDA,N), the LU factorization of the matrix.\n%\n% Output, integer IPVT(N), the pivot indices.\n%\n% Output, real RCOND, an estimate of the reciprocal\n% condition number of A.\n%\n\n%\n% Compute the L1 norm of A.\n%\n anorm = 0.0;\n for j = 1 : n\n anorm = max ( anorm, sum ( abs ( a(1:n,j) ) ) );\n end\n%\n% Compute the LU factorization.\n%\n [ a, ipvt, info ] = r8mat_gefa ( a, n );\n%\n% RCOND = 1 / ( norm(A) * (estimate of norm(inverse(A))) )\n%\n% estimate of norm(inverse(A)) = norm(Z) / norm(Y)\n%\n% where\n% A * Z = Y\n% and\n% A' * Y = E\n%\n% The components of E are chosen to cause maximum local growth in the\n% elements of W, where U'*W = E. The vectors are frequently rescaled\n% to avoid overflow.\n%\n% Solve U' * W = E.\n%\n ek = 1.0;\n z(1:n) = 0.0;\n\n for k = 1 : n\n\n if ( z(k) ~= 0.0 )\n ek = - abs ( ek ) * r8_sign ( z(k) );\n end\n\n if ( abs ( a(k,k) ) < abs ( ek - z(k) ) )\n s = abs ( a(k,k) ) / abs ( ek - z(k) );\n z(1:n) = s * z(1:n);\n ek = s * ek;\n end\n\n wk = ek - z(k);\n wkm = -ek - z(k);\n s = abs ( wk );\n sm = abs ( wkm );\n\n if ( a(k,k) ~= 0.0 )\n wk = wk / a(k,k);\n wkm = wkm / a(k,k);\n else\n wk = 1.0;\n wkm = 1.0;\n end\n\n if ( k+1 <= n )\n\n for j = k+1 : n\n sm = sm + abs ( z(j) + wkm * a(k,j) );\n z(j) = z(j) + wk * a(k,j);\n s = s + abs ( z(j) );\n end\n\n if ( s < sm )\n t = wkm - wk;\n wk = wkm;\n z(k+1:n) = z(k+1:n) + t * a(k,k+1:n);\n end\n\n end\n\n z(k) = wk;\n\n end\n\n z(1:n) = z(1:n) / sum ( abs ( z(1:n) ) );\n%\n% Solve L' * Y = W\n%\n for k = n : -1 : 1\n\n z(k) = z(k) + z(k+1:n) * a(k+1:n,k);\n\n if ( 1.0 < abs ( z(k) ) )\n z(1:n) = z(1:n) / abs ( z(k) );\n end\n\n l = ipvt(k);\n\n t = z(l);\n z(l) = z(k);\n z(k) = t;\n\n end\n\n z(1:n) = z(1:n) / sum ( abs ( z(1:n) ) );\n\n ynorm = 1.0;\n%\n% Solve L * V = Y.\n%\n for k = 1 : n\n\n l = ipvt(k);\n\n t = z(l);\n z(l) = z(k);\n z(k) = t;\n\n z(k+1:n) = z(k+1:n) + t * a(k+1:n,k)';\n\n if ( 1.0 < abs ( z(k) ) )\n ynorm = ynorm / abs ( z(k) );\n z(1:n) = z(1:n) / abs ( z(k) );\n end\n\n end\n\n s = sum ( abs ( z(1:n) ) );\n z(1:n) = z(1:n) / s;\n ynorm = ynorm / s;\n%\n% Solve U * Z = V.\n%\n for k = n : -1 : 1\n\n if ( abs ( a(k,k) ) < abs ( z(k) ) )\n s = abs ( a(k,k) ) / abs ( z(k) );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n end\n\n if ( a(k,k) ~= 0.0 )\n z(k) = z(k) / a(k,k);\n else\n z(k) = 1.0;\n end\n\n z(1:k-1) = z(1:k-1) - z(k) * a(1:k-1,k)';\n\n end\n%\n% Normalize Z in the L1 norm.\n%\n s = 1.0 / sum ( abs ( z(1:n) ) );\n z(1:n) = s * z(1:n);\n ynorm = s * ynorm;\n\n if ( anorm ~= 0.0 )\n rcond = ynorm / anorm;\n else\n rcond = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/r8mat_geco.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6243340491655468}} {"text": "function r = sqrt(a)\n%SQRT Taylor square root sqrt(a)\n%\n\n% written 05/21/09 S.M. Rump\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n e = 1e-30;\n if 1+e==1-e % fast check for rounding to nearest\n rndold = 0;\n else\n rndold = getround;\n setround(0)\n end\n\n K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;\n\n r = a;\n r.t(1,:) = sqrt(a.t(1,:));\n rt2 = 2*r.t(1,:); % almost 10 % faster\n for j=2:K1\n r.t(j,:) = ( a.t(j,:) - sum(r.t(2:j-1,:).*r.t(j-1:-1:2,:),1) ) ./ (rt2);\n end\n% straight version is faster\n% for j=2:K1\n% if even(j)\n% r.t(j,:) = ( a.t(j,:)/2 - sum(r.t(2:(j/2),:).*r.t(j-1:-1:(j/2)+1,:),1) ) ./ r.t(1,:);\n% else\n% r.t(j,:) = ( a.t(j,:)/2 - sum(r.t(2:((j-1)/2),:).*r.t(j-1:-1:(j+3)/2,:),1) - ...\n% (r.t((j+1)/2,:).^2)/2 ) ./ r.t(1,:);\n% end\n% end\n\n if rndold\n setround(rndold)\n end\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/taylor/@taylor/sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6243340439295438}} {"text": "function stroud_test03 ( )\n\n%*****************************************************************************80\n%\n%% TEST03 tests BALL_UNIT_07_3D, BALL_UNIT_14_3D, BALL_UNIT_15_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 06 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n global FUNC_3D_INDEX;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST03\\n' );\n fprintf ( 1, ' For integrals in the unit ball in 3D:\\n' );\n fprintf ( 1, ' BALL_UNIT_07_3D uses a formula of degree 7;\\n' );\n fprintf ( 1, ' BALL_UNIT_14_3D uses a formula of degree 14;\\n' );\n fprintf ( 1, ' BALL_UNIT_15_3D uses a formula of degree 15.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Unit ball volume = %f\\n', ball_unit_volume_nd ( 3 ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rule: #7 #14 #15\\n' );\n fprintf ( 1, ' F(X)\\n' );\n fprintf ( 1, '\\n' );\n\n num = function_3d_num ( );\n\n for i = 1 : num\n\n FUNC_3D_INDEX = i;\n\n result1 = ball_unit_07_3d ( 'function_3d' );\n result2 = ball_unit_14_3d ( 'function_3d' );\n result3 = ball_unit_15_3d ( 'function_3d' );\n\n fname = function_3d_name ( i );\n\n fprintf ( 1, ' %7s %12f %12f %12f\\n', ...\n fname, result1, result2, result3 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/stroud_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.624306887731585}} {"text": "% Jiao Xianjun (putaoshu@msn.com; putaoshu@gmail.com)\n% convert a sequence to a mat. each column shift previos to left by 1\n% for example input sequence 1 2 3 4 5 6 7, and len_body=4\n% output matrix:\n% 1 2 3 4\n% 2 3 4 5\n% 3 4 5 6\n% 4 5 6 7\n\n% A script of project: https://github.com/JiaoXianjun/multi-rtl-sdr-calibration\n\nfunction r = lin2col_shift_mat(s, len_body)\n\nif length(s) < len_body\n disp('Length of input is too short!');\n r = -1;\n return;\nend\n\nlen_tail = length(s) - len_body;\n\nr = toeplitz(s, [s(1) zeros(1, len_tail)]);\nr = r((len_tail+1):end, end:-1:1);\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/lin2col_shift_mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6243068616154237}} {"text": "function faces = sphDelaunay(dirs)\n%SPHDELAUNAY Computes the Delaunay triangulation on the unit sphere\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% SPHDELAUNAY.M - 10/10/2013\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Convert to cartesian\nN_vert = size(dirs, 1);\n[tempx, tempy, tempz] = sph2cart(dirs(:,1), dirs(:,2), ones(N_vert,1));\nU_vert = [tempx, tempy, tempz];\n\n% Find the convex hull of the points on the sphere - in this special case\n% the result equals the Delaunay triangulation of the points\nfaces = convhulln(U_vert);\n\n% Invert the triangles\nfaces = faces(:, 3:-1:1);\n\n% Shift the results to begin each triangle from the smallest entry\nfor n = 1:size(faces,1)\n tempface = faces(n,:);\n [~, minIdx] = min(tempface);\n faces(n, :) = circshift(tempface, [0 1-minIdx]);\nend\n\n% Sort through triangles with smaller entries first\nfaces = sortrows(faces, 1); % sort through first entry\nmaxentry = max(faces(:,1)); % sort through second entry\nn = 1;\nwhile n <= maxentry\n startIdx = find(faces(:,1) == n, 1, 'first');\n if ~isempty(startIdx)\n endIdx = find(faces(:,1) == n, 1, 'last');\n faces(startIdx:endIdx, :) = sortrows(faces(startIdx:endIdx, :), 2);\n n = n + 1;\n else\n n = n + 1;\n end\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Harmonic-Transform", "sha": "ef8a69aedbaf467e2fccb50c810564d747ce3409", "save_path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform", "path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform/Spherical-Harmonic-Transform-ef8a69aedbaf467e2fccb50c810564d747ce3409/sphDelaunay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6242602534538976}} {"text": "function [centers, radii] = SphericalHashing(data, bit)\n%Spherical Hashing method by Jae-Pil Heo\n\n [N, D] = size(data);\n centers = random_center(data, bit);\n [O1, O2, radii, avg, stddev] = compute_statistics(data, centers);\n \n iter = 1;\n while true \n forces = zeros(bit, D);\n for i = 1:bit - 1\n for j = i + 1:bit\n force = 0.5 * (O2(i, j) - N / 4) / (N / 4) * (centers(i, :) - centers(j, :));\n forces(i, :) = forces(i, :) + force ./ bit;\n forces(j, :) = forces(j, :) - force ./ bit;\n end\n end\n centers = centers + forces;\n \n [O1, O2, radii, avg, stddev] = compute_statistics(data, centers);\n\t\t\n if avg <= 0.1 * N / 4 && stddev <= 0.15 * N / 4\n break;\n end\n if iter >= 100\n fprintf('iter exceed 100, avg = %f, stddev = %f\\n', avg, stddev);\n end\n \n iter = iter + 1;\n end\n %fprintf('iteration = %d\\n', iter);\nend\n\nfunction centers = random_center(data, bit)\n [N, D] = size(data);\n centers = zeros(bit, D);\n for i = 1:bit\n R = randperm(N);\n sample = data(R(1:5), :);\n sample = sum(sample, 1) / 5;\n centers(i, :) = sample(:);\n end\nend\n\nfunction [O1, O2, radii, avg, stddev] = compute_statistics(data, centers) \n [N, D] = size(data);\n bit = size(centers, 1);\n \n dist = EuDist2(centers,data);\n sort_dist = sort(dist, 2);\n radii = sort_dist(:, floor(N / 2));\n dist = dist <= repmat(radii, 1, N);\n dist = dist * 1.0;\n\n O1 = sum(dist, 2);\n avg = 0;\n avg2 = 0;\n O2 = dist * dist';\n for i = 1:bit-1\n for j = i + 1:bit\n avg = avg + abs(O2(i, j) - N / 4);\n avg2 = avg2 + O2(i, j);\n end\n end\n \n avg = avg / (bit * (bit - 1) / 2);\n avg2 = avg2 / (bit * (bit - 1) / 2);\n stddev = 0;\n for i = 1:bit - 1\n for j = i + 1:bit\n stddev = stddev + (O2(i, j) - avg2) ^ 2;\n end\n end\n stddev = sqrt(stddev / (bit * (bit - 1) / 2));\nend\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/ANNS/Hashing/Unsupervised/SpH/SphericalHashing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6242602430146699}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mcs.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function [xbest,fbest,xmin,fmi,ncall,ncloc,flag]=mcs(fcn,data,u,v,prt,\n% smax,nf,stop,iinit,local,gamma,hess)\n% MCS global optimization for function defined by fcn in the \n% n-dimensional box [u,v]\n%\n% Input:\n% fcn = 'fun' \tname of function fun(data,x), x an n-vector\n% data\t\tdata vector (or other data structure)\n% [u,v] \tbox in which the optimization is carried out (u, v \n% \tn-vectors)\n% prt\t\tprint level\n% \t\tprt = 0: no printing\n% \t\tprt = 1: # sweep, minimal nonempty level, # f-calls, \n% \t\tbest point and function value (default)\n% \t\tprt > 1: only meaningful for test functions with known\n% \t\tglobal minimizers\n% \t\tin addition levels and function values of boxes \n% \t\tcontaining the global minimizers of a test function\n% smax \tnumber of levels (default: 5*n+10)\n% nf \tmaximum number of function evaluations (default: 50*n^2)\n% stop \tstop(1) in ]0,1[: relative error with which the known \n%\t\t global minimum of a test function should be found\n%\t\t stop(2) = fglob known global minimum of a test function\n%\t\t stop(3) = safeguard parameter for absolutely small \n%\t\t fglob\n%\t\tstop(1) >= 1: the program stops if the best function\n%\t\t value has not been improved for stop(1) sweeps\n%\t\tstop(1) = 0: the user can specify a function value that\n%\t\t should be reached\n% stop(2) = function value that is to be achieved\n% \t(default: stop = 3*n)\n% iinit \tparameter defining the initialization list\n% \t= 0 corners and midpoint (default for finite u,v)\n% \t= 1 safeguarded version *default otherwise)\n% \t\t= 2 5u/6 + v/6, u/6 + 5v/6 and midpoint\n%\t\t= 3 initialization list with line searches\n% \totherwise self-defined init. list (to be stored in \n%\t\t\t init0.m)\n%\t\tfor a self-defined initialization list, the user should\n% \t\tprovide an m-script file init0.m containing a matrix x0 \n%\t\twith n rows and at least 3 columns and two n-vectors l \n%\t\tand L \n%\t\tthe ith column of x0 contains the initialization list\n%\t\tvalues for the ith coordinate, their number is L(i), and\n%\t\tx0(i,l(i)) is the ith coordinate of the initial point\n% local\t\tlocal = 0: no local search\n%\t\totherwise: maximal number of steps in local search\n%\t\t(default: 50) \n% gamma\t\tstopping criterion for local search (default: eps)\n% \tthe local search is stopped if abs(g)'*max(abs(x),\n%\t\tabs(xold)) < gamma*(f0-f) \n% hess\t\tsparsity pattern of the Hessian for local search \n%\t\t(default: hessian = ones(n,n))\n%\n% Output:\n% xbest(1:n) \tcurrent best point \n% fbest \tfunction value at xbest\n% xmin \tmatrix with n rows; the columns are the points in the\n% \t'shopping basket' (i.e. good points resp. local \n%\t\tminimizers)\n% fmi \tfunction values corresponding to the 'shopping basket';\n%\t\tfmi(i) is the function value at xmin(:,i)\n% ncall \tnumber of function evaluations\n% ncloc\t\tnumber of function evaluations used for local search\n% flag \tspecifies which stopping criterion has been used\n% \t= 0 a (known) global minimum fglob of a test function \n% has been found with the required relative error \n%\t\t relerr\n% \t= 1 the division procedure has been completed\n% \t= 2 the maximum number nf of function calls has been\n% reached without finding a known minimum with the\n% required relative error or completing the division\n% procedure\n%\t\t= 3 stop(1) sweeps without progress (for stop(1) >= 1)\n%\n% Uses the following m-files (directly or indirectly):\n% addloc.m \n% basket.m\n% basket1.m\n% bounds.m\n% chkloc.m\n% chrelerr.m\n% chvtr.m\n% csearch.m \tcalled by lsearch.m\n% exgain.m\n% fbestloc.m\n% genbox.m\n% hessian.m\tcalled by triple.m\n% init.m\n% initbox.m\n% initlist.m\n% gls.m and its subprograms called by lsearch.m \n% lsearch.m\n% minq.m and its subprograms called by lsearch.m\n% neighbor.m\n% polint.m\tcalled by exgain.m and initbox.m\n% polint1.m\tcalled by triple.m\n% quadmin.m\n% quadpol.m\n% range.m\tcalled by lsearch.m\n% splinit.m\n% split.m\n% split1.m\n% split2.m \tcalled by splrnk.m\n% splrnk.m\n% strtsw.m\n% subint.m\n% triple.m\tcalled by lsearch.m\n% updtf.m \tcalled by vertex.m\n% updtoptl.m\n% updtrec.m \tcalled by splinit.m and split.m\n% vert1.m \tcalled by vertex.m\n% vert2.m \tcalled by vertex.m\n% vert3.m \tcalled by vertex.m\n% vertex.m\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [xbest,fbest,xmin,fmi,ncall,ncloc,flag]=mcs(fcn,data,u,v,prt,smax,nf,stop,iinit,local,gamma,hess)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% global variables\nglobal foptbox nbasket nboxes ncall nglob nsweep nsweepbest optlevel record xglob xloc\n% foptbox(1:nglob) function value(s) of the box(es) containing the (a)\n% \tglobal minimizer of a test function\n% nbasket \tcounter for boxes in the 'shopping basket'\n% nboxes \tcounter for boxes not in the 'shopping basket'\n% nglob \tnumber of global minimizers of a test function\n% nloc\t\t(for local ~= 0) counter of points that have been used\n% \t\tas starting points for a local search\n% nsweep \tsweep counter\n% nsweepbest number of sweep in which fbest was updated for the last\n%\t\ttime\n% optlevel \tlevel(s) of the box(es) containing the (a) global\n% \tminimum of a test function\n% record(1:smax-1) record(i) points to the best non-split box at level i\n% \t(record list)\n% xglob(1:n,1:nglob) xglob(:,i), i=1:nglob, are the global minimizers\n% of a test function in [u,v]\n% xloc(1:n,:)\t(for local ~= 0) columns are the points that have been \n%\t\tused as starting points for local search\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nn = length(u);\n\n% check box bounds\nif ~isempty(find(v= 0\n x0(i,1) = u(i); [x0(i,2),x0(i,3)] = subint(u(i),v(i));x0(i,2) = 0.5*(x0(i,1)+x0(i,3));\n elseif v(i) <= 0\n x0(i,3) = v(i); [x0(i,2),x0(i,1)] = subint(v(i),u(i));x0(i,2) = 0.5*(x0(i,1)+x0(i,3));\n else\n x0(i,2) = 0; [xi,x0(i,1)] = subint(0,u(i)); [xi,x0(i,3)] = subint(0,v(i));\n end\n end\n l = 2*ones(n,1);\n L = 3*ones(n,1);\nelseif iinit == 2\n x0(:,1) = (5*u + v)/6;\n x0(:,2) = 0.5*(u + v);\n x0(:,3) = (u + 5*v)/6;\n l = 2*ones(n,1);\n L = 3*ones(n,1);\nelseif iinit == 3\n [x0,f0,l,L,istar,ncall1] = initlist(fcn,data,u,v);\n ncall = ncall + ncall1;\nelse\n init0 \t%self-defined initialization list\n for i=1:size(x0,2)\n if ~isempty(find(x0(:,i)v))\n error('incorrect initialization list')\n end\n end\nend \n\n% check whether there are infinities in the initialization list\nif ~isempty(find(isinf(x0))), error('infinities in ititialization list'), end\n\n% computation of the function values f0 appertaining to the init. list \n% and the pointer istar to the best point in the initialization list\nif iinit ~= 3\n [f0,istar,ncall1] = init(fcn,data,x0,l,L,n);\n ncall = ncall + ncall1; \nend\n\n% definition of the base vertex of the original box\nfor i = 1:n\n x(i) = x0(i,l(i));\nend\n\n% definition of the opposite vertex v1 of the original box\nfor i = 1:n\n if abs(x(i)-u(i)) > abs(x(i)-v(i))\n v1(i) = u(i);\n else\n v1(i) = v(i);\n end\nend\n\n% initialization of the record list, the counters nboxes, nbasket, m \n% and nloc, xloc and the output flag\nrecord = zeros(smax-1,1);\nnboxes = 1;\nnbasket = 0;\nnbasket0 = 0;\nnsweep = 0;\nm = n;\nrecord(1) = 1;\nnloc = 0;\nxloc = [];\nflag = 1; \n\n[ipar,level,ichild,f,isplit,p,xbest,fbest] = initbox(x0,f0,l,L,istar,u,v,prt);\n% generates the boxes in the initialization procedure\nf0min = fbest;\nif stop(1) > 0 & stop(1) < 1\n flag = chrelerr(fbest,stop);\nelseif stop(1) == 0\n flag = chvtr(fbest,stop(2));\nend\nif ~flag,return,end\n% if the (known) minimum function value fglob has been found with the\n% required tolerance, flag is set to 0 and the program is terminated\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ns = strtsw(smax,level,f(1,:)); \n% the vector record is updated, and the minimal level s containing \n% non-split boxes is computed\nnsweep = nsweep + 1;\t% sweep counter\n \nwhile s < smax & ncall + 1 <= nf\n par = record(s); % the best box at level s is the current box\n [n0,x,y,x1,x2,f1,f2] = vertex(par,n,u,v,v1,x0,f0,ipar,isplit,ichild,z,f,l,L); \n % compute the base vertex x, the opposite vertex y, the 'neighboring' \n % vertices and their function values needed for quadratic \n % interpolation and the vector n0 indicating that the ith coordinate\n % has been split n0(i) times in the history of the box\n if s > 2*n*(min(n0)+1) \n % s 'large' \n [isplit(par),z(2,par)] = splrnk(n,n0,p,x,y); \n % splitting index and splitting value z(2,par) for splitting by \n % rank are computed\n % z(2,par) is set to Inf if we split according to the init. list\n splt = 1; % indicates that the box is to be split\n else\n if nogain(par) % box has already been marked as not eligible for splitting\n % by expected gain\n splt = 0;\n else\n [e,isplit(par),z(2,par)] = exgain(n,n0,l,L,x,y,x1,x2,f(1,par),f0,f1,f2);\n % splitting by expected gain\n % compute the expected gain vector e and the potential splitting \n % index and splitting value\n fexp = f(1,par) + min(e);\n if fexp < fbest \n splt = 1;\n else\n splt = 0; % the box is not split since we expect no improvement\n nogain(par) = 1; % the box is marked as not eligible for splitting by expected gain\n end\n end\n end\n if splt == 1 % prepare for splitting\n i = isplit(par);\n level(par) = 0;\n if z(2,par) == Inf % prepare for splitting by initialization list\n m = m + 1;\n z(2,par) = m; \n [xbest,fbest,f0(:,m),xmin,fmi,ipar,level,ichild,f,flag,ncall1] = splinit(fcn,data,i,s,smax,par,x0,n0,u,v,x,y,x1,x2,L,l,xmin,fmi,ipar,level,ichild,f,xbest,fbest,stop,prt);\n ncall = ncall + ncall1;\n else % prepare for default splitting\n z(1,par) = x(i);\n [xbest,fbest,xmin,fmi,ipar,level,ichild,f,flag,ncall1] = split(fcn,data,i,s,smax,par,n0,u,v,x,y,x1,x2,z(:,par),xmin,fmi,ipar,level,ichild,f,xbest,fbest,stop,prt);\n ncall = ncall + ncall1;\n end\n if nboxes > dim \n% if the pre-assigned size of the `large' arrays has already been exceeded, these arrays are made larger\n isplit(nboxes+1:nboxes+step) = zeros(1,step);\n level(nboxes+1:nboxes+step) = zeros(1,step);\n ipar(nboxes+1:nboxes+step) = zeros(1,step);\n ichild(nboxes+1:nboxes+step) = zeros(1,step);\n z(:,nboxes+1:nboxes+step) = zeros(2,step);\n nogain(nboxes+1:nboxes+step) = zeros(1,step);\n f(:,nboxes+1:nboxes+step) = zeros(2,step);\n dim = nboxes + step;\n end\n if ~flag,break,end\n else % splt=0: no splitting, increase the level by 1\n if s + 1 < smax \n level(par) = s + 1;\n updtrec(par,s+1,f(1,:));\n else\n level(par) = 0;\n nbasket = nbasket + 1;\n xmin(:,nbasket) = x;\n fmi(nbasket) = f(1,par);\n end\n if prt > 1\n [w1,w2] = bounds(n,n0,x,y,u,v);\n % compute lower and upper bounds of the box in order to be able\n % to check whether it contains a global minimizer\n iopt = [];\n % the vector iopt contains the indices of the global minimizers\n % contained in the box\n for iglob = 1:nglob\n if w1 <= xglob(:,iglob) & xglob(:,iglob) <= w2\n iopt = [iopt, iglob];\n end\n for iglob = 1:length(iopt)\n optlevel(iopt(iglob)) = s + 1;\n end\n end \n end\n end % of prepare for splitting\n s = s + 1; \n while s < smax \n if record(s) == 0\n s = s + 1;\n else\n break \n end\n end\n if s == smax % if smax is reached, a new sweep is started \n if local,\n [fmi(nbasket0+1:nbasket),j] = sort(fmi(nbasket0+1:nbasket));\n xmin(:,nbasket0+1:nbasket) = xmin(:,nbasket0+j);\n xmin0 = [];\n fmi0 = [];\n for j = nbasket0+1:nbasket\n x = xmin(:,j);\n f1 = fmi(j);\n chkloc;\n if loc,\n addloc; \n [xbest,fbest,xmin,fmi,x,f1,loc,flag,ncall1] = basket(fcn,data,x,f1,xmin,fmi,xbest,fbest,stop,nbasket0);\n ncall = ncall + ncall1;\n if ~flag,break,end\n if loc,\n [xmin1,fmi1,nc,flag] = lsearch(fcn,data,x,f1,f0min,u,v,nf-ncall,stop,local,gamma,hess);\n ncall = ncall + nc;\n ncloc = ncloc + nc;\n if fmi1 < fbest\n xbest = xmin1;\n fbest = fmi1;\n nsweepbest = nsweep;\n if ~flag\n nbasket0 = nbasket0 + 1;\n nbasket = nbasket0;\n xmin(:,nbasket) = xmin1;\n fmi(nbasket) = fmi1;\n break\n end\n if stop(1) > 0 & stop(1) < 1\n flag = chrelerr(fbest,stop);\n elseif stop(1) == 0\n flag = chvtr(fbest,stop(2));\n end\n if ~flag,return,end\n end\n [xbest,fbest,xmin,fmi,loc,flag,ncall1] = basket1(fcn,data,xmin1,fmi1,xmin,fmi,xbest,fbest,stop,nbasket0);\n ncall = ncall + ncall1;\n if ~flag,break,end\n if loc,\n nbasket0 = nbasket0 + 1;\n xmin(:,nbasket0) = xmin1;\n fmi(nbasket0) = fmi1;\n fbestloc;\n if ~flag,\n nbasket = nbasket0; break\n end\n end\n end\n end\n end\n nbasket = nbasket0; \n if ~flag,break,end\n end\n s = strtsw(smax,level,f(1,:));\n if prt,\n if nsweep == 1\n fprintf('nsw minl ');\n if prt > 1\n fprintf('optl fopt ')\n end\n fprintf('nf fbest xbest\\n')\n end\n minlevel=s;\n fprintf('%3i %3i',nsweep,minlevel);\n if prt > 1\n fprintf(' %3i',optlevel);fprintf(' %10.3e',foptbox);\n end\n fprintf(' %5i %10.3e',ncall,fbest);\n fprintf(' %10.4f',xbest);\n fprintf(1,'\\n');\n end\n if stop(1) > 1\n if nsweep - nsweepbest >= stop(1),flag = 3; return,end\n end\n nsweep = nsweep + 1;\n end\nend\nif ncall >= nf\n flag = 2;\nend\nif local,\n if length(fmi) > nbasket\n xmin(:,nbasket+1:length(fmi)) = [];\n fmi(nbasket+1:length(fmi)) = [];\n end\nend\n\n\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/mcs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6242602411612787}} {"text": "function att = attenuationWater(f, T)\n%ATTENUATIONWATER Calculate ultrasound attenuation in distilled water.\n%\n% DESCRIPTION:\n% attenuationWater calculates the ultrasonic absorption in distilled\n% water at a given temperature and frequency using a 7th order\n% polynomial fitted to the data given by Pinkerton (1949). \n%\n% USAGE:\n% att = attenuationWater(f, T)\n%\n% INPUTS:\n% f - array of frequency values [MHz]\n% T - water temperature [degC]\n%\n% OUTPUTS:\n% att - attenuation [dB/cm]\n%\n% ABOUT:\n% author - Bradley E. Treeby\n% date - 10th November 2008\n% last udpate - 10th November 2008 \n%\n% REFERENCES:\n% [1] Pinkerton (1949) \"The Absorption of Ultrasonic Waves in Liquids and\n% its Relation to Molecular Constitution,\" Proceedings of the\n% Physical Society. Section B, 2, 129-141\n%\n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also speedSoundWater\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\nif T < 0 || T > 60\n disp('WARNING: Temperature outside range of experimental data');\nend\n\n% conversion factor between Nepers and dB\nNEPER2DB = 8.686; \n\n% coefficients for 7th order polynomial fit\na_0 = 56.723531840522710;\na_1 = -2.899633796917384;\na_2 = 0.099253401567561;\na_3 = -0.002067402501557;\na_4 = 2.189417428917596e-005;\na_5 = -6.210860973978427e-008;\na_6 = -6.402634551821596e-010;\na_7 = 3.869387679459408e-012;\n\n% compute attenuation\na_on_fsqr = (a_0 + a_1*T + a_2*T.^2 + a_3*T.^3 + a_4*T.^4 + a_5*T.^5 + a_6*T.^6 + a_7*T.^7)*1e-17;\natt = NEPER2DB*1e12*f.^2*a_on_fsqr;\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/attenuationWater.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6242602375789368}} {"text": "%% Dense vs Sparse SNLE\nclc\nfun = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\n \nx0 = [-30 -10 -30 -10]'; \n\nOpt = opti('fun',fun,'x0',x0,'options',optiset('solver','auto'))\n\n[x,f,e,i] = solve(Opt)\n\n\n%% Sparse above\nfun = @(x) -1;\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\ncl = zeros(4,1);\ncu = zeros(4,1);\n \nx0 = [-30 -10 -30 -10]'; \n\nOpt = opti('fun',fun,'nl',nleq,cl,cu,'x0',x0,'options',optiset('solver','auto'))\n\n[x,f,e,i] = solve(Opt)\n\n%% As above but new construct [no grad]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\n \nx0 = [-30 -10 -30 -10]'; \n\nOpt = opti('nleq',nleq,'x0',x0,'options',optiset('solver','auto'))\n\n[x,f,e,i] = solve(Opt)\n\n%% As above but new construct [w grad DENSE]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); \n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nleq',nleq,'nljac',nljac,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% As above but new construct [w grad SPARSE]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); nljac = @(x) sparse(nljac(x)); \n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nleq',nleq,'nljac',nljac,'nljacstr',nljacstr,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% As above but new construct [w grad SPARSE alt nl format]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); nljac = @(x) sparse(nljac(x)); \n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nleq',nleq,'nljac',nljac,'nljacstr',nljacstr,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% As above but new construct [w grad SPARSE alt nl format w lin]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); nljac = @(x) sparse(nljac(x)); \n A = [0 1 0 1]; b = 2;\n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nleq',nleq,'ineq',A,b,'nljac',nljac,'nljacstr',nljacstr,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% As above but new construct [w grad SPARSE alt nl format w lin + int]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); nljac = @(x) sparse(nljac(x)); \n A = [0 1 0 1]; b = 2;\n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nleq',nleq,'ivars',2,'lin',A,-Inf,b,'nljac',nljac,'nljacstr',nljacstr,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% As above but new construct [w grad SPARSE alt nl format w ineq]\nclc\nnleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4)-x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))\n x(3)];\nif (exist('syms.m','file')) \n [nljac,nljacstr] = symJac(nleq); nljac = @(x) sparse(nljac(x)); \n nlrhs = zeros(5,1);\n nle = [zeros(4,1);-1];\n A = [0 1 0 1]; b = 2;\n\n x0 = [-30 -10 -30 -10]'; \n\n Opt = opti('nlmix',nleq,nlrhs,nle,'ineq',A,b,'nljac',nljac,'nljacstr',nljacstr,'x0',x0,'options',optiset('solver','auto'))\n\n [x,f,e,i] = solve(Opt)\nend\n\n%% Wiki Ex 1\nclc\n% System of Nonlinear Equations\n nleq = @(x) [ 2*x(1) - x(2) - exp(-x(1));\n -x(1) + 2*x(2) - exp(-x(2))];\n\n% Starting Guess\n x0 = [-5;5];\n\n% Create OPTI Object\n Opt = opti('nleq',nleq,'x0',x0)\n\n% Solve the SNLE problem\n[x,fval,exitflag,info] = solve(Opt)\n\n%% Online Example\nclc\n% System of Nonlinear Equations\n nleq = @(x) [10*(x(2) - x(1)^2)\n sqrt(90)*(x(4) - x(3)^2)\n sqrt(10)*(x(2) + x(4) - 2)\n (1/sqrt(10))*(x(2) - x(4))];\n\n% Nonlinear Equations Jacobian\n nlJac = @(x) sparse([-20*x(1),10,0,0\n 0,0,-6*10^(1/2)*x(3),3*10^(1/2)\n 0,10^(1/2),0,10^(1/2)\n 0,10^(1/2)/10,0,-10^(1/2)/10]);\n\n% Jacobian Sparsity Pattern\n nlJacstr = @() sparse([1 1 0 0\n 0 0 1 1\n 0 1 0 1\n 0 1 0 1]);\n\n% Starting Guess\n x0 = [-30;-10;-30;-10];\n\n% Sparse SNLE OPTI Problem\n Opt = opti('nleq',nleq,'nlJac',nlJac,'nlJacstr',nlJacstr,'x0',x0)\n\n %Solve\n[x,f,e,i] = solve(Opt)\n\n%% SCNLE Example\nclc\n\n% Objective (Nonlinear Equations) Function\n fun = @(x) [ 2*x(1) - x(2) - exp(-x(1));\n -x(1) + 2*x(2) - exp(-x(2))];\n\n% Bounds\n lb = [0.6;0];\n ub = [1;1];\n\n% Starting Guess\n x0 = [-5;5];\n\n% Create OPTI Object\n Opt = opti('nleq',fun,'bounds',lb,ub,'x0',x0,'options',optiset('display','iter'))\n\n% Solve the SCNLE problem\n[x,fval,exitflag,info] = solve(Opt)\n\n\n%% Problem SCNLE\nclc\n\nA = randn(91);\nB12 = randn(91,145);\nB1 = randn(145,91); B2 = randn(145,91);\nConstant = randn(91,1);\nA_ieq = randn(12,91); b_ieq = randn(12,1);\nlb = zeros(91,1); ub = 100*ones(91,1);\nz0 = lb;\n\nnleq = @(x) A*x + B12*((B1*x).*(B2*x)) + Constant; \n\nOpt=opti('nleq',nleq,'ineq',A_ieq,b_ieq,'bounds',lb,ub,'x0',z0,'options',optiset('display','iter'))\n\nsolve(Opt)\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/math/opti/Test Problems/Development/test_sparse_snle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6242328157931608}} {"text": "function y = pow_pos( x, p )\n\n%POW_POS Power of positive part.\n% POW_POS(X,P) = POS(X).^P = MAX(X,0).^P.\n% Both P and X must be real, and P must be greater than or equal to 1.\n%\n% Disciplined convex programming information:\n% POW_POS(X,P) is convex and nondecreasing in X; so when used in CVX\n% expressions, X must be convex. P must be constant, real, and\n% greater than or equal to 1.\n\nnarginchk(2,2);\nif ~isnumeric( x ) || ~isreal( x ) || ~isnumeric( p ) || ~isreal( p ),\n error( 'Arguments must be real.' );\nelseif any( p(:) <= 1 ),\n error( 'Second argument must be greater than or equal to 1.\\nFor other exponents, use POW_P instead.', 1 ); %#ok\nend\ny = max(x,0).^p;\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/pow_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332532, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6242327925207208}} {"text": "function clenshaw_curtis_set_test ( )\n\n%*****************************************************************************80\n%\n%% CLENSHAW_CURTIS_SET_TEST tests CLENSHAW_CURTIS_SET.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 03 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLENSHAW_CURTIS_SET_TEST\\n' );\n fprintf ( 1, ' CLENSHAW_CURTIS_SET sets up a Clenshaw-Curtis rule;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Estimate the integral of sqrt(abs(x)) over [-1,+1].\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Estimate Error\\n' );\n fprintf ( 1, '\\n' );\n\n exact = 4.0 / 3.0;\n\n for n = 1 : 10\n\n [ x, w ] = clenshaw_curtis_set ( n );\n\n v(1:n,1) = sqrt ( abs ( x(1:n,1) ) );\n\n q = w' * v;\n e = abs ( q - exact );\n\n fprintf ( 1, ' %2d %24.16g %14.6e\\n', n, q, e );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/clenshaw_curtis_set_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6242048346766351}} {"text": "classdef KalmanFilterX < FilterX \n% KalmanFilterX class\n%\n% Summary of KalmanFilterX:\n% This is a class implementation of a standard Kalman Filter.\n%\n% KalmanFilterX Properties: (**)\n% + StatePrior - A structure used to store the state prior\n% + StatePrediction - A structure used to store the state prediction\n% + MeasurementPrediction - A structure used to store the measurement prediction\n% + StatePosterior - A structure used to store posterior information \n% + MeasurementList - A (yDim x 1) matrix used to store the received measurement\n% + ControlInput - A (uDim x 1) matrix used to store the last received control input\n% + KalmanGain - A (xDim x yDim) matrix representing the last computed Kalman Gain\n% + Model - An object handle to StateSpaceModelX object\n% + Transition (*) = Object handle to TransitionModelX SubClass \n% + Measurement (*) = Object handle to MeasurementModelX SubClass \n% + Control (*) = Object handle to ControlModelX SubClass \n%\n% (*) Signifies properties necessary to instantiate a class object\n% (**) xDim, yDim and uDim denote the dimentionality of the state, measurement\n% and control vectors respectively.\n%\n% KalmanFilterX Methods:\n% + KalmanFilterX - Constructor method\n% + predict - Performs KF prediction step\n% + update - Performs KF update step\n%\n% (+) denotes puplic properties/methods\n% \n% See also TransitionModelX, MeasurementModelX and ControlModelX template classes\n \n properties\n StatePrior\n StatePrediction\n MeasurementPrediction\n StatePosterior\n KalmanGain\n ControlInput\n end\n \n properties (Dependent)\n MeasurementLikelihoods\n end\n \n properties (Access=protected)\n MeasurementLikelihoods_ = [];\n end\n \n methods (Access = protected)\n function initialise_(this, config)\n initialise_@FilterX(this,config);\n if (isfield(config,'StatePrior'))\n this.StatePrior = config.StatePrior;\n this.StatePosterior = this.StatePrior;\n end\n end\n % MeasurementList\n function measurementList = setMeasurementList(this, newMeasurementList)\n measurementList = newMeasurementList;\n this.MeasurementLikelihoods_ = [];\n end\n function StatePrior = setStatePrior(this,newStatePrior)\n if(isa(newStatePrior,'GaussianStateX'))\n StatePrior = newStatePrior;\n else\n StatePrior = GaussianStateX(newStatePrior);\n end\n end\n function StatePrediction = setStatePrediction(this,newStatePrediction)\n if(isa(newStatePrediction,'GaussianStateX'))\n StatePrediction = newStatePrediction;\n else\n StatePrediction = GaussianStateX(newStatePrediction.Mean, newStatePrediction.Covar);\n end\n end\n function MeasurementPrediction = setMeasurementPrediction(this,newMeasurementPrediction)\n if(isa(newMeasurementPrediction,'GaussianStateX'))\n MeasurementPrediction = newMeasurementPrediction;\n else\n MeasurementPrediction = GaussianStateX(newMeasurementPrediction.Mean, newMeasurementPrediction.Covar);\n end\n end\n function MeasurementLikelihoods = getMeasurementLikelihoods(this)\n if(isempty(this.MeasurementLikelihoods_))\n this.MeasurementLikelihoods_ = mvnpdf(this.MeasurementList.Vectors',this.MeasurementPrediction.Mean',this.MeasurementPrediction.Covar)';\n end\n MeasurementLikelihoods = this.MeasurementLikelihoods_;\n end\n function StatePosterior = setStatePosterior(this,newStatePosterior)\n if(isa(newStatePosterior,'GaussianStateX'))\n StatePosterior = newStatePosterior;\n else\n StatePosterior = GaussianStateX(newStatePosterior.Mean, newStatePosterior.Covar);\n end\n end\n end\n \n methods\n function this = KalmanFilterX(varargin)\n % KalmanFilterX Constructor method\n %\n % Parameters\n % ----------\n % Model: StateSpaceModelX\n % An object handle to StateSpaceModelX object.\n % StatePrior: struct, optional\n % A StateX subclass object describing the state prior. If StatePrior \n % is not a GaussianStateX instance, then it will be converted in\n % one using the extracted mean and covariance.\n %\n % Usage\n % -----\n % * kf = KalmanFilterX(___,Name,Value) instantiates an object handle, \n % configured with the options specified by one or more Name,Value \n % pair arguments. \n %\n % See also predict, update, smooth. \n \n % Call SuperClass method\n %this@FilterX(varargin{:});\n \n if(nargin==0)\n return;\n end\n \n % First check to see if a structure was received\n if(nargin==1)\n if(isstruct(varargin{1}))\n config = varargin{1};\n this.initialise_(config);\n end\n return;\n end\n \n % Otherwise, fall back to input parser\n parser = inputParser;\n parser.KeepUnmatched = true;\n parser.parse(varargin{:});\n config = parser.Unmatched;\n this.initialise_(config);\n end\n \n function initialise(this,varargin)\n % initialise Initialise the KalmanFilter with a certain set of\n % parameters. \n % \n % Parameters\n % ----------\n % Model: StateSpaceModelX\n % An object handle to StateSpaceModelX object.\n % StatePrior: StateX, optional\n % A StateX subclass object describing the state prior. If StatePrior \n % is not a GaussianStateX instance, then it will be converted in\n % one using the extracted mean and covariance.\n % \n % Usage\n % -----\n % * initialise(kf,___,Name,Value) initialises the KalmanFilterX \n % object kf with the options specified by one or more Name,Value \n % pair arguments. \n %\n % See also predict, update, smooth. \n \n if(nargin==0)\n error(\"Not enough input arguments.\");\n end\n \n initialise@FilterX(this);\n \n % First check to see if a structure was received\n if(nargin==2)\n if(isstruct(varargin{1}))\n config = varargin{1};\n this.initialise_(config);\n end\n return;\n end\n \n % Otherwise, fall back to input parser\n parser = inputParser;\n parser.KeepUnmatched = true;\n parser.parse(varargin{:});\n config = parser.Unmatched;\n this.initialise_(config);\n end\n \n function [statePrediction, measurementPrediction] = predict(this, varargin)\n % Predict Perform Kalman Filter prediction step\n % \n % Parameters\n % ----------\n % prior: GaussianStateX, optional\n % The prior state estimate.\n % timestamp: datetime, optional\n % A timestamp indicating the time at which prediction is\n % performed.\n %\n % Returns\n % -------\n % GaussianStateX\n % The generated state prediction\n % GaussianStateX, optional\n % The generated measurement prediction\n %\n % See also update, smooth.\n \n % Predict state and measurement\n statePrediction = this.predictState(varargin{:});\n if nargin>1 && isa(varargin{1},'StateX')\n % Replace a potential prior with the generated prediction\n % before forwarding the arguments to the measurement\n % prediction. Failure to do so will result in errors!!!\n varargin{1} = statePrediction; \n end\n measurementPrediction = this.predictMeasurement(varargin{:});\n end\n \n function statePrediction = predictState(this,varargin)\n % predictState Perform Kalman Filter state prediction step\n % \n % Usage\n % -----\n % * predictState(this) calculates the predicted system state and covariance.\n %\n % See also update, smooth.\n \n timestamp = [];\n timestamp_old = [];\n for i = 1:min([2,nargin-1])\n if isa(varargin{i},'StateX')\n this.StatePosterior = varargin{i};\n timestamp_old = this.StatePosterior.Timestamp;\n elseif isdatetime(varargin{i})\n timestamp = varargin{i};\n end\n end\n \n if isempty(timestamp)\n dt = this.Model.Transition.TimestepDuration;\n timestamp = this.StatePosterior.Timestamp;\n else\n dt = timestamp - timestamp_old;\n end\n \n % Extract model parameters\n F = this.Model.Transition.matrix(dt);\n Q = this.Model.Transition.covar(dt);\n if(~isempty(this.Model.Control))\n B = this.Model.Control.feval();\n Qu = this.Model.Control.covar();\n else\n this.ControlInput = 0;\n B = 0;\n Qu = 0;\n end\n \n % Perform state prediction\n [statePredictionMean, statePredictionCovar] = ...\n this.predictState_(this.StatePosterior.Mean, this.StatePosterior.Covar, F, Q, this.ControlInput, B, Qu); \n \n statePrediction = GaussianStateX(statePredictionMean, statePredictionCovar, timestamp);\n this.StatePrediction = statePrediction;\n end\n \n function measurementPrediction = predictMeasurement(this, varargin)\n % PREDICTOBS Perform Kalman Filter measurement prediction step\n % \n % Usage\n % -----\n % * predict(this) calculates the predicted measurement,\n % as well as the associated uncertainty covariances.\n %\n % More details\n % ------------\n % * KalmanFilterX uses the Model class property, which should be an\n % instance of the TrackingX.Models.StateSpaceModel class, in order\n % to extract information regarding the underlying state-space model.\n % * State prediction is performed using the Model.Transition property,\n % which must be a subclass of TrackingX.Abstract.TransitionModel and\n % provide the following interface functions:\n % - Model.Transition.feval(): Returns the model transition matrix\n % - Model.Transition.covariance(): Returns the process noise covariance\n % * Measurement prediction and innovation covariance calculation is\n % performed usinf the Model.Measurement class property, which should be\n % a subclass of TrackingX.Abstract.TransitionModel and provide the\n % following interface functions:\n % - Model.Measurement.heval(): Returns the model measurement matrix\n % - Model.Measurement.covariance(): Returns the measurement noise covariance\n %\n % See also update, smooth.\n \n if nargin>1\n this.StatePrediction = varargin{1};\n end\n \n % Extract model parameters\n H = this.Model.Measurement.feval();\n R = this.Model.Measurement.covar();\n \n % Perform prediction\n [measurementPredictionMean, measurementPredictionCovar, this.KalmanGain] = ...\n this.predictMeasurement_(this.StatePrediction.Mean, this.StatePrediction.Covar, H, R);\n \n measurementPrediction = GaussianStateX(measurementPredictionMean,... \n measurementPredictionCovar,...\n this.StatePrediction.Timestamp);\n this.MeasurementPrediction = measurementPrediction;\n end\n \n function posterior = update(this, varargin)\n % UPDATE Perform Kalman Filter update step\n % \n % Usage\n % -----\n % * update(this) calculates the corrected sytem state and the \n % associated uncertainty covariance.\n %\n % See also KalmanFilterX, predict, iterate, smooth.\n \n if nargin>1\n if isa(varargin{1},'MeasurementX')\n this.MeasurementList = MeasurementListX(varargin{1});\n elseif isa(varargin{1}, 'StateX')\n this.StatePrediction = varargin{1};\n this.MeasurementList = MeasurementListX(varargin{2});\n end\n end\n if(this.MeasurementList.NumMeasurements)\n timestamp = this.MeasurementList.Timestamp;\n else\n timestamp = this.StatePrediction.Timestamp;\n end\n \n if(isempty(this.MeasurementPrediction.Mean) || isempty(this.MeasurementPrediction.Covar))\n [measurementPredictionMean, measurementPredictionCovar, this.KalmanGain] = ...\n this.predictMeasurement_(this.StatePrediction.Mean, this.StatePrediction.Covar, H, R);\n measurementPrediction = GaussianStateX(measurementPredictionMean,...\n measurementPredictionCovar,...\n this.StatePrediction.Timestamp);\n this.MeasurementPrediction = measurementPrediction;\n end \n \n % Perform single measurement update\n [posteriorMean, posteriorCovar] = this.update_(this.StatePrediction.Mean,this.StatePrediction.Covar,...\n this.MeasurementList.Vectors,this.MeasurementPrediction.Mean,...\n this.MeasurementPrediction.Covar,this.KalmanGain);\n posteriorCovar = (posteriorCovar+posteriorCovar')/2;\n \n posterior = GaussianStateX(posteriorMean, posteriorCovar, timestamp);\n this.StatePosterior = posterior;\n end\n \n function posterior = updatePDA(this, assocWeights, varargin)\n % UPDATEPDA Performs KF update step, for multiple measurements\n % Update is performed according to the generic (J)PDAF equations [1] \n % \n % Usage\n % -----\n % * updatePDA(assocWeights) Performs KF-PDA update step for multiple \n % measurements based on the provided (1-by-Nm+1) association weights \n % matrix assocWeights.\n %\n % [1] Y. Bar-Shalom, F. Daum and J. Huang, \"The probabilistic data association filter,\" in IEEE Control Models, vol. 29, no. 6, pp. 82-100, Dec. 2009.\n %\n % See also KalmanFilterX, Predict, Iterate, Smooth, resample.\n \n if(this.MeasurementList.NumMeasurements)\n timestamp = this.MeasurementList.Timestamp;\n else\n timestamp = this.StatePrediction.Timestamp;\n end\n \n [posteriorMean, posteriorCovar] = ...\n this.updatePDA_(this.StatePrediction.Mean,this.StatePrediction.Covar,this.MeasurementList.Vectors,...\n assocWeights,this.MeasurementPrediction.Mean,this.MeasurementPrediction.Covar,this.KalmanGain);\n\n posterior = GaussianStateX(posteriorMean,posteriorCovar,timestamp);\n this.StatePosterior = posterior;\n end\n \n function measurementLikelihoods = get.MeasurementLikelihoods(this)\n measurementLikelihoods = getMeasurementLikelihoods(this);\n end\n \n function statePrior = get.StatePrior(this)\n statePrior = this.StatePrior;\n end\n \n function set.StatePrior(this, newStatePrior)\n this.StatePrior = setStatePrior(this, newStatePrior);\n end\n \n function statePrediction = get.StatePrediction(this)\n statePrediction = this.StatePrediction;\n end\n \n function set.StatePrediction(this, newStatePrediction)\n this.StatePrediction = setStatePrediction(this, newStatePrediction);\n end\n \n function measurementPrediction = get.MeasurementPrediction(this)\n measurementPrediction = this.MeasurementPrediction;\n end\n \n function set.MeasurementPrediction(this, newMeasurementPrediction)\n this.MeasurementPrediction = setMeasurementPrediction(this, newMeasurementPrediction);\n end\n \n function statePosterior = get.StatePosterior(this)\n statePosterior = this.StatePosterior;\n end\n \n function set.StatePosterior(this, newStatePosterior)\n this.StatePosterior = setStatePosterior(this, newStatePosterior);\n end\n \n end\n \n methods (Static)\n \n function [xPred, PPred, yPred, S, K] = predict_(x,P,F,Q,H,R,u,B,O)\n % PREDICT_ Perform the discrete-time KF state and measurement\n % prediction steps, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % x: column vector\n % The (xDim x 1) state estimate at the previous time-step.\n % P: matrix \n % The (xDim x xDim) state covariance matrix at the previous\n % time-step.\n % F: matrix\n % An (xDim x xDim) state transition matrix.\n % Q: matrix\n % The (xDim x xDim) process noise covariance matrix.\n % H: matrix\n % A (xDim x yDim) measurement matrix.\n % R: matrix \n % The (yDim x yDim) measurement noise covariance matrix.\n % u: column vector, optional\n % A optional (xDim x 1) control input.\n % If omitted, no control input is used.\n % B: matrix, optional\n % An optional (xDim x xDim) control gain matrix.\n % If omitted, B is assumed to be 1.\n % O: matrix, optional\n % An optional (xDim x xDim) control noise covariance\n % matrix. If omitted, Q is assumed to be 0.\n %\n % Returns\n % -------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % Pxy: matrix\n % The (xDim x yDim) cross-covariance matrix.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n switch(nargin)\n case(6) \n u = 0;\n B = 0;\n O = 0;\n case(7)\n B = 1;\n O = 0;\n case(8)\n O = 0;\n end\n\n [xPred, PPred] = KalmanFilterX.predictState_(x,P,F,Q,u,B,O);\n [yPred, S, K] = KalmanFilterX.predictMeasurement_(xPred,PPred,H,R);\n end\n \n function [xPred, PPred] = predictState_(x,P,F,Q,u,B,Qu)\n % PREDICTSTATE_ Perform the discrete-time KF state prediction \n % step, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % x: column vector\n % The (xDim x 1) state estimate at the previous time-step.\n % P: matrix\n % The (xDim x xDim) state covariance matrix at the previous\n % time-step.\n % F: matrix\n % An (xDim x xDim) state transition matrix.\n % Q: matrix\n % The (xDim x xDim) process noise covariance matrix.\n % u: column vector, optional\n % An optional (xDim x 1) control input.\n % If omitted, no control input is used.\n % B: matrix, optional\n % An optional (xDim x xDim) control gain matrix.\n % If omitted, B is assumed to be 1.\n % O: matrix, optional\n % An optional (xDim x xDim) control noise covariance\n % matrix. If omitted, Q is assumed to be 0.\n %\n % Returns\n % -------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n switch(nargin)\n case(4) \n u = 0;\n B = 0;\n Qu = 0;\n case(5)\n B = 1;\n Qu = 0;\n case(6)\n Qu = 0;\n end\n\n % Compute predicted state mean and covariance\n xPred = F*x + B*u;\n PPred =F*P*F' + Q + B*Qu*B';\n end\n\n function [yPred, S, K] = predictMeasurement_(xPred,PPred,H,R)\n % PREDICTOBS_ Perform the discrete-time KF observation prediction \n % step, under the assumption of additive process noise.\n %\n % Parameters\n % ----------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate at the current\n % time-step.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix at \n % the current time-step.\n % H: matrix\n % An (xDim x yDim) measurement matrix.\n % R: matrix\n % The (yDim x yDim) measurement noise covariance matrix.\n %\n % Returns\n % -------\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % Pxy: matrix\n % The (xDim x yDim) cross-covariance matrix.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n % Compute predicted measurement mean and covariance\n yPred = H*xPred;\n Pxy = PPred*H';\n S = H*PPred*H' + R;\n K = Pxy/(S);\n end\n\n function [x,P] = update_(xPred,PPred,y,yPred,S,K)\n % UPDATE_ Perform the discrete-time KF update step, under the \n % assumption of additive process noisem for a single measurement.\n %\n % Parameters\n % ----------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n % y: column vector\n % The (yDim x 1) measurement vector.\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n % K: matrix\n % The (xDim x yDim) Kalman gain matrix at the current\n % time-step.\n %\n % Returns\n % -------\n % x: column vector\n % The (xDim x 1) state estimate at the current time-step.\n % P: matrix\n % The (xDim x xDim) state covariance matrix at the current\n % time-step.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n % Compute the filtered estimates\n x = xPred + K * (y - yPred);\n P = PPred - K*S*K';\n end\n\n function [x,P] = updatePDA_(xPred,PPred,Y,W,yPred,S,K)\n % UPDATEPDA_ Perform the discrete-time Probabilistic Data \n % Association (PDA) KF update step, under the assumption of additive process \n % noise, for multiple measurements (as a Gaussian Mixture)\n %\n % Parameters\n % ----------\n % xPred: column vector\n % The (xDim x 1) predicted state estimate.\n % PPred: matrix\n % The (xDim x xDim) predicted state covariance matrix.\n % Y: matrix\n % The (yDim x nY) measurement vector.\n % W: row vector\n % The (1 x nY+1) measurement association/mixture weights \n % vector. (dummy measurement assumed at index 1)\n % yPred: column vector\n % The (yDim x 1) predicted measurement estimate.\n % S: matrix\n % The (yDim x yDim) innovation covariance matrix.\n % K: matrix\n % The (xDim x yDim) Kalman gain matrix at the current\n % time-step.\n %\n % Returns\n % -------\n % x: column vector\n % The (xDim x 1) state estimate at the current time-step.\n % P: matrix\n % The (xDim x xDim) state covariance matrix at the current\n % time-step.\n %\n %October 2017 Lyudmil Vladimirov, University of Liverpool.\n\n % Get size of observation vector\n nY = size(Y,2);\n if(nY==0)\n x = xPred;\n P = PPred;\n return;\n end\n \n innov_err = Y - yPred;\n xupd = [xPred, xPred + K*innov_err];\n Pplus = PPred - K*S*K';\n \n try\n x = xupd*W';\n catch\n asd=2;\n end\n v_x = x - xupd;\n P = W(1)*(PPred + v_x(:,1)*v_x(:,1)');\n for j = 2:nY+1\n P = P + W(j)*(Pplus + v_x(:,j)*v_x(:,j)');\n end\n \n% % Compute innovation mean and (cross) covariance\n% innov_err = Y - yPred(:,ones(1,nY));\n% tot_innov_err = innov_err*W(2:end)';\n% Pc = PPred - K*S*K';\n% Pgag = K*((innov_err.*W(ones(yDim,1),2:end))*innov_err' - tot_innov_err*tot_innov_err')*K';\n% \n% % Compute filtered estimates\n% x = xPred + K*tot_innov_err; \n% P = W(1)*PPred + (1-W(1))*Pc + Pgag;\n P = (P+P')/2;\n end\n \n function config = getInitConfig()\n \n end\n end\nend", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Filters/Kalman/KalmanFilterX/KalmanFilterX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.6241986502241609}} {"text": "function [lf] = eeg_infinite_monopole(monpos, elc, vol)\n\n% EEG_INFINITE_MONOPOLE calculate the infinite medium potential for a monopole\n%\n% Use as\n% [lf] = eeg_infinite_monopole(monpos, elc, vol)\n%\n% Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993)\n% http://www.bem.fi/book/08/08.htm\n%\n% See also EEG_INFINITE_DIPOLE, EEG_HALFSPACE_DIPOLE, EEG_HALFSPACE_MONOPOLE\n\n% Copyright (C) 2011, Cristiano Micheli\n% Copyright (C) 2019, 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 ~isstruct(vol)\n % it only represents the conductivity, make a structure out of it\n vol = struct('cond', vol);\nend\n\nsiz = size(monpos);\nif any(siz==1)\n % positions are specified as a single vector\n Npoles = prod(siz)/3;\n monpos = monpos(:)'; % 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 Npoles = siz(1);\n monpos = monpos';\n monpos = monpos(:)'; % ensure that it is a row vector\nelse\n ft_error('incorrect specification of monopole locations');\nend\n\ncond = vol.cond;\nNelc = size(elc,1);\nlf = zeros(Nelc,Npoles);\n\nmu0 = 4*pi*1e-7; % Permeability of free space\nc = 2.99792458 * 1e8; % Speed of light\ne0 = 1 / (mu0*c^2); % Permittivity of Free Space\n\nfor i=1:Npoles\n % this is the position of monopole \"i\"\n monopole = monpos((1:3) + 3*(i-1));\n \n % distances from electrodes to monopole\n r = elc - ones(Nelc,1) * monopole;\n r = sqrt(sum(r.^2,2));\n \n lf(:,i) = 1 ./ (4*pi*cond*r);\nend\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/eeg_infinite_monopole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6240982320876591}} {"text": "% Van Leer scheme for one-dimensional Euler equations\n\n% Copyright 2001 P. Wesseling\n% This program and its subprograms may be freely used, modified and distributed\n% under the GNU General Public License: http://www.gnu.org/copyleft/gpl.html\n\n% Theory in Section 10.5 of:\n\n% \tP. Wesseling: Principles of Computational Fluid Dynamics\n% \tSpringer, Heidelberg, 2000 ISBN 3-5453-0. XII, 642 pp.\n% See http://ta.twi.tudelft.nl/nw/users/wesseling/cfdbook.html\n\n% This program makes Figs. 10.15, 10.16 in the book\n\n% Functions called: f, problem_specification, Riemann \n\nglobal PRL CRL MACHLEFT gamma pleft pright rholeft rhoright uleft...\n\turight tend lambda\t\t% lambda = dt/dx\n\n\t\t% .....................Input............................\ngamma = 1.4; \t% Ratio of specific heats\nJ = 48;\t\t% Number of grid cells\nbouncon = 0;\t% bouncon chooses outflow boundary conditions\n\t\t% = 0: Nothing happens: infinite domain\n\t\t% = 1: Solid wall at x = 1 with direct prescription of uwall\n\t\t% = 2: Solid wall at x = 1 with reflection b.c.\n\t\t% ....................End of input........................\n\ngammab = 1/(gamma - 1); gam1 = gamma-1; gamgam = gamma^gamma;\nproblem_specification\t\n\t\t\nh = 1/J; \t\t\t\t% Cell size\ndt = lambda*h;\t\t\t\t% Time step\nn = floor(tend/dt);\t\t\t% Number of time-steps\n\n% \t\tDefinition of grid numbering \n% x=0 \t\t\t\t\t x=1\n% grid |---o---|---o---|---o--- ... --|---o---|\n% 1 1 2 2 3 J-1 J \n\nxcenter = h*[1:J] - h/2;\t\t% Location of cell centers\n\npress = zeros(size(xcenter));\t\t% Preallocation of pressure, \nrhoold = press; uold = press;\t\t% density and velocity\nrhonew = press; mnew = press;\t\t% momentum \ntotenew = press;\t\t\t%\ttotal energy\n\nfor j = 1:length(xcenter)\t\t% Initial conditions\n if xcenter(j) < 0.5, press(j) = pleft; rhoold(j) = rholeft; uold(j) = uleft; \n else, \t press(j) = pright; rhoold(j) = rhoright; uold(j) = uright;\n end\nend\n\n\t% Initialization of cell center variables\ntotenold = rhoold.*(0.5*uold.*uold + gammab*press./rhoold); % Total energy rho*E\ntotenleft = totenold(1); totenright = totenold(J);\nmold = rhoold.*uold;\t\t\t\t\t % Momentum m\nc = sqrt(gamma*press./rhoold);\t\t\t\t % Sound speed \nmach = uold./c;\t\t\t\t\t\t % Mach number\t\t\t\t \n\n% Preallocation of split fluxes\nplus1 = c; minus1 = c; plus2 = c; minus2 = c; plus3 = c; minus3 = c;\n% Preallocation of van Leer fluxes\nflux1 = zeros(J-1,1); flux2 = flux1; flux3 = flux1;\n\nt = 0;\nfor i = 1:n, t = t + dt;\n Eflux1 = rhoold.*uold;\t\t\t% Eflux1,2,3 is Euler flux\n Eflux2 = Eflux1.*uold + (1/gamma)*rhoold.*c.^2;\n Eflux3 = 0.5*Eflux1.*uold.^2 + gammab*Eflux1.*c.^2; \n \n for j = 1:J\n if mach(j) > 1\n plus1(j) = Eflux1(j); plus2(j) = Eflux2(j); plus3(j) = Eflux3(j); \n elseif mach(j) < -1\n plus1(j) = 0; plus2(j) = 0; plus3(j) = 0; \n else\n plus1(j) = 0.25*rhoold(j)*c(j)*(1 + mach(j))^2;\n plus2(j) = plus1(j)*c(j)*(2 + gam1*mach(j))/gamma;\n plus3(j) = (plus2(j)^2/plus1(j))*gamma^2*0.5*gammab/(gamma+1);\n end\n end\n minus1 = Eflux1 - plus1; minus2 = Eflux2 - plus2; minus3 = Eflux3 - plus3; \n\n for j = 1:J-1\t\t\t\t\t% van Leer fluxes\n flux1(j) = plus1(j) + minus1(j+1);\n flux2(j) = plus2(j) + minus2(j+1);\n flux3(j) = plus3(j) + minus3(j+1);\n end\n \n\t% Update of state variables\n rhonew(1) = rholeft;\t\t rhonew(J) = rhoright; \n mnew(1) = rholeft*uleft; \t mnew(J) = rhoright*uright;\n totenew(1) = totenleft; \t totenew(J) = totenright;\n for j = 2:J-1\n rhonew(j) = rhoold(j) - lambda*(flux1(j) - flux1(j-1));\n mnew(j) = mold(j) - lambda*(flux2(j) - flux2(j-1));\n totenew(j) = totenold(j) - lambda*(flux3(j) - flux3(j-1));\n end\n\n if bouncon ~= 0\n if bouncon == 1\n rhowall = rhoold(J); uwall = 0;\n pwall = (gamma-1)*(totenold(J) - 0.5*mold(J)^2/rhoold(J)); % pwall = p(J) \n totenwall = pwall/(gamma-1) + 0.5*rhowall*uwall^2;\n else\n rhowall = rhoold(J); uwall = - mold(J)/rhoold(J);\n pwall = (gamma-1)*(totenold(J) - 0.5*mold(J)^2/rhoold(J)); % pwall = p(J) \n totenwall = pwall/(gamma-1) + 0.5*rhowall*uwall^2;\n end\n wallflux1 = rhowall*uwall;\n pwall = gam1*(totenwall - 0.5*wallflux1*uwall);\n wallflux2 = wallflux1.*uwall + pwall;\n wallflux3 = 0.5*wallflux1*uwall^2 + gammab*gamma*uwall*pwall;\n cwall = sqrt(gamma*pwall/rhowall); machwall = uwall/cwall; \n if machwall > 1\n plus1wall = wallflux1; plus2wall = wallflux2; plus3wall = wallflux3 ; \n elseif machwall < -1\n plus1wall = 0; plus2wall = 0; plus3wall = 0; \n else\n plus1wall = 0.25*rhowall*cwall*(1 + machwall)^2;\n plus2wall = plus1wall*cwall*(2 + gam1*machwall)/gamma;\n plus3wall = (plus2wall^2/plus1wall)*gamma^2*0.5*gammab/(gamma+1);\n end\n minus1wall = wallflux1 - plus1wall; \n minus2wall = wallflux2 - plus2wall; minus3wall = wallflux3 - plus3wall;\n \n flux1wall = plus1(J) + minus1wall;\t\t\t% van Leer fluxes\n flux2wall = plus2(J) + minus2wall;\n flux3wall = plus3(J) + minus3wall;\n \n rhonew(J) = rhoold(J) - lambda*(flux1wall - flux1(J-1));\n mnew(J) = mold(J) - lambda*(flux2wall - flux2(J-1));\n totenew(J) = totenold(J) - lambda*(flux3wall - flux3(J-1));\n end\n \t% Update of state variables \n uold = mnew./rhonew; press = gam1*(totenew - 0.5*mnew.*uold);\n rhoold = rhonew; totenold = totenew; mold = mnew;\n \n c = sqrt(gamma*press./rhoold); mach = uold./c;\nend\n\nentropy = log(press./rhoold.^gamma);\n\nfigure(1), clf\nsubplot(2,3,1),hold on,title('DENSITY','fontsize',14),plot(xcenter,rhonew,'o')\nsubplot(2,3,2),hold on,title('VELOCITY','fontsize',14),plot(xcenter,uold,'o')\nsubplot(2,3,3),hold on,title('PRESSURE','fontsize',14),plot(xcenter,press,'o')\nsubplot(2,3,4),hold on,title('MACHNUMBER','fontsize',14),plot(xcenter,mach,'o')\nsubplot(2,3,5),hold on,title('ENTROPY','fontsize',14),plot(xcenter,entropy,'o')\nsubplot(2,3,6),axis('off'),hold on,title('Van Leer scheme','fontsize',14)\n\nRiemann\t\t% Plot exact solution\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/cfdbook/chap10.3457/van_Leer_scheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6240982315432355}} {"text": "function [X, spectrum] = slcmds(D, d, w, ty)\n%SLMDS Performs Classical Multidimensional scaling\n%\n% $ Syntax $\n% - X = slcmds(D, d)\n% - X = slcmds(D, d, w)\n% - X = slcmds(D, d, w, 'sqr')\n% - [X, spectrum] = slcmds(...)\n%\n% $ Arguments $\n% - D: The pairwise distance matrix (n x n)\n% - d: The dimension of the embedding space\n% - w: The weights of samples (1 x n or [])\n% - X: The embedded samples (d x n)\n%\n% $ Description $\n% - X = slcmds(D, d) performs classic multidimensional scaling to\n% pursue an embedding space of d-dimension and the vector \n% representation in that space of the objects, such that the \n% distances are optimally preserved.\n%\n% - X = slcmds(D, d, w) If w is not empty, it performs classic \n% multidimensional scaling on weighted samples. \n%\n% - X = slcmds(D, d, w, 'sqr') indicates that D contains the square\n% of distances.\n%\n% - [X, spectrum] = slcmds(...) additionally outputs the spectrum of\n% the embedded space\n% \n% $ History $\n% - Created by Dahua Lin, on Sep 8th, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n raise_lackinput('slcmds', 2);\nend\n\nif ndims(D) ~= 2 || size(D, 1) ~= size(D, 2)\n error('sltoolbox:invalidarg', ...\n 'The D should be a square matrix');\nend\nn = size(D, 1);\n\nif d >= n\n error('sltoolbox:exceedbound', ...\n 'The dimension d should be less than the number of samples n');\nend\n\nif nargin < 3\n w = [];\nelse\n if ~isempty(w)\n if ~isequal(size(w), [1, n])\n error('sltoolbox:sizmismatch', ...\n 'If w is specified, it should be an 1 x n row vector');\n end\n end\nend\n\nif nargin >= 4 && strcmpi(ty, 'sqr')\n is_sqr = true;\nelse\n is_sqr = false;\nend\n\n\n%% compute\n\nif ~is_sqr\n K = sldists2kernels(D);\nelse\n K = sldists2kernels(D, 'sqr');\nend\n\n[X, spectrum] = slkernelembed(K, d, w);\n\n\n\n\n\n \n \n\n\n", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/wordsim/code/sltoolbox_r101/sltoolbox_r101/sltoolbox/manifold/slcmds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6240971406149711}} {"text": "function [x,lambda_opt,svd_state,Y_hat] = ridge_gcv(varargin)\n%[x_hat,lambda_opt] = ridgeGCV(Y,A,P)\n%\n% Estimates a ridge regression model, also know as Tikhonov regularization,\n% or minimum norm with L2 prior.\n%\n% x_hat = argmin(x) ||Y-A*x||^2 + lambda*||P*x||^2\n% with lambda > 0\n%\n% \n% [..., svd_state] = ridge_gcv(...) returns the svd decomposition. This can\n% be reused if the target vector does not change.\n%\n% [..., Y_hat] = ridge_gcv(...) returns the predicted target vector.\n% Residuals can be computed via E = Y-Y_hat;\n%\n% This code is based on a previous implementation used in Valdes-Hernandez\n% et al. (2009), written by Alejandro Ojeda and Pedro Valdez-Hernandez at\n% the Cuban Neuroscience Center in 2009.\n%\n% Author: Alejandro Ojeda, SCCN/INC/UCSD, Jul-2012\n% Tim Mullen, SCCN/INC/UCSD, Jan-2013, Apr-2013\n%\n% References:\n% Pedro A. Valdes-Hernandez, Alejandro Ojeda, Eduardo Martinez-Montes, Agustin\n% Lage-Castellanos, Trinidad Virues-Alba, Lourdes Valdes-Urrutia, Pedro A.\n% Valdes-Sosa, 2009. White matter architecture rather than\n% cortical surface area correlates with the EEG alpha rhythm. NeuroImage 49\n% (2010) 2328–2339\n\narg_define([0 Inf],varargin, ...\n arg_norep({'Y','TargetVector','y'},mandatory,[],'The target vector'), ...\n arg_norep({'A','DesignMatrix'},mandatory,[],'The design matrix. This is the data matrix (ie X).'), ...\n arg({'P','PriorInvCov'},[],[],'Prior inverse covariance (precision) matrix for params. Can be an [nc x nc] matrix, where nc is the number of columns of A. Can also be a scalar, P, specifying the prior inverse variance (precision) of each parameter (diagonal covariance matrix). If empty, identity covariance matrix assumed. A sparse matrix is advised if precision matrix is not dense.'), ...\n arg_nogui({'blksz','DesignMatrixBlockSize','designMatrixBlockSize'},[],[],'Design matrix structure. Can be a tuple [numrows numcols], in which case A consists of identical blocks of this size, along the main diagonal'), ...\n arg_subswitch({'lambdaMode','LambdaSelectionMode'},'grid_gcv', { ...\n 'manual' { ...\n arg({'lambda','RegularizationParam'},1,[0 Inf],'Regularization parameter (lambda)','type','denserealdouble') ...\n }, ...\n 'grid_gcv' { ...\n arg({'gridSize','GridSize'},100,[0 Inf],'Grid size for regularization param search. This is used to automatically select the regularization parameter which minimizes the Generalized Cross-Validation (GCV) criteria.') ...\n arg({'plotGCV','PlotGCV'},false,[],'Plot GCV curve'), ...\n } ...\n },'Selection mode for lambda. Automatic (GCV grid search) or Manual (must provide lambda)'), ...\n arg_nogui('svd_state',[],[],'SVD decomposition structure'), ...\n arg({'verb','Verbosity'},false,[],'Verbose output') ...\n );\n\n\n[nr,nc] = size(A);\n\n% if A is not sufficiently sparse, convert to full\nif issparse(A) && nnz(A)/numel(A) > 0.9\n A = full(A);\nend\n\nif isempty(svd_state)\n if verb, fprintf('Computing SVD of design matrix.\\nr'); end\n \n % init prior covmat\n if isscalar(P)\n P=P*speye(nc);\n end\n if ~isempty(P)\n Pinv = inverse(P);\n end\n % compute SVD\n if ~isempty(P)\n APinv = A*Pinv;\n else\n APinv = A;\n end\n if isempty(blksz)\n [U,S,V] = svd_wrapper(APinv);\n else\n %warning('block optimization not yet implemented');\n [U,S,V] = svd_wrapper(APinv);\n% [U,S,V] = svd_wrapper(APinv(1:blksz(1),1:blksz(2)));\n end\n if isempty(P)\n iPV = V;\n else\n iPV = Pinv*V;\n end\n s = diag(S);\n s2 = s.^2;\n Ut = U';\nelse\n iPV = svd_state.iPV;\n s = svd_state.s;\n s2 = svd_state.s2;\n Ut = svd_state.Ut;\nend\n\nUtY = Ut*Y;\n\nswitch lambdaMode.arg_selection\n case 'grid_gcv'\n % search over a grid of lambda values for the value that minimizes\n % the Generalized Cross Validation (GCV) criteria\n % lambdaOpt = argmin(lambda) { GCV(lambda) }\n \n % automatically determine lambda range based on singular values\n tol = max([nr nc])*eps(max(s));\n lgrid = logspace(log10(tol),log10(max(s)),lambdaMode.gridSize);\n gcv = zeros(lambdaMode.gridSize,1);\n for it=1:lambdaMode.gridSize\n % compute GCV criteria\n d = lgrid(it)./(s2+lgrid(it));\n f = diag(d)*UtY;\n gcv(it) = dot(f,f,1)/sum(d)^2;\n end\n loc = getMinima(gcv);\n if isempty(loc),\n % no minimum found, search for elbow instead\n if verb\n fprintf('no GCV minimum, finding elbow...\\nr'); \n end\n [val loc] = hlp_findElbow(gcv); % min(gcv)\n end\n loc = loc(end);\n lambda_opt = lgrid(loc);\n if verb\n fprintf('lambda: %0.5g, GCV: %0.5g\\nr',lambda_opt,gcv(loc)); \n end\n if lambdaMode.plotGCV\n plotLambdaGCV(lgrid,gcv,lambda_opt,loc); \n end\n case 'manual'\n lambda_opt = lambdaMode.lambda;\n otherwise\n error('SIFT:ridge_gcv:BadLambdaRule', ...\n 'Unknown lambda learning rule %s',lambdaMode.arg_selection);\nend\n\n% solve system for parameters x\nx = iPV*bsxfun(@times,(s./(s2+lambda_opt^2)),UtY);\n\nif nargout > 2\n Y_hat = A*x;\nend\nif nargout > 3\n svd_state.iPV = iPV;\n svd_state.s = s;\n svd_state.s2 = s2;\n svd_state.UtY = UtY;\nend\n\n% Helper functions\n% -------------------------------------------------------------------------\nfunction [U,S,V] = svd_wrapper(A)\n% compute SVD\nif issparse(A)\n [U,S,V] = svds(A,min(size(A)));\nelse\n [U,S,V] = svd(A,'econ');\nend\n \nfunction plotLambdaGCV(lgrid,gcv,lambda_opt,loc)\n% plot lambda versus GCV\nfigure;\nsemilogx(lgrid,gcv)\nxlabel('log-lambda');\nylabel('GCV');\nhold on;\nplot(lambda_opt,gcv(loc),'rx','linewidth',2);\nhold off; grid on;\n\n\nfunction indmin = getMinima(x)\n% get minimum of a function\nfminor = diff(x)>=0;\nfminor = ~fminor(1:end-1, :) & fminor(2:end, :);\nfminor = [0; fminor; 0];\nindmin = find(fminor);\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/est/mvar/solvers/ridge_gcv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6240971277226453}} {"text": "classdef IMMOEA_F9 < PROBLEM\n% \n% Benchmark MOP for testing IM-MOEA\n\n%------------------------------- Reference --------------------------------\n% R. Cheng, Y. Jin, K. Narukawa, and B. Sendhoff, A multiobjective\n% evolutionary algorithm using Gaussian process-based inverse modeling,\n% IEEE Transactions on Evolutionary Computation, 2015, 19(6): 838-856.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = zeros(1,obj.D);\n obj.upper = [1,zeros(1,obj.D-1)+10];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n t = X(:,2:obj.D).^(1./(1+3*repmat(2:obj.D,size(X,1),1)/obj.D)) - repmat(X(:,1),1,obj.D-1);\n g = sum(t.^2/4000,2) - prod(cos(t./repmat(sqrt(1:obj.D-1),size(X,1),1)),2) + 2;\n PopObj(:,1) = X(:,1);\n PopObj(:,2) = g.*(1-sqrt(PopObj(:,1)./g));\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - sqrt(R(:,1));\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/IMMOEA_F9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6240293229471964}} {"text": "function [x,y,z,s,w,flag] = msquadsolve(Q,c,A,b,C), \n% MSQUADSOLVE\n% \n% USAGE: [x,y,z,s,w,flag] = msquadsolve(Q,c,A,b,C)\n%\n% PARAMETERS: Q -> (n,n) symetric matrix (definite positive)\n% c -> (n,1) vector\n% A -> (m,n) matrix \n% b -> (m,1) vector\n% C -> (m,1) vector\n%\n% x -> primal variables\n% y -> lagrangian coeff of equality constraints\n% z -> dual variables of x\n% s -> primal auxiliary variable (only if C < Inf)\n% w -> dual variable of s\n% flag -> set to 0 => no problem, set to 1 => problem\n%\n% DESCRIPTION: Primal-dual method for quadratic programming\n% \n% minimize c'*x + 0.5*x'*Q*x\n%\n% subject to A*x=b\n% 0<= x <= C\n% The method used here is a primal dual method with a predictor-corrector\n% approach and a logarithmic barrier. I used the heuristic from two \n% existing methods LOQO and HOPDM. The method is an iterative method. The \n% maximal number of iteration is stored in the variable 'max_iter'.\n%\n% ERRORS AND BUGS: 1. There is no test about the conditionning of the matrix Q. If the iteration\n% 50 has been reached, then the optimization may not be finished and the output\n% may be wrong. \n% 2. If C contains infinite values then, the algorithm will consider that all its\n% components are actually infinite.\n%\n% NOTES: 50 iterations have always been sufficient to solve all problems.\n% This code should be read with the tech. report:\n% \"Regularized Symmetric Indefinite Systems in Interior Point\n% Methods for Linear and Quadratic Optimization\", \n% A. Altman and J. Gondzio, Logilab Tech. Report 1998.6\n%\n% Andre Elisseeff, May. 2001\n \n %% init \n verbose = 0;\n n = size(Q,1);\n m = size(A,1);\n H = zeros(n+m,n+m);\n flag=1;\n maxC = max(C);\n \n %% Values of the original HOPDM of Gondzio and Altmann\n dinf = 10^(-14);\n smallz = 10^(-14);\n smallt = 2.3*10^(-16); \n opttol = 10^(-6);\n itref = 1;\n mu = 1;\n maxiter = 50; \n \n %% init values of the primal and dual variables\n x=ones(n,1);\n z=ones(n,1);\n y=ones(m,1);\n if maxC < Inf,\n s=ones(n,1);\n w=ones(n,1);\n else\n s=[];w=[];\n end; \n \n %% Description of variables:\n %%\n %% x,s -> primal variables\n %% z,w -> dual variables\n %% n -> number of variables in the initial pb (size of x)\n %% m -> number of constraints in A\n %%\n %% dinf -> smallest value for all variables \n %% smallz -> smallest value of z\n %% smallt -> smallest value for t in the computation of the matrix theta\n %% opttol -> acceptable tolerance for optimality conditions\n %% itref -> iteration counter\n %% maxiter -> maximum number of iteration\n \n %% Analyze the constraints...\n disp(sprintf('Analyzing the equality constraints...\\n'));\n [QQ,RR]=qr(A',0);\n [mm,nb] = size(QQ); %% number of eq constraints\n ind = 1:1:nb;\n for i=1:nb,\n if abs(RR(i,i)) < 100*eps\n disp(sprintf('Constraints %d removed because of dependence\\n',i));\n ind(i)=0;\n end;\n end; \n indice = find(ind >0);\n \n if (isempty(indice))\n disp(sprintf('No equality constraints... \\n'));\n A=[];\n m=0;\n else\n A = A(indice,:); %% new independent eq constraints \n b = b(indice);\n y = y(indice);\n m=length(indice);\n end;\n clear QQ;clear RR;\n u = C;\n %% init values before looping\n cont = 1;\n objQ = 0.5*x'*Q*x;\n \n %% init values of primal and dual objective functions\n pobjo = abs(c'*x+objQ) + 1;\n if maxC < inf,\n dobjo = abs(b'*y - u'*w - objQ);\n else\n dobjo = abs(b'*y - objQ);\n end;\n%%%%%%%%%%%%%%\n%% MAIN LOOP\n%%%%%%%%%%%%%%\n while (cont)&(itref<=maxiter)\n %% Compute the primal objective function\n objQ = 0.5*x'*Q*x;\n pobj = c'*x+objQ;\n if (maxC 10^6) \n disp(sprintf('Solution not bounded in the primal. Exit.\\n'));\n return;\n end;\n if (dd > 10^6) \n disp(sprintf('Solution not bounded in the dual. Exit.\\n'));\n return;\n end;\n \n %% test if optimality\n oldgap = dlgap;\n dp = abs(dobj) + 1;\n if ((abs(dlgap)/dp) <= opttol)\n disp(sprintf('Optimal solution found. Exit.\\n'));\n cont = 0;\n break;\n end;\n \n dp = dp + abs(pobj);\n T = abs(dlgap)/dp;\n \n %% put the variables away from zero (from HOPDM)\n if (itref <= 3)\n ax = 2*10^(-3);\n az = 10^(-3);\n elseif (T >= 0.8)\n ax = 2*10^(-4);\n az = 10^(-4);\n elseif (T >= 0.1)\n ax = 2*10^(-5);\n az = 10^(-5);\n elseif (T >=0.01)\n ax = 2*10^(-6);\n az = 10^(-6);\n elseif (T>=0.001)\n ax = 2*10^(-7);\n az = 10^(-7);\n elseif (T>=0.0001)\n ax = 2*10^(-8);\n az = 10^(-7);\n elseif (T>=0.00001)\n ax = 2*10^(-9);\n az = 10^(-9);\n else\n ax = T*10^(-5);\n az = ax;\n end;\n \n %% consider only variables that can be changed\n x = x + ax;\n z = z + az;\n if maxC < Inf\n s = s + ax;\n w = w + az;\n end;\n %% Compute the values of xi_b, xi_c and xi_u\n xi_b = -A*x + b; \n xi_c = c - A'*y - z + Q*x;\n xi_z = - x.*z;\n if maxC < Inf,\n xi_c=xi_c + w;\n xi_u = u - x - s;\n xi_w = - s.*w;\n end;\n %% Compute theta = (z/x + w/s)\n \n %% for bounded variables\n if maxC= 10^8);\n if ~isempty(neglect)\n theta(neglect)=(10^4)*sqrt(theta(neglect));\n end;\n %% factorize H = [-Q-theta^(-1) A^T]\n %% [ A 0 ]\n \n H = zeros(n+m,n+m);\n H(1:n,1:n) = -Q-diag(theta);\n H(n+1:n+m,1:n) = A;\n H(1:n,n+1:n+m) = A';\n \n %% Compute the predictor step\n if maxC < Inf,\n f = xi_c-xi_z./x+(xi_w - xi_u.*w)./s ;\n h = xi_b;\n else\n f = xi_c - xi_z./x;\n h = xi_b;\n end;\n delta=H\\[f;h];\n dx = delta(1:n);\n dy = delta(n+1:n+m);\n dz = (xi_z-z.*dx)./x;\n if maxC1 && ~isempty(p)\n if p thresh * std)\n% - threshRatio : Detect asymetric triangles (ratio perimeter/area > thresh * std)\n% - threshAngle : Detect triangles with angles that are too open (angle in degrees > thresh)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012-2016\n\n% ===== PARSE INPUTS =====\nif (nargin < 6) || isempty(threshEdge)\n threshEdge = [];\nend\nif (nargin < 5) || isempty(threshAngle)\n threshAngle = [];\nend\nif (nargin < 4) || isempty(threshRatio)\n threshRatio = [];\nend\nif (nargin < 3)\n threshArea = [];\nend\niFacesRemoveArea = [];\niFacesRemoveRatio = [];\niFacesRemoveAngle = [];\niFacesRemoveEdge = [];\n\n% ===== COMPUTE SURFACE STATISTICS =====\n% Triangles area\ntriArea = tess_area(Vertices, Faces);\n% Compute the vector of each edge\nv1 = Vertices(Faces(:,1),:) - Vertices(Faces(:,2),:);\nv2 = Vertices(Faces(:,1),:) - Vertices(Faces(:,3),:);\nv3 = Vertices(Faces(:,2),:) - Vertices(Faces(:,3),:);\n\n% ===== THRESHOLD: AREA =====\n% Detect the faces that have an area above the threshold\nif ~isempty(threshArea) && (threshArea > 0)\n iFacesRemoveArea = find(triArea - mean(triArea) > threshArea * std(triArea));\nend\n\n% ===== THRESHOLD: PERIMETER/AREA =====\nif ~isempty(threshRatio) && (threshRatio > 0)\n % Compute perimeter again\n triPerimeter = tess_perimeter(Vertices, Faces);\n % Ratio perimeter / area\n ratio = (triPerimeter ./ triArea);\n % Detect the Faces that have an area above the threshold\n iFacesRemoveRatio = find(ratio - mean(ratio) > threshRatio * std(ratio));\nend\n\n% ===== THRESHOLD: ANGLE =====\nif ~isempty(threshAngle) && (threshAngle > 0)\n % Compute the angle between all the vectors\n maxAngle = zeros(size(Vertices,1),1);\n for i = 1:size(v1,1)\n maxAngle(i) = max([atan2(norm(cross(v1(i,:),v2(i,:))), dot(v1(i,:),v2(i,:))), ...\n atan2(norm(cross(v1(i,:),v3(i,:))), dot(v1(i,:),v3(i,:))), ...\n atan2(norm(cross(v2(i,:),v3(i,:))), dot(v2(i,:),v3(i,:)))]);\n end\n % Convert to degrees\n maxAngle = maxAngle / 2 / pi * 360;\n % Detect the Faces that have an area above the threshold\n iFacesRemoveAngle = find(maxAngle > threshAngle);\nend\n\n% ===== THRESHOLD: EDGE LENGTH =====\nif ~isempty(threshEdge) && (threshEdge > 0)\n % Compute the length of all the edges\n edgeLength = sqrt(v1.^2 + v2.^2 + v3.^2);\n % Split long edges\n iFacesRemoveEdge = find(edgeLength - mean(edgeLength) > threshEdge * std(edgeLength));\nend\n\n% List of faces to remove\niFacesRemove = [iFacesRemoveArea(:); iFacesRemoveRatio(:); iFacesRemoveAngle(:)];\n% Keep only the good faces\nif ~isempty(iFacesRemove)\n Faces(iFacesRemove,:) = [];\nend\n\n \n \n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/anatomy/tess_threshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.623941693388694}} {"text": "function result = simplex_unit_05_nd ( func, n )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_UNIT_05_ND approximates an integral inside a unit simplex in ND.\n%\n% Integration region:\n%\n% The unit simplex in N dimensions,\n% 0 <= X(1:N),\n% Sum ( X(1:N) ) <= 1.\n%\n% Discussion:\n%\n% An N^2 + 3 N + 3 point formula of degree 5 is used. This is\n% Stroud formula TN:5-1.\n%\n% (For N = 2, the number of points is actually only 7, and\n% for N = 3, the number of points is actually only 15.)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Arthur H Stroud,\n% A Fifth Degree Integration Formula for the N-Simplex,\n% SIAM Journal on Numerical Analysis,\n% Volume 6, Number 1, March 1969.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function which evaluates F(X) at the N-dimensional point\n% X, of the form\n% function value = func ( n, x )\n%\n% Input, integer N, the dimension of the space. For this routine,\n% it must be the case that 2 <= N <= 16.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n coef1 = [ ...\n 0.0E+00, 0.225E+00, ...\n 0.118518518519E+00, 0.0631521898883E+00, ...\n 0.235714285714E+00, 0.791575476992E+00, ...\n 1.85798728021E+00, 3.53666958042E+00, ...\n 5.90844340844E+00, 9.03765432098E+00, ...\n 12.9758241758E+00, 17.7645108738E+00, ...\n 23.4375030259E+00, 30.0224941950E+00, ...\n 37.5423613501E+00, 46.0161454949E+00 ];\n coef21 = [ ...\n 0.0E+00, 0.12593918054483E+00, ...\n 0.0719370837790E+00, 0.0470456145702E+00, ...\n 0.0333009774677E+00, 0.0248633014592E+00, ...\n 0.0192679696358E+00, 0.0153322153879E+00, ...\n 0.0124316229901E+00, 0.0102112988361E+00, ...\n 0.00845730697460E+00, 0.00703433430999E+00, ...\n 0.00585330520067E+00, 0.00485356735291E+00, ...\n 0.00399261092720E+00, 0.00323988713017E+00 ];\n coef22 = [ ...\n 0.0E+00, 0.13239415278851E+00, ...\n 0.0690682072263E+00, 0.0371530185868E+00, ...\n -0.0719253160920E+00, -0.264323879461E+00, ...\n -0.537926779961E+00, -0.886895605701E+00, ...\n -1.30409181465E+00, -1.78227048964E+00, ...\n -2.31462336314E+00, -2.89499045158E+00, ...\n -3.51790849765E+00, -4.17858310668E+00, ...\n -4.87282884913E+00, -5.59699944261E+00 ];\n coef31 = [ ...\n 0.0E+00, 0.0E+00, ...\n 0.0529100529100E+00, 0.0261368740713E+00, ...\n 0.0499020181331E+00, 0.0782233395867E+00, ...\n 0.109041040862E+00, 0.140874828568E+00, ...\n 0.172735353396E+00, 0.203992490408E+00, ...\n 0.234263814181E+00, 0.263332763315E+00, ...\n 0.291091849264E+00, 0.317504208212E+00, ...\n 0.342577872069E+00, 0.366348654344E+00 ];\n coef32 = [ ...\n 0.0E+00, 0.0E+00, ...\n 0.0E+00, 0.0254485903613E+00, ...\n 0.0165000982690E+00, 0.0115218303668E+00, ...\n 0.00850478779483E+00, 0.00655297510968E+00, ...\n 0.00522372456259E+00, 0.00428017828134E+00, ...\n 0.00358722367033E+00, 0.00306362964360E+00, ...\n 0.00265836687133E+00, 0.00233816221525E+00, ...\n 0.00208061510846E+00, 0.00187022027571E+00 ];\n\n if ( n < 2 | 16 < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SIMPLEX_UNIT_05_ND - Fatal error!\\n' );\n fprintf ( 1, ' Input spatial dimension N out of range.\\n' );\n fprintf ( 1, ' N = %d\\n', n );\n error ( 'SIMPLEX_UNIT_05_ND - Fatal error!' );\n end\n\n quad = 0.0;\n%\n% S1\n%\n x(1:n) = 1.0E+00 / ( n + 1 );\n quad = quad + coef1(n) * feval ( func, n, x );\n%\n% S21\n%\n r1 = ( ( n + 4 ) - sqrt ( 15.0E+00 ) ) / ( n * n + 8 * n + 1 );\n s1 = 1.0E+00 - n * r1;\n\n x(1:n) = r1;\n\n for i = 1 : n + 1\n\n quad = quad + coef21(n) * feval ( func, n, x );\n\n if ( 1 < i )\n x(i-1) = r1;\n end\n\n if ( i < n + 1 )\n x(i) = s1;\n end\n\n end\n%\n% S22\n%\n r2 = ( n + 4 + sqrt ( 15.0E+00 ) ) / ( n * n + 8 * n + 1 );\n s2 = 1.0E+00 - n * r2;\n\n x(1:n) = r2;\n\n for i = 1 : n + 1\n\n quad = quad + coef22(n) * feval ( func, n, x );\n\n if ( 1 < i )\n x(i-1) = r2;\n end\n\n if ( i < n + 1 )\n x(i) = s2;\n end\n\n end\n%\n% S31\n%\n u1 = ( n + 7 + 2.0E+00 * sqrt ( 15.0E+00 ) ) / ( n * n + 14 * n - 11 );\n v1 = ( ( 4 * n - 2 ) - ( n - 1 ) * sqrt ( 15.0E+00 ) ) / ( n * n + 14 * n - 11 );\n\n for i = 1 : n\n\n x(1:n) = u1;\n x(i) = v1;\n\n for j = i : n\n\n if ( i < j - 1 )\n x(j-1) = u1;\n end\n\n x(j) = v1;\n\n quad = quad + coef31(n) * feval ( func, n, x );\n\n end\n\n end\n%\n% S32\n%\n u2 = ( n + 7 - 2.0E+00 * sqrt ( 15.0E+00 ) ) / ( n^2 + 14 * n - 11 );\n v2 = ( ( 4 * n - 2 ) + ( n - 1 ) * sqrt ( 15.0E+00 ) ) / ( n^2 + 14 * n - 11 );\n\n for i = 1 : n\n\n x(1:n) = u2;\n x(i) = v2;\n\n for j = i : n\n\n if ( i < j - 1 )\n x(j-1) = u2;\n end\n\n x(j) = v2;\n\n quad = quad + coef32(n) * feval ( func, n, x );\n\n end\n\n end\n\n volume = simplex_unit_volume_nd ( n );\n\n result = quad * volume;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/simplex_unit_05_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6237536157588536}} {"text": "function [dx] = spm_dx(dfdx,f,t)\n% returns dx(t) = (expm(dfdx*t) - I)*inv(dfdx)*f\n% FORMAT [dx] = spm_dx(dfdx,f,[t])\n% dfdx = df/dx\n% f = dx/dt\n% t = integration time: (default t = Inf);\n% if t is a cell (i.e., {t}) then t is set to:\n% exp(t - log(diag(-dfdx))\n%\n% dx = x(t) - x(0)\n%--------------------------------------------------------------------------\n% Integration of a dynamic system using local linearization. This scheme\n% accommodates nonlinearities in the state equation by using a functional of\n% f(x) = dx/dt. This uses the equality\n%\n% expm([0 0 ]) = (expm(t*dfdx) - I)*inv(dfdx)*f\n% [t*f t*dfdx]\n%\n% When t -> Inf this reduces to\n%\n% dx(t) = -inv(dfdx)*f\n%\n% These are the solutions to the gradient ascent ODE\n%\n% dx/dt = k*f = k*dfdx*x =>\n%\n% dx(t) = expm(t*k*dfdx)*x(0)\n% = expm(t*k*dfdx)*inv(dfdx)*f(0) -\n% expm(0*k*dfdx)*inv(dfdx)*f(0)\n%\n% When f = dF/dx (and dfdx = dF/dxdx), dx represents the update from a\n% Gauss-Newton ascent on F. This can be regularised by specifying {t}\n% A heavy regularization corresponds to t = -4 and a light\n% regularization would be t = 4. This version of spm_dx uses an augmented\n% system and the Pade approximation to compute requisite matrix\n% exponentials\n%\n% references:\n%\n% Friston K, Mattout J, Trujillo-Barreto N, Ashburner J, Penny W. (2007).\n% Variational free energy and the Laplace approximation. NeuroImage.\n% 34(1):220-34\n%\n% Ozaki T (1992) A bridge between nonlinear time-series models and\n% nonlinear stochastic dynamical systems: A local linearization approach.\n% Statistica Sin. 2:113-135.\n%\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_dx.m 7144 2017-07-31 13:55:55Z karl $\n\n% defaults\n%--------------------------------------------------------------------------\nnmax = 512; % threshold for numerical approximation\nif nargin < 3, t = Inf; end % integration time\nxf = f; f = spm_vec(f); % vectorise\nn = length(f); % dimensionality\n\n% t is a regulariser\n%--------------------------------------------------------------------------\nsw = warning('off','MATLAB:log:logOfZero');\nif iscell(t)\n \n % relative integration time\n %----------------------------------------------------------------------\n t = t{:};\n if isscalar(t)\n t = exp(t - spm_logdet(dfdx)/n);\n else\n t = exp(t - log(diag(-dfdx)));\n end\n \nend\nwarning(sw);\n\n% use a [pseudo]inverse if all t > TOL\n%==========================================================================\nif min(t) > exp(16)\n \n dx = -spm_pinv(dfdx)*f;\n \nelse\n \n % ensure t is a scalar or matrix\n %----------------------------------------------------------------------\n if isvector(t), t = diag(t); end\n \n % augment Jacobian and take matrix exponential\n %======================================================================\n J = spm_cat({0 [] ;\n t*f t*dfdx});\n \n % solve using matrix expectation\n %----------------------------------------------------------------------\n if n <= nmax\n dx = spm_expm(J);\n dx = dx(:,1);\n else \n x = sparse(1,1,1,n + 1,1);\n dx = expv(1,J,x);\n end\n \n % recover update\n %----------------------------------------------------------------------\n dx = dx(2:end);\n \nend\ndx = spm_unvec(real(dx),xf);\n\nreturn\n\n\n%==========================================================================\n% Roger B. Sidje (rbs@maths.uq.edu.au)\n% EXPOKIT: Software Package for Computing Matrix Exponentials.\n% ACM - Transactions On Mathematical Software, 24(1):130-156, 1998\n\nfunction [w, err, hump] = expv( t, A, v, tol, m )\n% FOTMAT [w, err, hump] = expv( t, A, v, tol, m )\n% EXPV computes an approximation of w = exp(t*A)*v for a\n% general matrix A using Krylov subspace projection techniques.\n% It does not compute the matrix exponential in isolation but instead,\n% it computes directly the action of the exponential operator on the\n% operand vector. This way of doing so allows for addressing large\n% sparse problems. The matrix under consideration interacts only\n% via matrix-vector products (matrix-free method).\n%\n% w = expv( t, A, v )\n% computes w = exp(t*A)*v using a default tol = 1.0e-7 and m = 30.\n%\n% [w, err] = expv( t, A, v )\n% renders an estimate of the error on the approximation.\n%\n% [w, err] = expv( t, A, v, tol )\n% overrides default tolerance.\n%\n% [w, err, hump] = expv( t, A, v, tol, m )\n% overrides default tolerance and dimension of the Krylov subspace,\n% and renders an approximation of the `hump'.\n%\n% The hump is defined as:\n% hump = max||exp(sA)||, s in [0,t] (or s in [t,0] if t < 0).\n% It is used as a measure of the conditioning of the matrix exponential\n% problem. The matrix exponential is well-conditioned if hump = 1,\n% whereas it is poorly-conditioned if hump >> 1. However the solution\n% can still be relatively fairly accurate even when the hump is large\n% (the hump is an upper bound), especially when the hump and\n% ||w(t)||/||v|| are of the same order of magnitude (further details in\n% reference below).\n%\n% Example 1:\n% ----------\n% n = 100;\n% A = rand(n);\n% v = eye(n,1);\n% w = expv(1,A,v);\n%\n% Example 2:\n% ----------\n% % generate a random sparse matrix\n% n = 100;\n% A = rand(n);\n% for j = 1:n\n% for i = 1:n\n% if rand < 0.5, A(i,j) = 0; end;\n% end;\n% end;\n% v = eye(n,1);\n% A = sparse(A); % invaluable for a large and sparse matrix.\n%\n% tic\n% [w,err] = expv(1,A,v);\n% toc\n%\n% disp('w(1:10) ='); disp(w(1:10));\n% disp('err ='); disp(err);\n%\n% tic\n% w_matlab = expm(full(A))*v;\n% toc\n%\n% disp('w_matlab(1:10) ='); disp(w_matlab(1:10));\n% gap = norm(w-w_matlab)/norm(w_matlab);\n% disp('||w-w_matlab|| / ||w_matlab|| ='); disp(gap);\n%\n% In the above example, n could have been set to a larger value,\n% but the computation of w_matlab will be too long (feel free to\n% discard this computation).\n%\n% See also MEXPV, EXPOKIT.\n\n% Roger B. Sidje (rbs@maths.uq.edu.au)\n% EXPOKIT: Software Package for Computing Matrix Exponentials.\n% ACM - Transactions On Mathematical Software, 24(1):130-156, 1998\n%__________________________________________________________________________\n\n[n,n] = size(A);\nif nargin == 3,\n tol = 1.0e-7;\n m = min(n,30);\nend;\nif nargin == 4,\n m = min(n,30);\nend;\n\nanorm = norm(A,'inf');\nmxrej = 10; btol = 1.0e-7;\ngamma = 0.9; delta = 1.2;\nmb = m; t_out = abs(t);\nnstep = 0; t_new = 0;\nt_now = 0; s_error = 0;\nrndoff= anorm*eps;\n\nk1 = 2; xm = 1/m; normv = norm(v); beta = normv;\nfact = (((m+1)/exp(1))^(m+1))*sqrt(2*pi*(m+1));\nt_new = (1/anorm)*((fact*tol)/(4*beta*anorm))^xm;\ns = 10^(floor(log10(t_new))-1); t_new = ceil(t_new/s)*s;\nsgn = sign(t); nstep = 0;\n\nw = v;\nhump = normv;\nwhile t_now < t_out\n nstep = nstep + 1;\n t_step = min( t_out-t_now,t_new );\n V = zeros(n,m+1);\n H = zeros(m+2,m+2);\n \n V(:,1) = (1/beta)*w;\n for j = 1:m\n p = A*V(:,j);\n for i = 1:j\n H(i,j) = V(:,i)'*p;\n p = p-H(i,j)*V(:,i);\n end;\n s = norm(p);\n if s < btol,\n k1 = 0;\n mb = j;\n t_step = t_out-t_now;\n break;\n end;\n H(j+1,j) = s;\n V(:,j+1) = (1/s)*p;\n end;\n if k1 ~= 0,\n H(m+2,m+1) = 1;\n avnorm = norm(A*V(:,m+1));\n end;\n ireject = 0;\n while ireject <= mxrej,\n mx = mb + k1;\n F = expm(sgn*t_step*H(1:mx,1:mx));\n if k1 == 0,\n err_loc = btol;\n break;\n else\n phi1 = abs( beta*F(m+1,1) );\n phi2 = abs( beta*F(m+2,1) * avnorm );\n if phi1 > 10*phi2,\n err_loc = phi2;\n xm = 1/m;\n elseif phi1 > phi2,\n err_loc = (phi1*phi2)/(phi1-phi2);\n xm = 1/m;\n else\n err_loc = phi1;\n xm = 1/(m-1);\n end;\n end;\n if err_loc <= delta * t_step*tol,\n break;\n else\n t_step = gamma * t_step * (t_step*tol/err_loc)^xm;\n s = 10^(floor(log10(t_step))-1);\n t_step = ceil(t_step/s) * s;\n if ireject == mxrej,\n error('The requested tolerance is too high.');\n end;\n ireject = ireject + 1;\n end;\n end;\n mx = mb + max( 0,k1-1 );\n w = V(:,1:mx)*(beta*F(1:mx,1));\n beta = norm( w );\n hump = max(hump,beta);\n \n t_now = t_now + t_step;\n t_new = gamma * t_step * (t_step*tol/err_loc)^xm;\n s = 10^(floor(log10(t_new))-1);\n t_new = ceil(t_new/s) * s;\n \n err_loc = max(err_loc,rndoff);\n s_error = s_error + err_loc;\nend;\nerr = s_error;\nhump = hump / normv;\n\nreturn\n\n\nfunction E = padm( A, p )\n% FORMAT E = padm( A, p )\n% PADM computes the matrix exponential exp(A) using the irreducible\n% (p,p)-degree rational Pade approximation to the exponential function.\n%\n% E = padm( A )\n% p is internally set to 6 (recommended and generally satisfactory).\n%\n% See also CHBV, EXPOKIT and the MATLAB supplied functions EXPM and EXPM1.\n\n% Roger B. Sidje (rbs@maths.uq.edu.au)\n% EXPOKIT: Software Package for Computing Matrix Exponentials.\n% ACM - Transactions On Mathematical Software, 24(1):130-156, 1998\n%__________________________________________________________________________\n\nif nargin == 1, p = 6; end;\n[n,n] = size(A);\n\n% Pade coefficients (1-based instead of 0-based as in the literature)\n%--------------------------------------------------------------------------\nc(1) = 1;\nfor k = 1:p\n c(k+1) = c(k)*((p+1-k)/(k*(2*p+1-k)));\nend;\n\n% Scaling\n%--------------------------------------------------------------------------\ns = norm(A,'inf');\nif s > 0.5,\n s = max(0,fix(log(s)/log(2))+2);\n A = 2^(-s)*A;\nend;\n\n% Horner evaluation of the irreducible fraction (see ref. above)\n%--------------------------------------------------------------------------\nI = eye(n);\nA2 = A*A;\nQ = c(p+1)*I;\nP = c(p)*I;\nodd = 1;\nfor k = p-1:-1:1,\n if odd == 1,\n Q = Q*A2 + c(k)*I;\n else\n P = P*A2 + c(k)*I;\n end;\n odd = 1-odd;\nend;\nif odd == 1\n Q = Q*A;\n Q = Q - P;\n E = -(I + 2*(Q\\P));\nelse\n P = P*A;\n Q = Q - P;\n E = I + 2*(Q\\P);\nend;\n\n% Squaring\n%--------------------------------------------------------------------------\nfor k = 1:s,\n E = E*E;\nend;\n\nreturn\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/spm_dx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6237536119016236}} {"text": " function y = Gtomo_nufft_filter(omega, ob, do_phase)\n%function y = Gtomo_nufft_filter(omega, ob, do_phase)\n% build the sinogram-spectrum-sized matrix\n% that is .* multiplied after 2D FT, before iFFT or NUiFFT\n% in\n%\tomega\t[M 2]\tfrequency sample locations (radians)\n% out\n%\ty\t[M 2]\tfilter\n% Copyright 2001-1, Jeff Fessler, The University of Michigan\n% Extend to fan-beam geometry, 2003-11, Yingying Zhang\n\n%\n% effect of image-domain shift\n%\ny = exp(1i * (omega * ob.nxy_shift(:)));\n\n%\n% effect of image basis function (extension to non-rect by S. Matej)\n% basis: b(x/Dx,y/Dy) <-FT-> Dx*Dy * B(Dx*u,Dy*v)\n%\ny = y .* (ob.dx).^2;\n\nif isempty(ob.basis.type) | streq(ob.basis.type, 'pixel')\n\t% sinc_2 due to square pixels\n\tif ob.chat, printf('pixel basis, dx=%g', ob.dx), end\n\ty = y .* sinc(omega(:,1)/(2*pi)) .* sinc(omega(:,2)/(2*pi));\n\nelseif streq(ob.basis.type, 'no')\n\tif ob.chat, printf('no image basis modeled'), end\n\nelseif streq(ob.basis.type, 'KB')\n\tif ob.chat, printf('KB basis: J=%g, alpha=%g, m=%g, n=%g', ...\n\t\tob.basis.diam, ob.basis.shape, ob.basis.m, ob.basis.dim); end\n\tnorm = kaiser_bessel_ft(0, ...\n\t\tob.basis.diam, ob.basis.shape, ob.basis.m, ob.basis.dim);\n\tnd = sqrt(omega(:,1)/(2*pi) .* omega(:,1)/(2*pi) + ...\n\t\tomega(:,2)/(2*pi) .* omega(:,2)/(2*pi));\n\ty = y .* kaiser_bessel_ft(nd, ...\n\t\tob.basis.diam, ob.basis.shape, ob.basis.m, ob.basis.dim) / norm;\n\nelseif streq(ob.basis.type, 'Gauss')\n\terror('Gaussian basis not yet implemented')\n\nelse\n\terror(sprintf('basis function %s not implemented', ob.basis.type))\nend\n\n\n% form into sinogram shape\nK = ob.Krho;\ny = reshape(y, K, ob.na);\n\n%\n% detector radial response resolution-loss effect in frequency domain\n% extension to parallel-beam non-rect case by S. Matej\n%\n\nkk = [-K/2 : K/2-1]';\nif isempty(ob.beam.type) | streq(ob.beam.type, 'rect')\n\n\t% Trick: in fan-beam, the detector blur is not shift-invariant.\n\t% We approximate by the blur at the center of object.\n\t% The effective strip_width / ds at the center is the same.\n\n\tstrip_ray = ob.strip_width / ob.ds;\n\tblur = sinc(strip_ray * kk / K);\n\tif ob.chat\n\t\tprintf('strip integrals, relative beam width=%g', strip_ray)\n\tend\n\nelseif streq(ob.beam.type, 'line')\n\tblur = ones(size(kk));\n\tif ob.chat, printf('line integrals modeled'), end\n\nelseif streq(ob.beam.type, 'KB')\n\tif ob.chat, printf('KB beam shape: J=%g, alpha=%g, m=%g', ...\n\t\tob.beam.diam, ob.beam.shape, ob.beam.m), end\n\trel_bdiam = ob.beam.diam;\t% KB_diameter relative to ob.ds\n\tnorm = kaiser_bessel_ft(0, rel_bdiam, ob.beam.shape, ob.beam.m, 1);\n\tblur = kaiser_bessel_ft(...\n\t\tkk/K, rel_bdiam, ob.beam.shape, ob.beam.m, 1) / norm;\n\nelseif streq(ob.beam.type, 'Gauss')\n\tg_sigma = ob.beam.shape / sqrt(8*log(2));\n\tblur = exp(-(2*pi*kk/K).^2 .* g_sigma^2/2);\n\nelse\n\terror(sprintf('beam shape %s not implemented', ob.beam.type))\n\nend\n\ny = y .* repmat(blur, [1 ob.na]);\t% include blur effect\n\n%\n% phase \"shift\" to effect a half-pixel shift in each row\n% corresponding to \"offset=0\" in tomographic projection.\n% build in the post-fft shift too while at it.\n%\n%if streq(ob.geometry, 'par') % do we need this in fan-beam ???\nif do_phase % do we need this in fan-beam ???\n\tphase = exp(1i*2*pi*(K+ob.is.shift0)/2 * kk / K);\n\ty = y .* repmat(phase, [1 ob.na]);\n\ty = y ./ ob.ds;\t% see JF tech. report\nend\n\n% trick: for parallel case, build in the phase shift due to offset_s\n% added 2005-8-24 since it had been omitted previously\nif ~ob.is.fan\n\tphase = exp(-2i*pi * ob.offset_s * kk / K);\n\ty = y .* repmat(phase, [1 ob.na]);\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/systems/arch/Gtomo_nufft_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6237447444911441}} {"text": "function c = mvn_vbcost(x,L,mu,L_mu,L_K,logdet_K)\nwarning('This function is deprecated')\n\n% c = mvnvbcost(x,Covx,mu,Covmu,pCholCov,pLogDetCov)\n%\n% Calculates c = -KL(q||p) = - \n% where the expectation <.> is taken over q(X). This is used for\n% calculating the lower bound of the marginal loglikelihood in VB\n% models.\n%\n% p(X) = N(M,K)\n% q(X) = N(x,Covx)\n% \n% Rest of the parameters are defined as:\n% q(M) = N(mu,Covmu)\n% = inv(L_K * L_K')\n% = logdet_K\n%\n% If Covx==[], then the term is not calculated.\n% This is useful when X is, e.g., observations.\n\n\nc = 0;\nd = length(x);\n\n% Cost from q-posterior\nif ~isempty(L)\n c = mnorm_entropy(L);\nelse\n L = 0;\nend\n\n% Use Cholesky of the prior covariance\nz = solve_tril(L_K, x-mu);\n\n% Cost from prior\n\n% Below: (x-mu)' * Cov^(-1) * (x-mu) + trace(Cov^(-1)*(Covx+Covmu))\nV = linsolve_chol(L_K, L*L'+L_mu*L_mu')\nerr2 = z'*z + trace(V, V); % TODO: Optimize!\n% $$$ err2 = z'*z + trace(solve_triu(pCholCov',solve_tril(pCholCov,Covx+Covmu)));\nc = c - 0.5*logdet_K - 0.5*err2 - 0.5*d*log(2*pi);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/deprecated/mvn_vbcost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6237447332304851}} {"text": "function [varargout]=rhombicDodecahedronMesh(varargin)\n\n% function [E,V,C,F,CF,CFF]=rhombicDodecahedronMesh(r,nCopies)\n% ------------------------------------------------------------------------\n% Creates a rhombic dodecahedron mesh where r sets the radias and nCopies\n% (a 1x3 vector) sets the number of copies in the x, y, and z direction.\n% The output consists of:\n%\n% Fc_Q, Fc_T: the quadrilateral and triangular face cell arrays (1 cell\n% entry per element).\n%\n% Ft_Q, Ft,T: the quadrilateral and triangular face arrays\n%\n% Ct_Q, Ct,T: color/label data for the face arrays\n%\n% Vt: the vertex array\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 2019/02/08 Created\n% 2019/10/13 Changed orientation for gridding to create more regular grid\n% ------------------------------------------------------------------------\n\n%% Parse input\n\nswitch nargin\n case 1\n r=varargin{1};\n nCopies=2;\n case 2\n r=varargin{1};\n nCopies=varargin{2};\nend\n\nif isempty(nCopies)\n nCopies=2;\nend\n\nif numel(nCopies)==1\n nCopies=nCopies*ones(1,3);\nend\n\n%%\n\n% Get single rhombic dodecahedron\n[~,Vs]=rhombicDodecahedron(r);\nV_offsets=2*r*eye(3,3); %Offset vectors\n\n% Copy over rhombic dodecahedron in grid like fashion 4 times and shift\n% some of the copies to nest them together. \nnCopies1=nCopies;\n[Vg1]=gridClone(Vs,nCopies1,V_offsets);\n\nnCopies2=nCopies;\nnCopies2([1,2])=nCopies2([1,2])-1;\n[Vg2]=gridClone(Vs,nCopies2,V_offsets);\n\nnCopies3=nCopies;\nnCopies3([1,3])=nCopies3([1,3])-1;\n[Vg3]=gridClone(Vs,nCopies3,V_offsets);\n\nnCopies4=nCopies;\nnCopies4([2,3])=nCopies4([2,3])-1;\n[Vg4]=gridClone(Vs,nCopies4,V_offsets);\n\n%%\n\nVg2(:,1)=Vg2(:,1)+r;\nVg2(:,2)=Vg2(:,2)+r;\n\nVg3(:,1)=Vg3(:,1)+r;\nVg3(:,3)=Vg3(:,3)+r;\n\nVg4(:,2)=Vg4(:,2)+r;\nVg4(:,3)=Vg4(:,3)+r;\n\nV=[Vg1;Vg2;Vg3;Vg4];\n\n%% Create element and face arrays\nE=reshape((1:1:size(V,1)),14,size(V,1)/14)';\nC=(1:1:size(E,1))'; %Element colors\n[F,CF,CFF]=element2patch(E,C);\n\n%% Merging point and fix element and face indices\n[F,V,~,indFix]=mergeVertices(F,V);\nE=indFix(E);\n\n%% Collect output\nvarargout{1}=E;\nvarargout{2}=V;\nvarargout{3}=C;\nvarargout{4}=F;\nvarargout{5}=CF;\nvarargout{6}=CFF;\n\nend\n\n%%\n\nfunction [Vg]=gridClone(Vs,nCopies,V_offsets)\n\nnTotal=prod(nCopies); %Total number of copies\nindC=ones(size(Vs,1),1)*(1:1:nTotal);\nindC=indC(:);\n[I,J,K] = ind2sub(nCopies,indC);\nI=I-1; J=J-1; K=K-1;\n\n%Defining offsets\nD1=I*V_offsets(1,:);\nD2=J*V_offsets(2,:);\nD3=K*V_offsets(3,:);\n\n%Defining vertices matrix\nVg=repmat(Vs,nTotal,1)+(D1+D2+D3);\n\nend\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/rhombicDodecahedronMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6237014288385554}} {"text": "function value = scasum ( n, x, incx )\n\n%*****************************************************************************80\n%\n%% SCASUM takes the sum of the absolute values of a complex vector.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for FORTRAN usage,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 3, pages 308-323, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, complex X(*), the vector.\n%\n% Input, integer INCX, the increment between successive entries of X.\n%\n% Output, real VALUE, the sum of the absolute values.\n%\n value = sum ( abs ( real ( x(1:incx:1+(n-1)*incx) ) ) ...\n + abs ( imag ( x(1:incx:1+(n-1)*incx) ) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_c/scasum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6237014245976393}} {"text": "%% DML Toolbox Functions\n%\n% * - multivariate analysis class\n% * - Bayesian logistic regression\n% * - bootstrapping to determine parameter relevance\n% * - circular regression method\n% * - template matching correlation based classifier\n% * - crossvalidation class\n% * - efficient elastic net algorithm\n% * - filtering approach to feature selection\n% * - variational garrote\n% * - Gaussian process\n% * - native implementation of graphnet algorithm\n% * - grid search method\n% * - Hidden Markov model with continuous observations\n% * - linear dynamical system\n% * - abstract class for multivariate methods\n% * - gaussian naive Bayes classifier\n% * - wrapper class to make methods handle multiple datas\n% * - wrapper class to make methods handle multiple outpu\n% * - one-against-one binary classification\n% * - one-against-rest binary classification\n% * - permutation testing class\n% * - used to created smoothing and shrinkage priors\n% * - searchlight analysis\n% * - circular regression by decomposing into sine and co\n% * - shrinkage linear discriminant analysis\n% * - sparse orthonormalized partial least squares\n% * - takes zscores\n% * - test statistics\n% * - support vector machine\n% * - whitens the data\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/html/funct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6237014245976392}} {"text": "function hermite_polynomial_test15 ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_POLYNOMIAL_TEST15 tests HE_POLYNOMIAL_COEFFICIENTS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n n = 10;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_POLYNOMIAL_TEST15\\n' );\n fprintf ( 1, ' HE_POLYNOMIAL_COEFFICIENTS determines the probabilist''s Hermite \\n' );\n fprintf ( 1, ' polynomial coefficients.\\n' );\n\n c = he_polynomial_coefficients ( n );\n \n for i = 0 : n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' He(%d) = \\n', i );\n fprintf ( 1, '\\n' );\n for j = i : -1 : 0\n if ( c(i+1,j+1) == 0.0 )\n\n elseif ( j == 0 )\n fprintf ( 1, ' %f\\n', c(i+1,j+1) );\n elseif ( j == 1 )\n fprintf ( 1, ' %f * x\\n', c(i+1,j+1) );\n else\n fprintf ( 1, ' %f * x^%d\\n', c(i+1,j+1), j );\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_polynomial/hermite_polynomial_test15.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6237014103272434}} {"text": "function eta = conftim1(a, om, omr, omt, h)\n% calculate the conformal time today for a universe with a cosmological constant\n% oml = ratio of dark energy and matter = ohm_l/ohm_m\n%\n% D Vangheluwe 2 oct 2004\n% modified for curvature of space with extra variable : omt (dd 31 mrt 2005)\n\nglobal GL_cmb_c GL_cmb_h0;\n\n% velocity of light in m/s\n%c = 2.998e8;\nc = GL_cmb_c;\n% the hubble constant at present in h Mpc^-1, see my notes p71\n%h0 = 1e5/c;\nh0 = GL_cmb_h0;\n\neta = 1 ./ (h0 * h * sqrt(omr + om * a + (omt - omr - om) * a.^4 + (1 - omt) * a.^2));\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8491-cmbaccur/conftim1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.6236515832274097}} {"text": "% Calculate gridness score for an autocorrelogram\n%\n% Calculates a gridness score by expanding a circle around the centre field and\n% calculating a correlation value of the expanded circle with it's rotated versions.\n% The expansion is done up until the smallest side of the autocorrelogram.\n% Can also calculate grid statistics.\n%\n% Gridness score value by itslef is calculated as a maximum over sliding mean\n% of expanded circles. The widtg of the sliding window is given by variable\n% numGridnessRadii. This is done in order to keep the values the same with\n% historical development of gridness score.\n%\n% NB! The function assumes that the provided input is indeed an autocorrelgoram.\n% This means that the center pixel must have the maximum value. This must be true\n% for both square and rectangular autocorrelogram. This will be important if you\n% manually create square matrix from a rectangular one. Imagine you have a rectangular\n% matrix aCorr of size 309x305, aCorr(155, 153) == 1. If you make it rectangular\n% like this `aSquare = aCorr(1:305, :);`, then the centre pixel will not have\n% the highest values, i.e. `aSquare(153, 153) ~= 1`. You should do it like this\n% `aSquare = aCorr(3:309-2, :)`, then `aSquare(153, 153)` yields `1`.\n%\n% USAGE\n% [score, ] = analyses.gridnessScore(aCorr, )\n% aCorr A 2D autocorrelogram. aCorr can be square or rectangular. See the note (NB) above!\n% Optional list of property-value pairs (see table below)\n%\n% ==============================================================================================\n% Properties Values\n% ----------------------------------------------------------------------------------------------\n% 'minOrientation' Value of minimal difference of inner fields orientation (in degrees). If\n% there are fields that differ in orientation for less than minOrientation,\n% then only the closest to the centre field are left. Default value is 15.\n% 'debug' True or False. If set to True, the function produces some debug output.\n% ==============================================================================================\n% score Gridness score. Ranges from -2 to 2. 2 is more a theoretical bound for a perfect grid.\n% More practical value is around 1.3.\n% stats If this variable is requested, then it is a structure with the following statistics:\n% spacing 3-element vector with distances from the centre field to neighbour fields.\n% orientation 3-element vector with orientations between the centre field and neighbour fields.\n% ellipse Ellipse fitted to the grid. Contains the centre, radii and orientation in\n% radians, stored as [Cx, Cy, Rx, Ry, theta].\n% ellipseTheta Radius of the ellipse in degrees wrapped in range [0..180].\n%\nfunction [gscore, varargout] = gridnessScore(aCorr, varargin)\n nout = max(nargout, 1) - 1;\n inp = inputParser;\n defaultMinOrientation = 15;\n gridStat.orientation = [];\n gridStat.spacing = [];\n gridStat.ellipse = [];\n gridStat.ellipseTheta = nan;\n\n % input argument check functions\n checkDScalar = @(x) helpers.isdscalar(x, '>0');\n\n % fill input parser object\n addRequired(inp, 'aCorr');\n addParameter(inp, 'minOrientation', defaultMinOrientation, checkDScalar);\n addParameter(inp, 'debug', false);\n\n parse(inp, aCorr, varargin{:});\n\n % get parsed arguments\n minOrientation = inp.Results.minOrientation;\n isDebug = inp.Results.debug;\n\n halfSize = ceil(size(aCorr)/2);\n half_height = halfSize(1);\n half_width = halfSize(2);\n aCorrRad = min(halfSize);\n aCorrSize = size(aCorr);\n\n if aCorrSize(1) == 1 || aCorrSize(2) == 1\n gscore = nan;\n if nout > 0\n varargout{1} = gridStat;\n varargout{2} = 0;\n varargout{3} = nan(6, 2);\n varargout{4} = 0;\n end\n return;\n end\n\n % contourc is efficient if aCorr is normalized\n maxValue = max(max(aCorr));\n if maxValue ~= 1\n aCorr = aCorr / maxValue;\n end\n\n cFieldRadius = findCentreRadius(aCorr, half_width, half_height);\n if isDebug\n fprintf('Center radius is %f\\n', cFieldRadius);\n end\n if cFieldRadius == 0 || cFieldRadius == 1 || cFieldRadius == -1 || cFieldRadius >=min(halfSize)\n gscore = nan;\n if nout > 0\n varargout{1} = gridStat;\n varargout{2} = 0;\n varargout{3} = nan(6, 2);\n varargout{4} = 0;\n end\n return;\n end\n\n % Meshgrid for expanding circle\n [rr, cc] = meshgrid(1:size(aCorr, 2), 1:size(aCorr, 1));\n\n % Define iteration radius step size for the gridness score\n% if cFieldRadius>=aCorrRad % modified by Weijian Zong,20201012\n% cFieldRadius=aCorrRad; % modified by Weijian Zong,20201012\n% else% modified by Weijian Zong,20201012\n% end % modified by Weijian Zong,20201012\n radSteps = cFieldRadius:aCorrRad;\n radSteps(1) = [];\n numSteps = length(radSteps);\n\n GNS = zeros(numSteps, 2);\n rotCorr = zeros(1, 5);\n rotAngles_deg = 30*(1:5);\n\n % aCorr is rotated outside the loop for speed\n rotatedCorr = cell(1, length(rotAngles_deg));\n for i = 1:length(rotAngles_deg)\n rotatedCorr{i} = imrotate(aCorr, rotAngles_deg(i), 'bilinear', 'crop');\n end\n\n mainCircle = sqrt((cc - half_height).^2 + (rr - half_width).^2);\n innerCircle = mainCircle > cFieldRadius;\n\n % Define expanding ring of autocorrellogram and do x30 correlations\n for i = 1:numSteps\n ind = (innerCircle & (mainCircle < radSteps(i)));\n tempCorr = reshape(aCorr(ind), 1, [])';\n for j = 1:5\n rotatedCircle = reshape(rotatedCorr{j}(ind), 1, [])';\n rotCorr(j) = corr(tempCorr, rotatedCircle);\n if isDebug\n fprintf('Step %u, angle %u, corr value %f\\n', i-1, rotAngles_deg(j), rotCorr(j));\n end\n end\n GNS(i, 1) = min(rotCorr([2, 4])) - max(rotCorr([1, 3, 5]));\n GNS(i, 2) = radSteps(i);\n end\n\n % Find the biggest gridness score and radius\n [~, gscoreLoc] = max(GNS(:, 1));\n % See function help about numGridnessRadii\n numGridnessRadii = 3;\n numStep = numSteps - numGridnessRadii;\n if numStep < 1\n numStep = 1;\n end\n\n if numStep == 1\n gscore = nanmean(GNS(:, 1));\n else\n meanGridnessArray = zeros(numStep, 1);\n for ii = 1:numStep\n meanGridnessArray(ii) = nanmean(GNS(ii:ii + numGridnessRadii-1, 1));\n end\n\n [gscore, gInd] = max(meanGridnessArray);\n gscoreLoc = gInd + (numGridnessRadii-1)/2;\n end\n\n varargout{4} = radSteps(gscoreLoc);\n\n % Return if we do not need to calculate grid statistics\n if nout < 1\n return;\n end\n\n %% Calculate gridness score statistics\n bestCorr = (mainCircle < radSteps(gscoreLoc) * 1.25) .* aCorr;\n regionalMaxMap = imregionalmax(bestCorr, 4);\n se = strel('square', 3);\n im2 = imdilate(regionalMaxMap, se); % dilate map to eliminate fragmentation\n cc = bwconncomp(im2, 8);\n stats = regionprops(cc, 'Centroid');\n\n if length(stats) < 5\n warning('BNT:numFields', 'Not enough inner fields has been found. Can''t calculate grid properties');\n\n varargout{1} = gridStat;\n varargout{2} = cFieldRadius;\n varargout{3} = nan(6, 2);\n varargout{4} = radSteps(gscoreLoc);\n return;\n end\n\n allCoords = [stats(:).Centroid];\n centresOfMass(:, 1) = allCoords(1:2:end);\n centresOfMass(:, 2) = allCoords(2:2:end);\n\n % Calculate orientation for each field relative to the centre field\n orientation = (atan2(centresOfMass(:, 2) - half_height, centresOfMass(:, 1) - half_width)); % atan2(Y, X)\n peaksToCentre = sqDistance(centresOfMass', [half_width half_height]');\n zeroInd = find(orientation == 0, 1);\n orientation(zeroInd) = []; % remove zero value, so that we do not have a side effect with minOrientation\n stats(zeroInd) = [];\n peaksToCentre(zeroInd) = [];\n centresOfMass(zeroInd, :) = [];\n\n % filter fields that have similar orientation\n orientDistSq = CircStat2012a.circ_dist2(orientation);\n closeFields = abs(orientDistSq) < deg2rad(minOrientation);\n [rows, cols] = size(closeFields);\n closeFields(1:(rows+1):rows*cols) = 0; % assign zero to diagonal elements\n closeFields(tril(true(rows))) = 0; % assign zero to lower triangular of a matrix. Matrix is\n % symmetric and we do not need these values.\n [rows, cols] = find(closeFields); % find non-empty elements, they correspond to indices of close fields\n if ~isempty(rows)\n indToDelete = zeros(1, length(rows));\n for i = 1:length(rows)\n % fieldPeaks = [fields([rows(i) cols(i)]).peakX; fields([rows(i) cols(i)]).peakY];\n % peaksToCentre = sqDistance(fieldPeaks, [half_width; half_height]);\n if peaksToCentre(rows(i)) > peaksToCentre(cols(i))\n indToDelete(i) = rows(i);\n else\n indToDelete(i) = cols(i);\n end\n end\n indToDelete = unique(indToDelete);\n stats(indToDelete) = [];\n peaksToCentre(indToDelete) = [];\n\n if length(stats) < 4\n warning('BNT:numFields', 'Not enough inner fields has been found. Can''t calculate grid properties');\n\n varargout{1} = gridStat;\n varargout{2} = cFieldRadius;\n varargout{3} = nan(6, 2);\n varargout{4} = radSteps(gscoreLoc);\n return;\n end\n\n allCoords = [stats(:).Centroid];\n clear centresOfMass;\n centresOfMass(:, 1) = allCoords(1:2:end);\n centresOfMass(:, 2) = allCoords(2:2:end);\n end\n\n % % get fields peak coordinates\n % fieldPeaks = zeros(length(stats), 2);\n % for i = 1:length(stats)\n % [~, maxInd] = max(bestCorr(stats(i).PixelIdxList));\n % fieldPeaks(i, :) = stats(i).PixelList(maxInd, :);\n % end\n % % fieldPeaks = [fields(:).peakX; fields(:).peakY]'; %\n% peaksToCentre = sqDistance(centresOfMass', [half_width half_height]');\n [~, sortInd] = sort(peaksToCentre);\n stats = stats(sortInd);\n centresOfMass = centresOfMass(sortInd, :);\n\n % leave only 6 closest neighbours (if available)\n if length(stats) > 5\n% stats = stats(1:6);\n centresOfMass = centresOfMass(1:6, :);\n else\n% stats = stats(1:end);\n centresOfMass = centresOfMass(1:end, :);\n end\n\n % centresOfMass = [fields(:).x; fields(:).y]';\n % Calculate orientation for each field relative to the centre field\n orientation = rad2deg(atan2(centresOfMass(:, 2) - half_height, centresOfMass(:, 1) - half_width)); % atan2(Y, X)\n\n % Calculate distances between centre of masses for each field and the centre field\n spacing = sqrt((centresOfMass(:, 1) - half_width).^2 + (centresOfMass(:, 2) - half_height).^2);\n\n% % Plot grid polygon points\n% figure, plot.colorMap(bestCorr), hold on;\n% plot(centresOfMass(:, 1), centresOfMass(:, 2), '+k', 'markersize', 8);\n\n ell = general.fitEllipse(centresOfMass(:, 1), centresOfMass(:, 2));\n ellipseTheta = rad2deg(general.wrap(ell(end)) + pi);\n% drawEllipse(ell, 'linewidth', 2, 'color', [1 1 1]);\n\n % Determine axes orientation, spacing and deviation\n [~, bBC] = sort(abs(orientation));\n [~, bBC2] = sort(abs(orientation - orientation(bBC(1))));\n\n % leave only three values, because autocorrelogram is symmetric\n orientation = orientation(bBC2(1:3));\n spacing = spacing(bBC2(1:3));\n [orientation, orientSortInd] = sort(orientation);\n\n spacing = spacing(orientSortInd);\n\n gridStat.orientation = orientation;\n gridStat.spacing = spacing;\n gridStat.ellipse = ell;\n gridStat.ellipseTheta = ellipseTheta;\n\n varargout{1} = gridStat;\n varargout{2} = cFieldRadius;\n varargout{3} = centresOfMass;\n varargout{4} = radSteps(gscoreLoc);\nend\n\nfunction D = sqDistance(X, Y)\n D = bsxfun(@plus,dot(X,X,1)',dot(Y,Y,1))-2*(X'*Y);\nend\n\nfunction cFieldRadius = findCentreRadius(aCorr, half_width, half_height)\n cFieldRadius = 0;\n\n % Search for fields only around the centre\n peakCoords = [half_width, half_height];\n [~, fields] = SpatialTuning_BNT.placefieldAdaptive(aCorr, 'minPeak', 0, 'minBins', 2, ...\n 'peakCoords', peakCoords);\n if isempty(fields)\n return;\n end\n\n peakLoc = [fields(:).peakX; fields(:).peakY]';\n\n % get all distances and check two minimums of them\n allDistances = sqDistance(peakLoc', [half_width half_height]'); % point should be in format [x y]\n [~, sortIndices] = sort(allDistances);\n if length(sortIndices) >= 2\n % this is a bit leagacy code. By using peakCoords with placefieldAdaptive, we\n % should always get just a single field. Keeping it as I did not test the version without it properly.\n twoMinIndices = sortIndices(1:2);\n\n if abs(allDistances(twoMinIndices(1)) - allDistances(twoMinIndices(2))) < 2\n % two fields with close middle points. Let's select one with minimum square\n [~, minInd] = min([fields(twoMinIndices).area]);\n closestFieldInd = twoMinIndices(minInd);\n else\n closestFieldInd = twoMinIndices(1); % get the first minimum\n end\n else\n closestFieldInd = sortIndices(1);\n end\n cFieldRadius = floor(sqrt(fields(closestFieldInd).area / pi));\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/+SpatialTuning_BNT/gridnessScore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6235933833869418}} {"text": "function [beta,Mu_c,Sigma_y_tmp] = GMC(Priors, Mu, Sigma, x, in, out)\n%GMC Gaussian Mixture Conditional. Returns the conditional P(out|in=x) of\n% the Gaussian Mixture Model P(out,in) at the point in=x.\n%\n%\n%\n% Inputs -----------------------------------------------------------------\n% o Priors: 1 x K array representing the prior probabilities of the K GMM\n% components.\n% o Mu: D x K array representing the centers of the K GMM components.\n% o Sigma: D x D x K array representing the covariance matrices of the\n% K GMM components.\n% o x: P x N array representing N datapoints of P dimensions.\n% o in: 1 x P array representing the dimensions to consider as\n% inputs.\n% o out: 1 x Q array representing the dimensions to consider as\n% outputs (D=P+Q)\n%\n% Output------------------------------------------------------------------------\n%\n% o beta : N x K\n%\n% o Mu_c : Q x N x K\n%\n% o Sigma_c : Q x Q x K\n%\n%\n%\n\nnbData = size(x,2);\nnbVar = size(Mu,1);\nnbStates = size(Sigma,3);\n\n%% Compute the influence of each GMM component, given input x\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor i=1:nbStates\n% if i == 1\n% Mu(in,i)\n% Sigma(in,in,i)\n% inv(Sigma(in,in,i))\n% det(Sigma(in,in,i))\n% gaussPDF(x, Mu(in,i), Sigma(in,in,i))\n% end\n Pxi(:,i) = Priors(i).*gaussPDF(x, Mu(in,i), Sigma(in,in,i));\nend\nbeta = Pxi./repmat(sum(Pxi,2)+realmin,1,nbStates);\n\n%% Compute expected means y, given input x\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor j=1:nbStates\n % (N x D x K)\n % (D x N) (D x D) (D x N)\n Mu_c(:,:,j) = (repmat(Mu(out,j),1,nbData) + Sigma(out,in,j)*inv(Sigma(in,in,j)) * (x-repmat(Mu(in,j),1,nbData)))';\n % Mu_c(:,:,j) = (repmat(Mu(out,j),1,nbData))';\n\nend\n\n%% Compute Marginal covariance matrices Sigma_y\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor j=1:nbStates\n Sigma_y_tmp(:,:,j) = Sigma(out,out,j) - (Sigma(out,in,j)*inv(Sigma(in,in,j))*Sigma(in,out,j));\n Sigma_y_tmp(:,:,j) = 0.5 * (Sigma_y_tmp(:,:,j) + Sigma_y_tmp(:,:,j)');\nend\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/gmmbox/GMMfunctions/GMM-GMR-v2.0/GMC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6234957328803432}} {"text": "function [pdf,X1,X2]=akde(X,grid,gam)\n%% adaptive kernel density estimation in high dimensions;\n% optimal accuracy/speed tradeoff, controlled via parameter \"gam\";\n% INPUTS: X - data as a 'n' by 'd' vector;\n%\n% grid - 'm' points of dimension 'd' over which pdf is computed;\n% default provided only for 2-dimensional data;\n% see example on how to construct it in higher dimensions\n%\n% gam - cost/accuracy tradeoff parameter, where gam200), break, end\nend\n% now output density values at grid\npdf = probfun(mesh,w,mu,Sig)/prod(scaling); % evaluate density\ndel=del*scaling; % adjust bandwidth for scaling\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction pdf=probfun(x,w,mu,Sig)\n[gam,d]=size(mu);\npdf=0;\nfor k=1:gam\n L=chol(Sig(:,:,k));s=diag(L);\n logpdf=-.5*sum(( bsxfun(@minus,x,mu(k,:))/L).^2,2)+log(w(k))...\n -sum(log(s))-d*log(2*pi)/2;\n pdf=pdf+exp(logpdf);\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [w,mu,Sig,del,ent]=regEM(w,mu,Sig,del,X)\n[gam,d]=size(mu);[n,d]=size(X);\nlog_lh=zeros(n,gam); log_sig=log_lh; \nfor i=1:gam\n L=chol(Sig(:,:,i));\n Xcentered = bsxfun(@minus, X, mu(i,:));\n xRinv = Xcentered /L; xSig = sum((xRinv /L').^2,2)+eps;\n log_lh(:,i)=-.5*sum(xRinv.^2, 2)-sum(log(diag(L)))...\n +log(w(i))-d*log(2*pi)/2-.5*del^2*trace((eye(d)/L)/L');\n log_sig(:,i)=log_lh(:,i)+log(xSig);\nend\nmaxll = max (log_lh,[],2); maxlsig = max (log_sig,[],2);\np= exp(bsxfun(@minus, log_lh, maxll));\npsig=exp(bsxfun(@minus, log_sig, maxlsig));\ndensity = sum(p,2); psigd=sum(psig,2);\nlogpdf=log(density)+maxll; logpsigd=log(psigd)+maxlsig;\np = bsxfun(@rdivide, p, density);\nent=sum(logpdf); w=sum(p,1);\nfor i=find(w>0)\n mu(i,:)=p(:,i)'*X/w(i); %compute mu's\n Xcentered = bsxfun(@minus, X,mu(i,:));\n Xcentered = bsxfun(@times,sqrt(p(:,i)),Xcentered);\n Sig(:,:,i)=Xcentered'*Xcentered/w(i)+del^2*eye(d); % compute sigmas;\nend\nw=w/sum(w);curv=mean(exp(logpsigd-logpdf)); % estimate curvature\ndel=1/(4*n*(4*pi)^(d/2)*curv)^(1/(d+2));\nend\n\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/algorithm/akde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6233868483878812}} {"text": "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ldlup.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function [L,d,p]=ldlup(L,d,j,g)\n% updates LDL^T factorization when a unit j-th row and column\n% are replaced by column g \n% if the new matrix is definite (signalled by p=[]);\n% otherwise, the original L,d and \n% a direction p of null or negative curvature are returned\n%\n% d contains diag(D) and is assumed positive\n% Note that g must have zeros in other unit rows!!!\n%\nfunction [L,d,p]=ldlup(L,d,j,g);\n\np=[];\n\ntest=0;\nif test, \n disp('enter ldlup')\n A=L*diag(d)*L';A(:,j)=g;A(j,:)=g'; \nend;\n\nn=size(d,1);\nI=1:j-1;K=j+1:n;\nif j==1,\n v=zeros(0,1);\n del=g(j);\n if del<=n*eps, \n p=[1;zeros(n-1,1)]; \n if test, \n A,p\n Nenner=abs(p)'*abs(A)*abs(p);\n if Nenner==0, indef1=0 ,else indef1=(p'*A*p)/Nenner, end;\n disp('leave ldlup at 1')\n end;\n return; \n end;\n w=g(K)/del;\n L(j,I)=v';\n d(j)=del;\n if test, \n A1=L*diag(d)*L',A \n quot=norm(A1-A,1)/norm(A,1), \n disp('leave ldlup at 3')\n end;\n return; \nend;\n\n% now j>1, K nonempty\nLII=L(I,I);\nu=LII\\g(I);\nv=u./d(I);\ndel=g(j)-u'*v;\nif del<=n*eps,\n p=[LII'\\v;-1;zeros(n-j,1)];\n if test, \n A,p\n indef1=(p'*A*p)/(abs(p)'*abs(A)*abs(p))\n disp('leave ldlup at 2')\n end;\n return;\nend;\nLKI=L(K,I);\nw=(g(K)-LKI*u)/del;\n[LKK,d(K),q]=ldlrk1(L(K,K),d(K),-del,w);\nif isempty(q),\n % work around expensive sparse L(K,K)=LKK\n L=[L(I,:);\n v', 1,L(j,K);\n LKI,w,LKK];\n d(j)=del;\n if test, \n A1=L*diag(d)*L',A \n quot=norm(A1-A,1)/norm(A,1), \n disp('leave ldlup at 4')\n end;\nelse\n % work around expensive sparse L(K,K)=LKK\n L=[L(1:j,:);\n LKI,L(K,j),LKK];\n pi=w'*q;\n p=[LII'\\(pi*v-LKI'*q);-pi;q];\n if test, \n indef2=(p'*A*p)/(abs(p)'*abs(A)*abs(p)), \n disp('leave ldlup at 5')\n end;\nend;\n\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/minq5/ldlup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6233868389552311}} {"text": "function path_length = iTreePathLength(x, treenode, current_path_length)\n%UNTITLED7 Summary of this function goes here\n% Detailed explanation goes here\n\n% if strcmp(class(treenode), 'iTreeLeaf')\n% path_length = current_path_length + adjustment(treenode.Size);\n% else\n% if x(treenode.SplitAttribute) < treenode.SplitValue\n% path_length = iTreePathLength(x, treenode.Left, current_path_length+1);\n% else\n% path_length = iTreePathLength(x, treenode.Right, current_path_length+1);\n% end\n% end\n\npath_length = 0;\nwhile ~strcmp(class(treenode), 'iTreeLeaf')\n if x(treenode.SplitAttribute) < treenode.SplitValue\n treenode = treenode.Left;\n else\n treenode = treenode.Right;\n end\n path_length = path_length + 1;\nend\npath_length = path_length + adjustment(treenode.Size);\nend\n\nfunction value=adjustment(n)\n%The average path length of an unsuccessful BST search\n if n<=1\n value = 0;\n else\n value = 2 * (log(n-1)+0.5772156649) - 2*(n-1) / n;\n end\nend", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/others/iForest/iTreePathLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.623386834238906}} {"text": "% [INPUT]\n% eq = A vector of floats [0,Inf) of length k representing the market value of equity.\n% db = A float or a vector of floats [0,Inf) of length k representing the default barrier.\n% r = A float or a vector of floats (-Inf,Inf) of length k representing the annualized risk-free interest rate.\n% t = A float or a vector of floats (0,Inf) of length k representing the time to maturity of default barrier.\n% op = A string representing the option pricing model used by the Systemic CCA framework (optional, default='BSM'):\n% - 'BSM' for Black-Scholes-Merton;\n% - 'GC' for Gram-Charlier.\n%\n% [OUTPUT]\n% va = A column vector of floats of length k representing the value of assets.\n% vap = Output argument representing the distributional parameters of assets whose type depends on the chosen option pricing model:\n% - for Black-Scholes-Merton, a float [0,Inf) representing the annualized volatility of assets;\n% - for Gram-Charlier, a row vector of floats (-Inf,Inf) of length 3 whose values represent respectively the annualized volatility, skewness and excess kurtosis of assets.\n\nfunction [va,vap] = kmv_structural(varargin)\n\n persistent ip;\n\n if (isempty(ip))\n ip = inputParser();\n ip.addRequired('eq',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n ip.addRequired('db',@(x)validateattributes(x,{'double'},{'real' 'finite' 'nonnegative' 'vector' 'nonempty'}));\n ip.addRequired('r',@(x)validateattributes(x,{'double'},{'real' 'finite' 'vector' 'nonempty'}));\n ip.addRequired('t',@(x)validateattributes(x,{'double'},{'real' 'finite' '>' 0 'vector' 'nonempty'}));\n ip.addRequired('op',@(x)any(validatestring(x,{'BSM' 'GC'})));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n [eq,db,r,t] = validate_input(ipr.eq,ipr.db,ipr.r,ipr.t);\n op = ipr.op;\n\n nargoutchk(1,2);\n\n [va,vap] = kmv_structural_internal(eq,db,r,t,op);\n\nend\n\nfunction [va,vap] = kmv_structural_internal(eq,db,r,t,op)\n\n df = exp(-r .* t);\n\n k = numel(r);\n sk = sqrt(k);\n\n va = eq + (db .* df);\n va_r = diff(log(va));\n va_s = sqrt(252) * std(va_r);\n\n sst = va_s .* sqrt(t);\n d1 = (log(va ./ db) + ((r + (0.5 * va_s^2)) .* t)) ./ sst;\n d2 = d1 - sst;\n n1 = normcdf(d1);\n n2 = normcdf(d2);\n\n va_old = va;\n va = eq + ((va .* (1 - n1)) + (db .* df .* n2));\n\n count = 0;\n error = norm(va - va_old) / sk;\n\n while ((count < 10000) && (error > 1e-8))\n sst = va_s .* sqrt(t);\n d1 = (log(va ./ db) + ((r + (0.5 * va_s^2)) .* t)) ./ sst;\n d2 = d1 - sst;\n n1 = normcdf(d1);\n n2 = normcdf(d2);\n\n va_old = va;\n va = eq + ((va .* (1 - n1)) + (db .* df .* n2));\n va_r = diff(log(va));\n va_s = sqrt(252) * std(va_r);\n\n count = count + 1;\n error = norm(va - va_old) / sk;\n end\n\n if (strcmp(op,'BSM'))\n vap = va_s;\n else\n va_g = skewness(va_r,0) / sqrt(252);\n va_k = (kurtosis(va_r,0) - 3) / 252;\n\n vap = [va_s va_g va_k];\n end\n\nend\n\nfunction [eq,db,r,t] = validate_input(eq,db,r,t)\n\n eq = eq(:);\n eq_len = numel(eq);\n\n if (eq_len < 5)\n error('The value of ''eq'' is invalid. Expected input to be a vector containing at least 5 elements.');\n end\n\n data = {db(:) r(:) t(:)};\n\n l = unique(cellfun(@numel,data));\n l_scalar = (l == 1);\n\n if (any(l_scalar))\n if (any(l(~l_scalar) ~= eq_len))\n error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(eq_len) '.']);\n end\n else\n if (any(l ~= eq_len))\n error(['The number of elements of ''db'', ''r'' and ''t'' must be either 1 or equal to ' num2str(eq_len) '.']);\n end\n end\n\n for i = 1:numel(data)\n data_i = data{i};\n\n if (numel(data_i) == 1)\n data{i} = repmat(data_i,eq_len,1);\n end\n end\n\n [db,r,t] = deal(data{:});\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsModels/kmv_structural.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6233318948706391}} {"text": "function coeffs3D = vals2coeffs(F)\n%VALS2COEFFS Convert tensor of values to tensor of coefficients.\n%\n% See also CHEBFUN3/COEFFS2VALS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n[m, n, p] = size(F);\n\n%% Step 1:\n% Mode-1 unfolding of F to get a matrix of size m x n*p:\nF1 = chebfun3.unfold(F, 1); \n\n% Apply 1D \"vals2coeffs\" in the X direction i.e., the 1st dimension of F1:\nF1 = chebtech2.vals2coeffs(F1);\n\n% Tensorize F1 back to its original m x n x p size:\nF1 = chebfun3.fold(F1, [m, n, p], 1, [2 3]); \n% This is simply F1 = reshape(V1, m, n, p);\n\n%% Step 2:\n% Mode-2 unfolding of (the tensorized) F1 to get a matrix of size m x n*p:\nF2 = chebfun3.unfold(F1, 2); \n\n% Apply 1D \"vals2coeffs\" in the Y direction, i.e. to the 1st direction of\n% F2:\nF2 = chebtech2.vals2coeffs(F2);\n\n% Tensorize F2 back to its original m x n x p size:\nF2 = chebfun3.fold(F2, [m, n, p], 2, [1 3]);\n\n%% Step 3:\n% Mode-3 unfolding of (the tensorized) F2 to get a matrix of size p x m*n:\nF3 = chebfun3.unfold(F2, 3);\n\n% Now, vals2coeffs is applied in the Z direction.\nF3 = chebtech2.vals2coeffs(F3);\n\n% Reshape F3 back to the original m x n x p size:\ncoeffs3D = chebfun3.fold(F3, [m, n, p], 3, [1 2]);\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun3/vals2coeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6233233069313197}} {"text": "function [ net,res,opts ] = rmsprop( net,res,opts )\n% Modified RMSProp using second-order information. \n% 1.Tieleman, T. and Hinton, G. Lecture 6.5 - RMSProp, COURSERA: Neural Networks for Machine Learning.\n% Technical report, 2012.\n% 2.Ye, C., Yang, Y., Fermuller, C., & Aloimonos, Y. (2017). \n% On the Importance of Consistency in Training Deep Neural Networks. arXiv preprint arXiv:1708.00631.\n\n if ~isfield(opts.parameters,'second_order')\n opts.parameters.second_order=0;\n end\n if opts.parameters.second_order\n [ net,res,opts ] = gradient_decorrelation( net,res,opts );\n end\n\n if ~isfield(opts.parameters,'weightDecay')\n opts.parameters.weightDecay=1e-4;\n end\n\n \n if ~isfield(opts.parameters,'clip')\n opts.parameters.clip=1e0;\n end\n \n if ~isfield(opts.parameters,'eps')\n opts.parameters.eps=1e-6;\n end\n \n if ~isfield(net,'iterations')||(isfield(opts,'reset_mom')&&opts.reset_mom==1)\n net.iterations=0;\n end\n \n net.iterations=net.iterations+1;\n \n mom_factor=(1-opts.parameters.mom.^net.iterations);\n \n for layer=1:numel(net.layers)\n if isfield(net.layers{layer},'weights')\n if ~isfield(net.layers{layer},'momentum')||(isfield(opts,'reset_mom')&&opts.reset_mom==1)\n net.layers{layer}.momentum{1}=zeros(size(net.layers{layer}.weights{1}),'like',net.layers{layer}.weights{1});\n net.layers{layer}.momentum{2}=zeros(size(net.layers{layer}.weights{2}),'like',net.layers{layer}.weights{2});\n \n end\n \n net.layers{layer}.momentum{1}=opts.parameters.mom.*net.layers{layer}.momentum{1}+(1-opts.parameters.mom).*(res(layer).dzdw.^2);\n normalized_grad=res(layer).dzdw./(net.layers{layer}.momentum{1}.^0.5+opts.parameters.eps)./mom_factor;\n if isfield(opts.parameters,'clip')&&opts.parameters.clip>0\n mask=abs(normalized_grad)>opts.parameters.clip;\n normalized_grad(mask)=sign(normalized_grad(mask)).*opts.parameters.clip;\n end\n net.layers{layer}.weights{1}=net.layers{layer}.weights{1}-opts.parameters.lr*normalized_grad- opts.parameters.weightDecay * net.layers{layer}.weights{1};\n \n net.layers{layer}.momentum{2}=opts.parameters.mom.*net.layers{layer}.momentum{2}+(1-opts.parameters.mom).*(res(layer).dzdb.^2);\n normalized_grad=res(layer).dzdb./(net.layers{layer}.momentum{2}.^0.5+opts.parameters.eps)./mom_factor;\n if isfield(opts.parameters,'clip')&&opts.parameters.clip>0\n mask=abs(normalized_grad)>opts.parameters.clip;\n normalized_grad(mask)=sign(normalized_grad(mask)).*opts.parameters.clip;\n end\n net.layers{layer}.weights{2}=net.layers{layer}.weights{2}-opts.parameters.lr*normalized_grad;\n end\n end\n \n if ~isfield(opts,'reset_mom')||opts.reset_mom==1\n opts.reset_mom=0;\n end\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/optim/rmsprop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6232878823340691}} {"text": "function c = gain_cond_check(model_param, B, psi_1, evmax, c1, c2, kx, kv, kr, kw)\n\nm = model_param.mass;\nJ = model_param.I;\n\nalpha = sqrt(psi_1*(2-psi_1));\nW1 = [ c1*kx/m -c1*kv/(2*m)*(1+alpha);-c1*kv/(2*m)*(1+alpha) kv*(1-alpha)-c1 ];\nW12 = [kx*evmax+c1/m*B 0;B 0];\nW2 = [c2*kr/max(eig(J)) -c2*kw/(2*min(eig(J)));-c2*kw/(2*min(eig(J))) kw-c2];\n\nc = min(eig(W2))-4*norm(W12)^2/min(eig(W1));\n", "meta": {"author": "yorgoon", "repo": "minimum-snap-geometric-control", "sha": "efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac", "save_path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control", "path": "github-repos/MATLAB/yorgoon-minimum-snap-geometric-control/minimum-snap-geometric-control-efbd741223d1b38f5451f3e5ff421cb3dbf7f8ac/gain_tuning/gain_cond_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.6232659577863932}} {"text": "%% Check rate of convergence for 3D Hcurl interface problem\n% curl(A curl u) + B u = f, x\\in \\Omega\n% where A and B are piecewise constants on Omega^+ and Omega^-.\n%\n% Domain: Rectangular domain: [xmin,xmax] X [ymin,ymax] X [zmin,zmax]\n% Mesh: Cartesian triangular mesh.\n% Method: FE\n% for this method, need to mannualy import a mesh data\n\n%% Geometry and Boundary Conditions\n%clear\n%close all\n%clc\n\n%path(pathdef)\naddpath(genpath(pwd),'-begin');\nrmpath(genpath('./.git'));\nrmpath(genpath('./docs'));\nsavepath;\n\ndomain = [-1,1,-1,1,-1,1];\nbc = [1,1,1,1,1,1]; % Dirichelet BC\n\n%% Finite Element Type\nfemtype = '1st kind Nedelec';\ndisp(['FEM Type = Conforming ', femtype]);\n\n%% Initial Partition\nnx0 = 10;\nny0 = nx0;\nnz0 = nx0;\n\n%% Task\nshowErr = 0;\nshowMesh = 0;\ncomputErr = 1;\n\n%% PDE\ntest = 3;\nswitch test\n case 0\n pde = poissonNonPoly3D;\n case 1 % circular interface\n r = pi/5; bm = 1; bp = 1; am = 1; ap = 1;\n x0 = 0; y0 = 0; z0 = 0; a11 = 1; a12 = 1; a = 1;\n pde = elli3DcircIntf2(am,ap,bm,bp,r,x0,y0,z0,a11,a12,a);\n case 2\n r = pi/5; bm = 1; bp = 1;\n x0 = 0; y0 = 0; z0 = 0; coef = 1;\n pde = constant_fun(bm,bp,r,x0,y0,z0,coef);\n case 3\n r = pi/5; bm = 1; bp = 1; am = 1; ap = 1;\n x0 = 0; y0 = 0; z0 = 0; coef = 1;\n pde = linear_fun(am,ap,bm,bp,r,x0,y0,z0,coef);\nend\n\n%% Max Iteration\n\n%% 1. Generate Mesh\ndisp('*******************************************************************************')\ndisp('Import mesh');\nload('BoxTorusMesh.mat')\nmesh = enrichMesh3D(mesh,0); % Mesh detail level = 1 (for IFE).\n\n%% 2. Generate FEM DoF\nfem = genNedFEM3D(mesh,bc);\ndisp(['number of DoF = ', int2str(length(fem.p))]);\n\n%% 3. Assemble Matrix\ndisp(' '); disp('Start Assembling Matrix');\nS = globMatrixNedFit3D(am,ap,1,mesh,fem,fem);\nM = globMatrixNedFit3D(bm,bp,0,mesh,fem,fem);\nrhsF1 = globNedFitRHS3D(pde.fm1,pde.fp1, mesh, fem, 0, 1);\nrhsF2 = globNedFitRHS3D(pde.fm2,pde.fp2, mesh, fem, 0, 2);\nrhsF3 = globNedFitRHS3D(pde.fm3,pde.fp3, mesh, fem, 0, 3);\nrhsF = rhsF1 + rhsF2 + rhsF3;\nAtotal = S + M;\ntu1 = sum(feval(pde.exactu1,fem.gex,fem.gey,fem.gez).*fem.gew,2);\ntu2 = sum(feval(pde.exactu2,fem.gex,fem.gey,fem.gez).*fem.gew,2);\ntu3 = sum(feval(pde.exactu3,fem.gex,fem.gey,fem.gez).*fem.gew,2);\ntgt = mesh.p(mesh.e(:,2),:) - mesh.p(mesh.e(:,1),:);\ntgt = tgt./sum(tgt.^2,2).^(1/2);\ntu = tu1.*tgt(:,1) + tu2.*tgt(:,2) + tu3.*tgt(:,3);\n\nNdof = size(mesh.e,1);\nbdidx = zeros(Ndof,1);\nisBdEdge = true(Ndof,1);\nisBdEdge(fem.mapper) = false;\nbdidx(isBdEdge) = 1;\nTbd = spdiags(bdidx,0,Ndof,Ndof);\nT = spdiags(1-bdidx,0,Ndof,Ndof);\nA = T*Atotal*T + Tbd;\nub = tu;\nub(fem.mapper) = 0;\nrhsB = Atotal*ub;\nf = rhsF - rhsB;\nf(isBdEdge) = tu(isBdEdge);\n\n%% 3. Solve the linear system Au = f\noption.outsolver = 'cg';\ntID1 = (mesh.tLoc == 1);\ntID2 = (mesh.tLoc == 2);\ne1tmp = unique(reshape(mesh.t_e(tID1,:),[],1));\ne2tmp = unique(reshape(mesh.t_e(tID2,:),[],1));\neInt = intersect(e1tmp,e2tmp);\n%eIntp1 = mesh.p(mesh.e(eInt,1),:);\n%eIntp2 = mesh.p(mesh.e(eInt,2),:);\neid1 = setdiff(e1tmp,eInt);\neid2 = setdiff(e2tmp,eInt);\nalpha = am*ones(size(mesh.e,1),1);\nalpha(eid2) = ap;\nalpha(eInt) = (am+ap)/2;\nbeta = bm*ones(size(mesh.e,1),1);\nbeta(eid2) = bp;\nbeta(eInt) = (bm+bp)/2;\noption.alpha = alpha;\noption.beta = beta;\noption.solver = 'amg';\nedge = mesh.e;\noption.isBdEdge = isBdEdge;\noption.smoother = 'BD';\nNEdof = size(A,1);\noption.blklevel = 0;\noption.blkId = NEdof;\noption.fact = 'chol';\n[x,info] = amgMaxwellinterface(A,f,mesh.p,edge,option);\nuh = x;\n\n%% 4. Postprocess: Calculating Errors\ntic\nerrND = max(abs(uh - tu)); % Error on nodes\nerr.nd = errND; err.inf = 0; err.l2 = 0; err.h1 = 0;\nif computErr == 1\n disp(' '); disp('Start computing error in L2 norm');\n eNorm = 'L2'; disp(['Start computing error in ',eNorm,' norm']);\n [errL2,errL2K1,errL2K2,errL2K3] = getCurlErr3D(uh, pde, fem, eNorm);\n \n eNorm = 'Curl'; disp(['Start computing error in ',eNorm,' norm']);\n [errCurl,errCurl1,errCurl2,errCurl3] = getCurlErr3D(uh, pde, fem, eNorm);\n err.l2 = errL2;\n err.curl = errCurl;\nend\ntime(6) = toc;\ntime(7) = 1e6*sum(time(2:6))/length(mesh.t);\n\n%% 5: Output\n\ndisp(' ')\ndisp('Errors')\ndisp('Node L2 norm H1 norm')\nformatSpec = '%6.4e %6.4e %6.4e\\n';\nfprintf(formatSpec, err.nd, err.l2, err.curl)\n\nerr0 = err; h0 = h;\n\ndisp(' '); disp('CPU Time')\ndisp(' N Mesh FEM Matrix Solve Error Time/1M cell')\nformatSpec = '%4i %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\\n';\nfprintf(formatSpec, time)\n\n%% 6. Plot Solution and Error\nif showErr == 1\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/checkNedFEMfitted.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.6231470442820339}} {"text": "function [ x, y, z, w ] = ld0350 ( )\n\n%*****************************************************************************80\n%\n%% LD0350 computes the 350 point Lebedev angular grid.\n%\n% Modified:\n%\n% 14 September 2010\n%\n% Author:\n%\n% Dmitri Laikov\n%\n% Reference:\n%\n% Vyacheslav Lebedev, Dmitri Laikov,\n% A quadrature formula for the sphere of the 131st\n% algebraic order of accuracy,\n% Russian Academy of Sciences Doklady Mathematics,\n% Volume 59, Number 3, 1999, pages 477-481.\n%\n% Parameters:\n%\n% Output, real X(N), Y(N), Z(N), W(N), the coordinates\n% and weights of the points.\n%\n n = 0;\n x = zeros(350,1);\n y = zeros(350,1);\n z = zeros(350,1);\n w = zeros(350,1);\n a = 0.0;\n b = 0.0;\n v = 0.3006796749453936E-02;\n [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n v = 0.3050627745650771E-02;\n [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n a = 0.7068965463912316;\n v = 0.1621104600288991E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.4794682625712025;\n v = 0.3005701484901752E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.1927533154878019;\n v = 0.2990992529653774E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.6930357961327123;\n v = 0.2982170644107595E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.3608302115520091;\n v = 0.2721564237310992E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.6498486161496169;\n v = 0.3033513795811141E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.1932945013230339;\n v = 0.3007949555218533E-02;\n [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n a = 0.3800494919899303;\n v = 0.2881964603055307E-02;\n [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n a = 0.2899558825499574;\n b = 0.7934537856582316;\n v = 0.2958357626535696E-02;\n [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n a = 0.9684121455103957E-01;\n b = 0.8280801506686862;\n v = 0.3036020026407088E-02;\n [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n a = 0.1833434647041659;\n b = 0.9074658265305127;\n v = 0.2832187403926303E-02;\n [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, w );\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_lebedev_rule/ld0350.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6231470391144632}} {"text": "function p = bst_cross(x,y,dim)\n% BST_CROSS: Cross product between two sets, each set with three columns\n% \n% USAGE: p = bst_cross(x,y)\n% p = bst_cross(x,y,dim)\n%\n% INPUT:\n% - x : [1,3] double or single\n% - y : [1,3] double or single\n% - dim : dimension along which to compute the cross product\n%\n% NOTE:\n% - Does exactly then same as the Matlab 'cross' function, but much faster.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n\n% Default: dim=1\nif (nargin < 3) || isempty(dim)\n dim = 1;\nend\n% Check size\nif (size(x,dim)~=3) || (size(y,dim)~=3)\n error(' Must have three columns ');\nend\n% Compute cross product\nif (dim == 2)\n p = [x(:,2).*y(:,3) - x(:,3).*y(:,2),...\n x(:,3).*y(:,1) - x(:,1).*y(:,3),...\n x(:,1).*y(:,2) - x(:,2).*y(:,1)];\nelse\n p = [x(2,:).*y(3,:) - x(3,:).*y(2,:);...\n x(3,:).*y(1,:) - x(1,:).*y(3,:);...\n x(1,:).*y(2,:) - x(2,:).*y(1,:)];\nend\n\n\n \n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_cross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6231470314099071}} {"text": "function [mus,sigmas,R] = restore_from_projection(mus_p,sigmas_p,R_p,c,E)\n% restore from projection.\n% input:\n% mus_p - 1 by M cell array (each cell is a K_j by B matrix)\n% sigmas_p - 1 by M cell array (each cell is a B by B by K_j matrix)\n% R_p - M by d projected data or M by d by N projected data\n% c - 1 by B center of the PCA\n% E - B by d projection matrix\n% output:\n% mus, sigmas, R - restored versions of mus_p, sigmas_p and R_p\n\nif ~isempty(mus_p) && ~isempty(sigmas_p)\n M = length(mus_p);\nelseif ~isempty(R_p)\n M = size(R_p,1);\nend\nmus = cell(1,M);\nsigmas = cell(1,M);\nB = size(E,1);\nR = zeros(M,B);\n\nif ~isempty(mus_p) && ~isempty(sigmas_p)\n for j = 1:M\n K_j = size(mus_p{j},1);\n mus{j} = zeros(K_j,B);\n sigmas{j} = zeros(B,B,K_j);\n\n for k = 1:size(mus_p{j},1)\n % mus{j}(k,:) = solve_linsys_mu(E,mus_p{j}(k,:)')' + c;\n % sigmas{j}(:,:,k) = solve_linsys_sigma(E, sigmas_p{j}(:,:,k));\n mus{j}(k,:) = recover_mu(E,c,mus_p{j}(k,:));\n sigmas{j}(:,:,k) = recover_sigma(E,sigmas_p{j}(:,:,k));\n end\n end\nend\n\nif ~isempty(R_p)\n if ndims(R_p) == 2\n R = recover_mu(E,c,R_p);\n elseif ndims(R_p) == 3\n R = zeros(M,B,size(R_p,3));\n for i = 1:size(R_p,3)\n R(:,:,i) = recover_mu(E,c,R_p(:,:,i));\n end\n end\nend\n\nfunction mu = recover_mu(E,c,mu0)\nmu = E*mu0' + repmat(c',[1, size(mu0,1)]);\nmu = mu';\n\nfunction sigma = recover_sigma(E, sigma0)\nsigma = E*sigma0*E' + 1e-9*eye(size(E,1));\n\nfunction x = solve_linsys_mu(E,mu0)\nEE1 = E*E';\nB = size(EE1,1);\nEE1 = EE1 + 1e-9*eye(B);\nx = EE1 \\ (E* mu0);\n\nfunction sigma = solve_linsys_sigma(E,sigma0)\n[B,d] = size(E);\nw = 1e-9;\nEE = kron(E,E);\ntmp1 = EE * sigma0(:);\ntmp2 = (eye(d^2) + (1/w)*EE'*EE) \\ (EE' * tmp1);\nsigma = (1/w) * tmp1 - (1/w^2) * EE * tmp2;\nsigma = reshape(sigma,B,B);\n\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM/restore_from_projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6231470289665206}} {"text": "function [x, infos] = online_mu_nmf(V, rank, in_options)\n% Online non-negative matrix factorization (Online-NMF) algorithm.\n%\n% Inputs:\n% matrix V\n% rank rank\n% in_options options\n% Output:\n% w solution of w\n% infos information\n%\n% References:\n% S. S. Bucak, B. Gunsel,\n% \"Incremental Subspace Learning via Non-negative Matrix Factorization,\"\n% Pattern Recognition, 2009.\n% \n%\n% This file is part of NMFLibrary.\n%\n% Created by H.Kasai and H.Sakai on Feb. 12, 2017\n%\n% Change log: \n%\n% Oct. 27, 2017 (Hiroyuki Kasai): Fixed algorithm. \n%\n% May. 20, 2019 (Hiroyuki Kasai): Added initialization module.\n%\n% Jul. 12, 2022 (Hiroyuki Kasai): Modified code structures.\n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = [];\n \n % check input options\n if ~exist('in_options', 'var') || isempty(in_options)\n in_options = struct();\n end \n % merge options\n options = mergeOptions(get_nmf_default_options(), local_options); \n options = mergeOptions(options, in_options);\n \n % initialize factors\n init_options = options;\n [init_factors, ~] = generate_init_factors(V, rank, init_options); \n Wt = init_factors.W;\n H = init_factors.H; \n R = init_factors.R; \n \n % initialize\n method_name = 'Online-MU'; \n epoch = 0;\n grad_calc_count = 0;\n\n if options.verbose > 0\n fprintf('# %s: started ...\\n', method_name);\n end \n \n % store initial info\n clear infos;\n [infos, f_val, optgap] = store_nmf_info(V, Wt, H, R, options, [], epoch, grad_calc_count, 0);\n \n if options.verbose > 1\n fprintf('%s: Epoch = 0000, cost = %.16e, optgap = %.4e\\n', method_name, f_val, optgap); \n end \n \n % set start time\n start_time = tic();\n \n % main outer loop\n while true\n \n % check stop condition\n [stop_flag, reason, max_reached_flag] = check_stop_condition(epoch, infos, options);\n if stop_flag\n display_stop_reason(epoch, infos, options, method_name, reason, max_reached_flag);\n break;\n end \n \n % Reset sufficient statistic\n At = zeros(m, rank);\n Bt = zeros(rank, rank); \n\n % main inner loop\n for t = 1 : options.batch_size : n - 1\n\n % Retrieve vt and ht\n vt = V(:, t:t+options.batch_size-1);\n ht = H(:, t:t+options.batch_size-1);\n\n % uddate ht\n ht = ht .* (Wt.' * vt) ./ (Wt.' * (Wt * ht));\n ht = ht + (ht= n)\n x = blendenpik_over(A, b, params);\nelse\n x = blendenpik_under(A, b, params);\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/25241-blendenpik/blendenpik/blendenpik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6231447003542638}} {"text": "function [imax, xfin, s2fin, ufin, Cxx, uout] = OLOO(A, y, Q)\n% SYNTAX:\n% [imax, xfin, s2fin, ufin, Cxx, uout] = OLOO(A, y, Q)\n%\n% INPUT:\n% A: design matrix\n% y: observations vector\n% Q: cofactor matrix\n%\n% OUTPUT:\n% imax: index of the rejected blocks\n% x_fin: estimated parameters without outlier\n% s2fin: a posteriori sigma without outlier\n% ufin: estimated residuals without outlier\n% Cxx: parameters covariance of the final solution\n% uout: residual of outlier observation\n%\n% DESCRIPTION:\n% perform LS on blocks of correlated observations\n% identify one (block) outlier\n% reject it\n% re-estimate unknowns\n% according to the theory in \"L. Biagi and S. Caldera. An efficient leave one block out approach to identify outliers.Journal of Applied Geodesy, Volume 7, Issue 1, pages 11..19, 2013\"\n%\n% this version is optimized to manage l.o.o. of 1 observation at time, no blocks!\n%\n% CREDITS:\n% 1.0: Stefano Caldera, 22.05.2014\n% 1.1: Stefano Caldera, Andrea Gatti 08.12.2016 ( speedup improvements )\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by: Stefano Caldera 22.05.2014\n% Contributors: Stefano Caldera,\n% Andrea Gatti 08.12.2016 ( speedup improvements )\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n% when FTABLE is undefined, redefine it\nglobal FTABLE; if isempty(FTABLE); FTABLE = finv(0.9995,1,1:size(A,1))'; end\nif (size(FTABLE,1) < size(A,1)); FTABLE = finv(0.9995,1,1:size(A,1))'; end\nn_blocks = length(y);\n[m, n] = size(A); % m: number of observations, n: number of unknowns\nuout = NaN;\n\nif m - n > 0\n\n % compute the global solution\n if isdiag(Q) % Q is tipically diagonal -> let's use this information\n Qm = diag(Q);\n Qm = Qm ./ min(Qm);\n invQ = diag(1./Qm);\n At_invQ = A' * invQ;\n Ninv = inv(At_invQ * A);\n xcap = Ninv * At_invQ * y;\n um = y - A * xcap;\n s2cap = um' * invQ * um/(m-n);\n else\n Q = Q ./ (min(diag(Q)));\n At_invQ = A'/Q;\n Ninv = inv(At_invQ * A);\n xcap = Ninv * At_invQ * y;\n um = y - A * xcap;\n s2cap = um' / Q * um/(m-n);\n Qm = diag(Q);\n end\n % convert A in a sparse matrix, faster and lighter\n\n use_sparse_approach = false;\n\n if sum(A(1,:)==0) > size(A,2) / 0.577 % if A is sparse enough\n use_sparse_approach = true;\n A = sparse(A);\n end\n if m - n > 1\n %% start outliers rejection\n Im = eye(n);\n Bm = Ninv * A';\n Cm = diag(A * Bm);\n Km = Qm - Cm;\n Kminv = Km.^-1;\n wm = Qm .* Kminv .* um;\n s2m = ((m-n) .* s2cap - um .* Kminv .* um) ./ (m - n - 1);\n\n % original loop\n if use_sparse_approach\n % modified loop to exploit the sparse property of the A matrix\n Qw = zeros(n_blocks,1);\n tmp = (A .* repmat(Kminv,1,n));\n for i = 1 : n_blocks\n idOk = (tmp(i,:) ~= 0);\n Qw(i) = Qm(i) + Bm(idOk,i)' * (Im(idOk,idOk) + tmp(i,idOk)' * Bm(idOk,i)') * A(i,idOk)';\n end\n else\n Qw = zeros(n_blocks,1);\n for i = 1 : n_blocks\n Qw(i) = Qm(i) + Bm(:,i)' * (Im + A(i,:)' * Kminv(i) * Bm(:,i)') * A(i,:)';\n %Qw3=Bm(:,i)'*(Im+A(i,:)'*Kminv(i)*Bm(:,i)');\n end\n end\n\n %toc\n Qwinv = Qw.^-1;\n deg2 = m - n - 1;\n\n F = wm .* Qwinv .* wm ./ s2m;\n Flim = FTABLE(deg2);\n\n\n %% apply final solution\n % find maximum F(i)/Flim(i)\n [Fmax, imax] = max(abs(F ./ Flim));\n\n if (Fmax < 1)\n % no outlier\n imax = 0;\n xfin = xcap;\n s2fin = s2cap;\n Ninvfin = Ninv;\n ufin = um;\n Cxx = s2fin * Ninvfin;\n\n else\n % if the maximum ratio exceedes the threshold, the observation is eliminated from the solution\n uout = um(imax);\n xfin = xcap - Bm(:, imax) * Kminv(imax) * um(imax);\n yfin = y;\n yfin(imax) = [];\n\n Afin = A;\n Afin(imax,:) = [];\n\n s2fin = s2m(imax);\n\n Ninvfin = Ninv + Bm(:, imax) * Kminv(imax) * Bm(:, imax)';\n ufin = yfin - Afin * xfin;\n Cxx = s2fin * Ninvfin;\n\n end\n\n else\n imax = 0;\n xfin = xcap;\n s2fin = s2cap;\n Cxx = s2cap * Ninv;\n ufin = um;\n end\n\nelse\n % detection is not possibile\n imax = 0;\n xfin = [];\n Cxx = [];\n ufin = [];\n s2fin = NaN;\nend\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/OLOO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6231446952447859}} {"text": "function [u, s, U_p, U_k, U_d] = pinHoleHmg(p,k,d)\n\n% PINHOLEHMG Pin-hole camera model for HMG points, with optional radial distortion.\n% U = PINHOLEHMG(P) gives the projected pixel U of a homogeneous point P\n% in a canonical pin-hole camera, that is, with calibration parameters\n% u0 = 0\n% v0 = 0\n% au = 1\n% av = 1\n% It uses reference frames {RDF,RD} (right-down-front for the 3D world\n% points and right-down for the pixel), according to this scheme:\n%\n% / z (forward)\n% /\n% +------- x +------- u\n% | |\n% | 3D : P=[x;y;z] | image : U=[u;v]\n% | y | v\n%\n% U = PINHOLE(P,K) allows the introduction of the camera's calibration\n% parameters:\n% K = [u0 v0 au av]'.\n%\n% U = PINHOLE(P,K,D) allows the introduction of the camera's radial\n% distortion parameters:\n% D = [K2 K4 K6 ...]'\n% so that the new pixel is distorted following the distortion equation:\n% U_D = U * (1 + K2*R^2 + K4*R^4 + ...)\n% with R^2 = sum(U.^2), being U the projected point in the image plane\n% for a camera with unit focal length.\n%\n% [U,S] = PINHOLE(...) returns the depth S from the camera center.\n%\n% If P is a points matrix, PINHOLE(P,...) returns a pixel matrix U and a\n% depths row-vector S. P, U and S are defined as\n% P = [P1 ... Pn]; Pi = [xi;yi;zi]\n% U = [U1 ... Un]; Ui = [ui;vi]\n% S = [S1 ... Sn]\n%\n% [U,S,U_p,U_k,U_d] returns the Jacobians of U wrt P, K and D. It only\n% works for single points P=[x;y;z].\n%\n% See also PINHOLE, INVPINHOLEHMG, PINHOLEIDP.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargout <= 2 % only pixel\n\n peuc = hmg2euc(p);\n\n switch nargin\n case 1\n [u, s] = pinHole(peuc);\n case 2\n [u, s] = pinHole(peuc,k);\n case 3\n [u, s] = pinHole(peuc,k,d);\n end\n\n\nelse % Jacobians\n\n if size(p,2) > 1\n error('Jacobians not available for multiple points')\n else\n\n [peuc, PEUC_p] = hmg2euc(p);\n \n switch nargin\n case 1\n [u, s, U_peuc] = pinHole(peuc);\n U_p = U_peuc*PEUC_p;\n\n case 2\n [u, s, U_peuc, U_k] = pinHole(peuc,k);\n U_p = U_peuc*PEUC_p;\n\n case 3\n [u, s, U_peuc, U_k, U_d] = pinHole(peuc,k,d);\n U_p = U_peuc*PEUC_p;\n end\n\n end\n\nend\n\nreturn\n\n%% jacobians\nsyms x y z t u0 v0 au av d2 d4 d6 real\np = [x;y;z;t];\nk = [u0;v0;au;av];\nd = [d2;d4;d6];\n\n[u, s, U_p, U_k, U_d] = pinHoleHmg(p,k,d);\n\nsimplify(U_p - jacobian(u,p))\nsimplify(U_k - jacobian(u,k))\nsimplify(U_d - jacobian(u,d))\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/Observations/pinHoleHmg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6230977400036721}} {"text": "function [p,ellipse]=phantom3dAniso(varargin)\n\n%PHANTOM3D Three-dimensional analogue of MATLAB Shepp-Logan phantom\n% P = PHANTOM3D(DEF,N) generates a 3D head phantom that can \n% be used to test 3-D reconstruction algorithms.\n%\n% DEF is a string that specifies the type of head phantom to generate.\n% Valid values are: \n% \n% 'Shepp-Logan' A test image used widely by researchers in\n% tomography\n% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom\n% in which the contrast is improved for better \n% visual perception.\n% 'yu-ye-wang' Another version of the modified Shepp-Logan\n% phantom from \"Katsevich-Type Algorithms for\n% Variable Radius Spiral Cone-BeamCT\"\n%\n% N specifies the 3D grid size of P\n% If N is a scalar, P will have isotropic size [N, N, N]\n% If N is a 3-vector, P will have size [N(1) N(2) N(3)]\n% If you omit the argument, N defaults to [64 64 64].\n% \n% P = PHANTOM3D(E,N) generates a user-defined phantom, where each row\n% of the matrix E specifies an ellipsoid in the image. E has ten columns,\n% with each column containing a different parameter for the ellipsoids:\n% \n% Column 1: A the additive intensity value of the ellipsoid\n% Column 2: a the length of the x semi-axis of the ellipsoid \n% Column 3: b the length of the y semi-axis of the ellipsoid\n% Column 4: c the length of the z semi-axis of the ellipsoid\n% Column 5: x0 the x-coordinate of the center of the ellipsoid\n% Column 6: y0 the y-coordinate of the center of the ellipsoid\n% Column 7: z0 the z-coordinate of the center of the ellipsoid\n% Column 8: phi phi Euler angle (in degrees) (rotation about z-axis)\n% Column 9: theta theta Euler angle (in degrees) (rotation about x-axis)\n% Column 10: psi psi Euler angle (in degrees) (rotation about z-axis)\n%\n% For purposes of generating the phantom, the domains for the x-, y-, and \n% z-axes span [-1,1]. Columns 2 through 7 must be specified in terms\n% of this range.\n%\n% [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom.\n%\n% Class Support\n% -------------\n% All inputs must be of class double. All outputs are of class double.\n%\n% Remarks\n% -------\n% For any given voxel in the output image, the voxel's value is equal to the\n% sum of the additive intensity values of all ellipsoids that the voxel is a \n% part of. If a voxel is not part of any ellipsoid, its value is 0. \n%\n% The additive intensity value A for an ellipsoid can be positive or negative;\n% if it is negative, the ellipsoid will be darker than the surrounding pixels.\n% Note that, depending on the values of A, some voxels may have values outside\n% the range [0,1].\n% \n% Example\n% -------\n% ph = phantom3d(128);\n% figure, imshow(squeeze(ph(64,:,:)))\n%\n% Copyright 2005 Matthias Christian Schabel (matthias @ stanfordalumni . org)\n% University of Utah Department of Radiology\n% Utah Center for Advanced Imaging Research\n% 729 Arapeen Drive\n% Salt Lake City, UT 84108-1218\n%\n% This code is released under the Gnu Public License (GPL). For more information, \n% see : http://www.gnu.org/copyleft/gpl.html\n%\n% Portions of this code are based on phantom.m, copyrighted by the Mathworks\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Modification May 25, 2015, by Patrick J. Bolan, University of Minnesota\n% Added support for anisotropic phantom sizes: the phantom size can now be \n% a vector. \n%\n\n\n[ellipse,n] = parse_inputs(varargin{:});\n\nnx = n(1); ny = n(2); nz = n(3);\np = zeros([nx ny nz]);\n\nrngx = ( (0:nx-1)-(nx-1)/2 ) / ((nx-1)/2); \nrngy = ( (0:ny-1)-(ny-1)/2 ) / ((ny-1)/2); \nrngz = ( (0:nz-1)-(nz-1)/2 ) / ((nz-1)/2); \n\n% PJB: Note the swap of the x and y with meshgrid parameters. \n%[x,y,z] = meshgrid(rngx,rngy,rngz);\n[x,y,z] = meshgrid(rngy,rngx,rngz);\nx=single(x);y=single(y);z=single(z);\ncoord = [flatten(single(x)); flatten(single(y)); flatten(single(z))];\nclear x y z;\np = flatten(p);\n\nfor k = 1:size(ellipse,1) \n A = ellipse(k,1); % Amplitude change for this ellipsoid\n asq = ellipse(k,2)^2; % a^2\n bsq = ellipse(k,3)^2; % b^2\n csq = ellipse(k,4)^2; % c^2\n x0 = ellipse(k,5); % x offset\n y0 = ellipse(k,6); % y offset\n z0 = ellipse(k,7); % z offset\n phi = ellipse(k,8)*pi/180; % first Euler angle in radians\n theta = ellipse(k,9)*pi/180; % second Euler angle in radians\n psi = ellipse(k,10)*pi/180; % third Euler angle in radians\n \n cphi = cos(phi);\n sphi = sin(phi);\n ctheta = cos(theta);\n stheta = sin(theta);\n cpsi = cos(psi);\n spsi = sin(psi);\n \n % Euler rotation matrix\n alpha = [cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta;\n -spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta;\n stheta*sphi -stheta*cphi ctheta]; \n \n % rotated ellipsoid coordinates\n coordp = alpha*coord;\n \n idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1);\n p(idx) = p(idx) + A;\nend\n\n%p = reshape(p,[nx ny nz]);\np = reshape(p, [nx ny nz]);\n\nreturn;\n\n\nfunction out = flatten(in)\n\nout = reshape(in,[1 numel(in)]);\n\nreturn;\n \n \nfunction [e,n] = parse_inputs(varargin)\n% e is the m-by-10 array which defines ellipsoids\n% n is a 3-vector with the size of the phantom brain image, [nx ny nz]\n\nn = [64 64 64]; % The default size\ne = [];\ndefaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'};\n\nfor i=1:nargin\n if ischar(varargin{i}) % Look for a default phantom\n def = varargin{i};\n idx = strcmpi(def, defaults);\n if isempty(idx)\n eid = sprintf('Images:%s:unknownPhantom',mfilename);\n msg = 'Unknown default phantom selected.';\n error(eid,'%s',msg);\n end\n switch defaults{idx}\n case 'shepp-logan'\n e = shepp_logan;\n case 'modified shepp-logan'\n e = modified_shepp_logan;\n case 'yu-ye-wang'\n e = yu_ye_wang;\n end\n elseif numel(varargin{i})==1 \n n = [varargin{i} varargin{i} varargin{i}]; % a scalar is the image size\n elseif numel(varargin{i})==3 \n siz = varargin{i};\n n = [siz(1) siz(2) siz(3)]; % 3 integers specify image dimensions \n elseif ndims(varargin{i})==2 && size(varargin{i},2)==10 \n e = varargin{i}; % user specified phantom\n else\n eid = sprintf('Images:%s:invalidInputArgs',mfilename);\n msg = 'Invalid input arguments.';\n error(eid,'%s',msg);\n end\nend\n\n% ellipse is not yet defined\nif isempty(e) \n e = modified_shepp_logan;\nend\n\nreturn;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Default head phantoms: %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction e = shepp_logan\n\ne = modified_shepp_logan;\ne(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01];\n\nreturn;\n\n \nfunction e = modified_shepp_logan\n%\n% This head phantom is the same as the Shepp-Logan except \n% the intensities are changed to yield higher contrast in\n% the image. Taken from Toft, 199-200.\n% \n% A a b c x0 y0 z0 phi theta psi\n% -----------------------------------------------------------------\ne = [ 1 .6900 .920 .810 0 0 0 0 0 0\n -.8 .6624 .874 .780 0 -.0184 0 0 0 0\n -.2 .1100 .310 .220 .22 0 0 -18 0 10\n -.2 .1600 .410 .280 -.22 0 0 18 0 10\n .1 .2100 .250 .410 0 .35 -.15 0 0 0\n .1 .0460 .046 .050 0 .1 .25 0 0 0\n .1 .0460 .046 .050 0 -.1 .25 0 0 0\n .1 .0460 .023 .050 -.08 -.605 0 0 0 0\n .1 .0230 .023 .020 0 -.606 0 0 0 0\n .1 .0230 .046 .020 .06 -.605 0 0 0 0 ];\n \nreturn;\n \n\nfunction e = yu_ye_wang\n%\n% Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT\n% \n% A a b c x0 y0 z0 phi theta psi\n% -----------------------------------------------------------------\ne = [ 1 .6900 .920 .900 0 0 0 0 0 0\n -.8 .6624 .874 .880 0 0 0 0 0 0\n -.2 .4100 .160 .210 -.22 0 -.25 108 0 0\n -.2 .3100 .110 .220 .22 0 -.25 72 0 0\n .2 .2100 .250 .500 0 .35 -.25 0 0 0\n .2 .0460 .046 .046 0 .1 -.25 0 0 0\n .1 .0460 .023 .020 -.08 -.65 -.25 0 0 0\n .1 .0460 .023 .020 .06 -.65 -.25 90 0 0\n .2 .0560 .040 .100 .06 -.105 .625 90 0 0\n -.2 .0560 .056 .100 0 .100 .625 0 0 0 ];\n \nreturn;\n \n ", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Test_data/Shepp_logan/phantom3dAniso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6230502952327247}} {"text": "function x = reciprocal_cdf_inv ( cdf, a, b )\n\n%*****************************************************************************80\n%\n%% RECIPROCAL_CDF_INV inverts the Reciprocal CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < A <= B.\n%\n% Output, real X, the corresponding argument of the CDF.\n%\n if ( cdf <= 0.0 )\n x = 0.0;\n elseif ( 0.0 < cdf )\n x = b^cdf / a^( cdf - 1.0 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/reciprocal_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6230502886294172}} {"text": "function [final_sound] = im2sound(filename, ext, f_sample, f_low, ...\n f_high, amp_mod, sample_t)\n\n%INPUTS:\n%'filename' - Name of the image to be encoded (not including extension\n%ext' - Extension of the image (not including \".\" at the beginning). \n%'f_sample' - Sampling frequency (Hz)\n%'f_low' - Lowest frequency (Hz) (e.g. 40)\n%'f_high' - Highest frequency (Hz) (e.g. 6000)\n%'amp_mod' - Multiplication factor for the amplitude. Decrease until \n%image is clear. Too high and the waveform clips. Too low and the image \n%is very dark (e.g. 0.00002)\n%'sample_t' - Duration of the sample in seconds. Longer samples have\n%better quality (e.g. 10)\n\n%OUTPUTS:\n%'final_sound' - the final sound containing the image. This is\n%automatically saved to a .wav file with the original image filename\n\n\n%INITIALISING VARIABLES:\n%The waveform at each time point. This is reset at the beginning of each\n%time point\ntemp_sound = 0; \n%The final waveform\nfinal_sound = 0; \n\n\n%MAIN BODY\n%Loading the sample image and calculating the image size\nraw_im = imread(strcat(filename,'.',ext));\nsize_raw_im = size(raw_im);\n\n%Making a frequency table for the height of the image. Each row of the\n%image is assigned a particular frequency from the corresponding row of \n%this table. The frequencies are linearly distributed between the highest and\n%lowest user-definied frequencies. \"f_step\" is the increment between each\n%adjacent frequency\nf_step = (f_high - f_low)/size_raw_im(1,1);\nf_table = (f_high:-f_step:f_low);\n\n%The final sound will dwell on each column of the image for a specific\n%time. This time is defined by \"t_start\" and \"t_end\". It depends on how\n%long the user determined the sound-clip should be and how wide (how many\n%columns) the image is. \nt_step = (sample_t/size_raw_im(1,2));\n\n%Initial values for the start and end times. These will be increased at\n%the end of each loop iteration (when the script moves onto the next column\n%of the image).\nt_start = 0;\nt_end = t_step;\n\n%The loop which generates the sound file. At each iteration it generates a\n%segment of the final sound file, which is temporarily saved to \n%\"temp_sound\". This segment is built up of frequencies from that\n%particular column of the image.\nfor j = 1:size_raw_im(1,2)\n %Initialising the variable (the sound for each frequency (row) is added\n %to the existing sound)\n temp_sound = 0;\n \n %Setting the time in matrix format\n t = t_start:1/f_sample:(t_end);\n \n %For each iteration of this loop, the script goes down the current\n %column of the image and generates a waveform of the frequency\n %specified in \"f_table\". The amplitude of the waveform is determined\n %by the pixel intensity. This generated waveform is added to all the\n %previously generated waveforms in that particular column\n for i = size_raw_im(1,1):-1:1\n temp_sound = temp_sound+ sin(2*pi*t*f_table(i))*...\n double(raw_im(i,j))*amp_mod;\n \n end\n \n %At the end of each column the segment of sound generated is added to\n %the end of the existing sound file (\"final_sound\").\n final_sound = cat(2,final_sound,temp_sound);\n \n %The temporary sound is cleared ready for the start of the next column\n clear temp_sound\n \n %Moving to the next time frame\n t_start = t_start + t_step;\n t_end = t_end + t_step;\n \nend\n\n%This saves \"final_sound\" to the '.wav' file of the same name as the input\n%file\nwavwrite(final_sound, f_sample, strcat(filename, '.wav'));", "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/30735-hiding-image-in-sound-im2sound/im2sound.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6230470351522517}} {"text": "function [ gx ] = ObsRecGen(x,P,u,in)\n% observation function for k-ToM's bet about her opponent's next move\n% [ gx ] = ObsRecGen(x,P,u,in)\n% Marie Devaine wrote this function in November 2015 (comments: JD).\n% A k-ToM learner bases her decision (a=1 or a=0) upon her prediction of\n% her opponent's next move, given the game payoff table. When k>1, k-ToM\n% maintains more than one such prediction, which depends upon the possible\n% level of her opponent. Let P(o=1) be the probability that k-ToM's\n% opponent will pick the first alternative option. Then:\n% P(o=1) = sum_k P(o=1|k)*P(k)\n% where P(o=1|k) is the probability that k-ToM's opponent will pick\n% the first alternative option if he was a k-ToM, and P(k) is the\n% probability that k-ToM's opponent is a k-ToM.\n% IN:\n% - x: hidden states (see indexing in inG.indlev)\n% - P: observation param:\n% P(1) = (log-) temperature\n% P(2) = bias [optional]\n% - u: [useless]\n% - inG: input structure (see prepare_kToM.m)\n% OUT:\n% - gx: proba that the agent will pick the first option, i.e. gx=P(y=1).\n\nplayer = in.player; % 1 or 2: role of the player\nntotPar = in.npara; % only for k-ToM with k>0\nlevel = in.lev; % depth of k-ToM's recursive beliefs\ngame = in.game; % payoff table\na = 0.36; % for E[s(x)] when x~n(mu,Sig)\nindlev = in.indlev; % hidden-states indexing [see defIndlev.m]\n\n% Get the agent's prediction about her opponent's next move, ie P(o=1).\nif level==0 % 0-ToM\n \n mx = x(1); % E[log-odds of P(o=1)]\n Vx = exp(x(2)); % V[log-odds of P(o=1)]\n Po = VBA_sigmoid(mx/(sqrt(1+a*Vx))); % P(o=1)\n \nelse\n \n % Get P(k'). Note: if the agent is k-ToM, then, by definition, she\n % considers that her opponent's sophistication is k' < k. In addition,\n % there is a constraint of normalization, ie sum_k' P(k') = 1. Thus,\n % one only needs to keep track of k'-1 probabilities (the last one is,\n % by construction, 1-sum_k' P(k')).\n Pk = VBA_sigmoid(x(1:(level-1))); % P(k'), with k'=0,...,k-1\n Pk = [Pk;max(0,1-sum(Pk))]; % insert last P(k'=k-1)\n \n % Get P(o=1|k'). Note: the agent's prediction P(o=1|k') depends upon\n % her estimate of her opponent's parameters (learning rate, tmperature,\n % bias...). Uncertainty Re: these parameters eventually results in\n % blurring her prediction.\n % Note: hidden states encode x(theta), the log-odds of P(o=1|k',theta)\n % evaluated at the agent's estimate of theta (mu). In addition, they\n % encode the gradient of x wrt to theta (dx/dtheta), and V[theta]. This\n % then serves to derive P(o=1|k') as follows:\n % P(o=1|k') = E[sigm(x(theta))]\n % = sigm(E[x(theta)]/sqrt(1+a*V[x(theta)])\n % = sigm(E[x(theta)]/sqrt(1+a*V[theta]*(dx/dtheta)^2) \n f = zeros(level,1); % E[x(theta)]\n Vx = zeros(level,1); % V[x(theta)]\n for j=1:level % loop over possible opponent's levels (k'=j-1)\n f(j) = x(indlev(j).f); % E[x(theta)|k'=j-1]\n df = x(indlev(j).df); % d[x(theta)]/dtheta for k'=j-1\n Sig = exp(x(indlev(j).Par(2:2:2*ntotPar))); % V[theta|k'=j-1]\n Vx(j) = sum(Sig.*df.^2); % V[x(theta)|k'=j-1]\n end\n Es = VBA_sigmoid(f./sqrt(1+a*Vx)); % E[sigm(x(theta))]\n \n % Get P(o=1) = sum_k P(o=1|k')*P(k')\n Po = Pk'*Es; % k-ToM's belief about her opponent's next move\n \nend\n\n% Make decision based upon P(o=1)\nDV = fplayer(Po,exp(P(1)),player,game); % incentive for a=1\nif length(P)==1\n gx = VBA_sigmoid(DV); % P(a=1)\nelse % P(2) = bias\n gx = VBA_sigmoid(DV+P(2)); % P(a=1) with bias\nend\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/ObsRecGen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6230470345774847}} {"text": "function [Model, Info] = linear_sparse_stepwise_vec(X,Y,Model,parm)\n% Estimate linear weight matrix for input-output mapping\n% Automatic Relevance Prior for each input dimension\n% is imposed to get sparse weight matrix\n%\n% Notice !!\n% Delay embedding is done in this module,\n% then input vector should be original input data without embedding\n%\n% [Model, Info] = linear_sparse_stepwise(X,Y,Model,parm)\n% Scalar iteration version\n% --- Input\n% Y : Output data ( N x T x Ntrial )\n% X : Input data ( M x (T + (Dtau-1)*Tau) x Ntrial)\n% N = # of output\n% M = # of input (original input space dimension)\n% T = # of time sample\n%\n% Estimate the following model\n% Y(t) = W * [X(:, t + (Dtau-1)*Tau ); ...; X(:, t)]\n%\n% Model : Structure for estimated model\n% if Model is empty, initialization is done before training\n% if Model is previous training result, re-training us done\n%\n% parm : Structure for learning parameter\n% parm.Npre_train : # of VB-update in initial training\n% parm.Ntrain : # of training\n% parm.Nskip : skip # for print\n% parm.a_min : Min value for pruning small variance component\n% parm.Prune : = 1 : Prune small variance & irrelevant input dimension\n%\n% parm.Tau = Lag time\n% parm.Dtau = Number of embedding dimension\n% Total input dimension in embedding space is (M * parm.Dtau)\n% --- Output\n% Model : Structure for estimated model\n% Model.SY : Noise variance ( 1 x 1 )\n% Model.W : Weight matrix ( N x M*D ) , D = parm.Dtau\n% Model.A : Prior weight variance ( 1 x M*D ) \n% Model.ix_act : Active index for W after pruning\n%\n% Info : Structure for learning process history\n% Info.FE = LP + H : Free energy\n% Info.LP = Log likelihood\n% Info.H = - Model entropy\n%\n% 2009-10-18 Made by M. Sato\n\nMINVAL = 1.0e-15;\n\nfprintf('linear_sparse_stepwise start\\n')\n\n% Dimension\n[N ,T ,Ntrial] = size(Y); % N = # of output\n[M ,Tx ,Ntrialx] = size(X); % M = # of input without embedding\n\nTall = T * Ntrial;\n\nif Ntrial~=Ntrialx, error('# of trial is different in X and Y'); end;\n\nNskip = 100; % skip steps for display info\na_min = 1e-14;\t% Minimum value for weight pruning\nFdiff = 1e-12; % Threshold for convergence\nNcheck = 100; % Minimum number of training iteration\nFstep = 5; % Free energy convergence check step\nPrune = 1; % Prune mode\nspace_ARD=1;\t% if space_ARD=1, ARD is done only for space dimension\n\nif isfield(parm,'Nskip'), Nskip = parm.Nskip; end;\nif isfield(parm,'Fdiff'), Fdiff = parm.Fdiff; end;\nif isfield(parm,'a_min'), a_min = parm.a_min ; end;\nif isfield(parm,'Prune'), Prune = parm.Prune; end;\nif isfield(parm,'Ncheck'), Ncheck = parm.Ncheck; end\nif isfield(parm,'Fstep'),Fstep = parm.Fstep ; end\nif isfield(parm,'Fstep'),Fstep = parm.Fstep ; end\nif isfield(parm,'space_ARD'),space_ARD = parm.space_ARD ; end\n\n% # of embedding dimension\nif isfield(parm,'Dtau')\n\tD = parm.Dtau; \n\ttau = parm.Tau;\nelse\n\tD = 1;\n\ttau = 1;\nend\n% Parameters\nNtrain = parm.Ntrain;\n\nif Ntrain < 1, Info = []; return; end;\n\nif isfield(parm,'Npre_train')\n\tNpre_train = parm.Npre_train;\nelse\n%\tNpre_train = Ntrain;\n\tif Tall >= 2*M*D\n\t\tNpre_train = 0;\n\telseif Tall >= M*D\n\t\tNpre_train = fix(Ntrain/2);\n\telse\n\t\tNpre_train = Ntrain;\n\tend\nend\n\nif Npre_train > Ntrain, Npre_train = Ntrain; end;\n\nif isfield(parm,'Nupdate')\n\tNupdate = parm.Nupdate;\nelse\n\tNupdate = 1;\nend\n\nfprintf('--- Output Dimension = %d\\n',N)\nfprintf('--- Input Dimension = %d\\n',M)\nfprintf('--- Embedding Dimension = %d\\n',D)\nfprintf('--- Number of trials = %d\\n',Ntrial)\nfprintf('--- Number of training sample = %d\\n',Tall)\nfprintf('--- Total update iteration = %d (%d)\\n',Ntrain,Npre_train)\n\n% original input dimension\nXdim = M;\nM = Xdim*D;\nM_ALL = M;\n\n% \n% --- Initialization\n%\n\n% Input/Output variance\nsx = mean((X(:) - mean(X(:))).^2);\nsy = mean((Y(:) - mean(Y(:))).^2);\n\nSY0 = mean(sy);\nA0 = 1./mean(sx);\n\nif isfield(parm,'Ta0') && parm.Ta0 > 0,\n\tTa0 = parm.Ta0;\n\ta0 = parm.a0 * A0;\nelse\n\tTa0 = 0;\n\ta0 = 1;\nend\n\n% Input covariance\nXX = sum(sum(X.^2,3),2)/(Tx*Ntrial);\nXX = repmat(XX', [1 D]);% 1 x M\n\nif isfield(Model,'ix_act')\n\tSY = Model.SY; % 1 x 1\n\n\t% Active index\n\tix_act = Model.ix_act;\n\tA = zeros(1,M_ALL);\n\tW = zeros(N,M_ALL);\n\t\n\tA(ix_act) = sum(Model.A,1);\n\tW(:,ix_act) = Model.W;\n\n\tif M_ALL ~= Xdim*D,\n\t\tfprintf('M_ALL=%d,Xdim=%d,D=%d\\n',M_ALL ,Xdim ,D)\n\t\terror('M_ALL ~= Xdim*D')\n\tend\n\t\n\t% Active index in input space without embedding\n\tIX_dim = find( sum(reshape(A,[Xdim,D]),2) > 0);\n\t\n\tIX_act = repmat( (0:(D-1))* Xdim ,[length(IX_dim) 1]) ...\n\t + repmat(IX_dim, [1 D]);\n\tIX_act = IX_act(:);\n\t\n\tW = W(:,IX_act) ; % N x (M*D)\n\tA = A(IX_act) ; % 1 x (M*D)\n\tX = X(IX_dim,:,:);\n\tXX = XX(IX_act); \n\t\n\tM = length(IX_act);\n\tXdim = length(IX_dim);\nelse\n\tA = repmat(A0, [1,M_ALL]);\n\tW = zeros(N,M_ALL);\n\tSY = SY0;\n\t% Save original input for pruning\n\tIX_act = 1:M_ALL;\n\tIX_dim = 1:Xdim;\nend\n\nix_act = 1:M;\nix_dim = 1:Xdim;\nM_all = M;\n\n% Delay embedding index for W\nWid = [(0:(D-1))'* Xdim + 1 , (1:D)'* Xdim];\n\n% Working variable\nG_A = zeros(1,M); % N x M\n\nif size(A,1)==Xdim && size(A,2)==1\n\tA = repmat(A',[1 D]);\nelseif size(A,1)==1 && size(A,2)==Xdim\n\tA = repmat(A,[1 D]);\nend\n\nif length(SY)==1, SY= repmat(SY,N,1); end;\n\nSW = 1./(Tall*XX + 1./A );\n\nfprintf('a_min = %g\\n', a_min)\nfprintf('SY0 = %g\\n', SY0)\nfprintf('SY = %g\\n', mean(SY))\n\n% Free energy histry\nFE = zeros(Ntrain,1);\nLP = zeros(Ntrain,1);\nH = zeros(Ntrain,1);\nErr = zeros(Ntrain,1);\nMhist = zeros(Ntrain,1);\n\n% ARD hyper param. history\nif isfield(parm,'Debug') && ~isempty(parm.Debug) && parm.Debug > 0\n\tDebug = 1;\n\tA_tmp = zeros(N*M_ALL, ceil(Ntrain/Nskip));\nelse\n\tDebug = 0;\nend\n\n% recover all component\nA_all = zeros(1,M_all); % N x M\n\n[dY] = error_delay_time(X,Y,W,tau);\n\nk_save = 0;\n\n%%%%%% Learning Loop %%%%%%\nfor k=1:Ntrain\n\t% Ainv = alpha , A = 1/alpha\n\tAinv = 1./A;\t\n\t\n\t% E = ( (Y-W*X)^2 + W^2 * Ainv )/SY\n [W] = weight_update_embed(X, dY, W, Tall*XX, Ainv, tau);\n\t[dY] = error_delay_time(X, Y, W, tau);\n\n dYY = sum(dY.^2,2)/(Tall); % N x 1\n\tWW = W.^2;\n \n % Noise variance update\n SY = dYY + WW * Ainv'/(Tall);\n % Prevent zero variance\n SY = max( SY, MINVAL);\n \n % Weight variance\n\tSW = 1./(Tall*XX + Ainv );\n\n % Log variance\n SWA = max( SW .* Ainv , MINVAL);\n log_sw = N*(sum( log(SWA) - SWA + 1 ));\n log_sy = sum( log(SY) );\n log_a = Ta0*sum( log(Ainv) - a0.*Ainv + 1 );\n\t\n % Free energy\n LP(k) = - (0.5) * (log_sy + N*sum(SW.*XX));\n H(k) = 0.5*( log_sw + log_a );\n FE(k) = LP(k) + H(k)/Tall;\n Err(k) = sum(dYY)/(N*SY0);\n\n\n\t% E = ( (Y-W*X)^2 + W^2 * Ainv )/SY\n\t\n % Hyper parameter for weight variance (ARD)\n\tif mod(k,Nupdate) == 0,\n\t\t% Ainv = 1./A;\t\n\t % SW = 1./( Tall*XX + Ainv );\n\t \n\t % G_A = 1 - (SW)./A;\n\t % = (Tall*XX + Ainv - 1/A) * SW\n\t G_A = Tall.* ( SW ) .* XX;\n\t G_A = max((G_A), MINVAL);\n\t \n\t\t% N*A = ( (W.^2) + SW )/SY ; \n\t\tif k <= Npre_train,\n\t\t\t% VB update rule (Stable)\n\t\t\t% ARD for each weight\n\t\t\tA = ((1./SY)'*WW + N*SW + 2*Ta0*a0)/( N + 2*Ta0 );\n\t\telse\n\t\t\t% Accelerated update rule (Unstable)\n\t\t A = sqrt( A.* ((1./SY)'*WW) ./(G_A * N) );\n\t\t %A = (WW + 2*Ta0*a0)./(G_A * N + 2*Ta0);\n\t\tend\n\t\t\n\t\tif space_ARD==1\n\t\t\tAm = mean(reshape(A,[M/D,D]),2);\n\t\t\tA = repmat(Am', 1,D);\n\t\tend\n\t\t\n\t % Prune small variance\n\t if Prune == 1\n\t\t % Find active input dimension\n\t\t ix_act_old = ix_act;\n\t\t ix_dim_old = ix_dim;\n\n\t\t % recover all component\n\t\t\tA_all = zeros(1,M_all); % 1 x M\n\t\t % A_all(:,ix_act) = A;\n\t\t WWW = sum(WW,1);\n\t\t A_all(ix_act) = WWW/max(WWW);\n\t\t \n\t\t % find active input dimension (absolute index)\n\t\t ix_dim = find( sum(reshape(A_all,[Xdim,D]),2) > a_min );\n\t\t ix_act = repmat(ix_dim, [1 D]) ...\n\t\t + repmat([0:D-1]*Xdim, [length(ix_dim) 1]);\n\t\t ix_act = ix_act(:);\n\t\t \n\t\t Mnew = length(ix_act); \t\t% # of effective input\n\t\t \n\t\t if Mnew < M,\n\t\t\t % convert to relative index\n\t\t\t jx_act = trans_index(ix_act,ix_act_old,M_all);\n\t\t\t jx_dim = trans_index(ix_dim,ix_dim_old,Xdim);\n\t\t\t \n\t\t\t M = Mnew;\n\t\t\t A = A(jx_act) ; % 1 x M\n\t\t\t W = W(:,jx_act) ; % N x M\n\t\t\t SW = SW(:,jx_act); % N x M\n\t\n\t\t\t X\t = X(jx_dim,:,:); \t \t% Xdim x T\n\t\t\t XX\t = XX(jx_act); \t \t% 1 x M\n\t\t\tend\n\t end\n\t % END of if Prune == 1\n\n\t\tA = max(A,MINVAL);\n\t \n\tend\n\t% END of if mod(k,Nupdate) == 0\n\t\n\tMhist(k) = M;\n\n if mod(k, Nskip)==0\n % Save history\n\t\tif Debug == 1\n \tk_save = k_save + 1;\n \tA_tmp(:,k_save) = A_all(:);\n\t\tend\n\t\t\n fprintf('Iter = %4d, M = %4d, err = %g, F = %g, H = %g\\n', ...\n k, length(ix_act), Err(k), FE(k), - 2*H(k)/log(T));\n end\n \n % Convergence check\n\tif k > Ncheck,\n\t\tFdif = (FE(k) - FE(k-Fstep))/(abs(FE(k))+eps);\n\telse\n\t\tFdif = Fdiff + 1;\n\tend\n\t\n\tif (Fdiff > abs(Fdif)), \n\t\tfprintf('Converged : Free energy change = %g\\n',Fdif)\n\t\tbreak; \n\tend;\nend\n\nix_act = IX_act(ix_act);\n\n% Active index\nModel.ix_act = ix_act;\nModel.M_all = M_ALL ;\n\n% Save output variable\nModel.A = A ;\nModel.W = W ;\nModel.SY = SY;\nModel.SW = SW; % = 1./(Tall*XX + diag(Ainv))\n\nModel.method = 'linear_sparse_stepwise';\nModel.mode = 'scalar';\nModel.sparse = 'sparse';\n\n% Save history\nInfo.FE = FE(1:k);\nInfo.LP = LP(1:k);\nInfo.H = H(1:k) ;\nInfo.Err = Err(1:k);\nInfo.M = Mhist(1:k);\n\nif exist('A_tmp','var')\n\tInfo.A = A_tmp(:,1:k_save) ;\nend\n\n\n% recover all component\n%W_all = zeros(N,M_all);\n%SW_all = zeros(N,M_all);\n%\n%A_all(:,ix_act) = A;\n%W_all(:,ix_act) = W ; % N x M\n%SW_all(:,ix_act) = SW; % N x M\n\n%%% ---- Index transformation from old active_index to current active_index\nfunction\tjx = trans_index(ix,ix_old,M)\n\nN = length(ix_old);\nItrans = zeros(M,1);\nItrans(ix_old) = 1:N;\n\njx = Itrans(ix);\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/linear_sparse_stepwise_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6230386383652}} {"text": "function I = mi_model_gd_vec(x, y, Ym, biascorrect, demeaned)\n% MI_MODEL_GD_VEC Vectorized MI calculation between multiple Gaussian variables \n% and a common discrete variable in bits based on ANOVA style model comparison.\n% I = mi_model_gd_vec(x,y,Ym) returns the MI between the (possibly multidimensional)\n% Gaussian variables x and the discrete variable y.\n% size(x) = [Ntrl Nvec Ndim]\n% so each output I(i) = mi_model_gd(squeeze(x(:,i,:)), y, Ym);\n%\n% For 1D x this is a lower bound to the mutual information.\n% y should contain integer values in the range [0 Ym-1] (inclusive).\n%\n% biascorrect : true / false option (default true) which specifies whether\n% bias correction should be applied to the esimtated MI.\n% demeaned : false / true option (default false) which specifies whether the\n% input data already has zero mean (true if it has been copula-normalized)\n% See also: MI_MODEL_GD, MI_MIXTURE_GD_VEC\n\n% ensure samples first axis for vectors\nif isvector(x)\n x = x(:);\nend\nif ndims(x)>3\n error('mi_model_gd: input arrays should be 3d')\nend\nif isvector(y)\n y = y(:);\nelse\n error('mi_model_gd: only univariate discrete variable supported');\nend\n\nNtrl = size(x,1);\nNvec = size(x,2);\nXdim = size(x,3);\n\nif size(y,1) ~= Ntrl\n error('mi_model_gd: number of trials do not match');\nend\n\n% default option values\nif nargin<4\n biascorrect = true;\nend\n\nif nargin<5\n demeaned = false;\nend\n\n% unconditional demean\nif ~demeaned\n x = bsxfun(@minus,x,sum(x,1)/Ntrl);\nend\n\nI = zeros(Nvec,1);\n\n% y = y-1;\n% for vi=1:Nvec\n% I(vi) = mi_model_gd(squeeze(x(:,vi,:)),y,Ym,true,true);\n% end\n% \n% return\n\n% one-hot encoding of Y\nYhot = indexed2boolean(y);\n\n% remove class means\n[Xcen class_means] = removeclassmeans(x, Yhot);\n\n% allocate memory for class-conditional entropies and covariances\nNtrl_y = sum(Yhot);\nHcond = zeros(Nvec,Ym);\nCm = zeros(Nvec,Xdim,Xdim,Ym);\n\n% allocate memory for overall entropy and covariance\nHunc = zeros(Nvec,1);\nCx = zeros(Nvec,Xdim,Xdim);\n\n% data is class-demeaned, this needs to be accounted for in the\n% unconditional entropies\nc = diag(sqrt(Ntrl_y))*class_means.';\nc = reshape(c, [Ym Nvec Xdim]);\n\nfor vi1=1:Xdim\n % all voxels for this dimension\n x1 = Xcen(:,:,vi1);\n c1 = squeeze(c(:,:,vi1));\n \n Cx(:,vi1,vi1) = sum(x1.^2)+sum(c1.^2);\n for yi=1:Ym\n tmp = x1(Yhot(:,yi),:);\n Cm(:,vi1,vi1,yi) = sum(tmp.^2);\n end\n \n for vi2=(vi1+1):Xdim\n x2 = Xcen(:,:,vi2);\n c2 = squeeze(c(:,:,vi2));\n tmp = transpose(sum(x1.*x2) + sum(c1.*c2));\n \n Cx(:,vi1,vi2) = tmp;\n Cx(:,vi2,vi1) = tmp;\n for yi=1:Ym\n tmp = transpose(sum(x1(Yhot(:,yi),:).*x2(Yhot(:,yi),:)));\n Cm(:,vi1,vi2,yi) = tmp;\n Cm(:,vi2,vi1,yi) = tmp;\n end\n end\nend\n\nCx = Cx / (Ntrl-1);\nCx = vecchol(Cx);\nfor vi=1:Xdim\n Hunc = Hunc + shiftdim(log(Cx(:,vi,vi)));\nend\n\nfor yi=1:Ym\n Cm(:,:,:,yi) = Cm(:,:,:,yi) / (Ntrl_y(yi) - 1);\n Cm(:,:,:,yi) = vecchol(Cm(:,:,:,yi));\n for vi=1:Xdim\n Hcond(:,yi) = Hcond(:,yi)+shiftdim(log(Cm(:,vi,vi,yi)));\n end\nend\n\n% apply bias corrections\nln2 = log(2);\nif biascorrect\n\n vars = 1:Xdim;\n \n psiterms_unc = psi((Ntrl - vars)/2) / 2;\n dterm_unc = (ln2 - log(Ntrl-1)) / 2;\n bias_unc = Xdim'*dterm_unc + sum(psiterms_unc);\n \n dterm_cond = (ln2 - log(Ntrl_y-1)) / 2;\n psiterms_cond = zeros(1,Ym);\n for vi=vars\n idx = (Ntrl_y-vi);\n psiterms_cond = psiterms_cond + psi(idx/2);\n end\n bias_cond = Xdim*dterm_cond + (psiterms_cond/2);\n\n Hunc = Hunc - bias_unc;\n Hcond = Hcond - ones(Nvec,1)*bias_cond;\nend\n\n% class weights\nw = Ntrl_y ./ Ntrl;\n\n% compute mutual information\nI = Hunc - Hcond*w';\n\n% convert to bits\nI = I / ln2;\n\nfunction [Xcen, class_means] = removeclassmeans(X, design)\n[Ntrl, Nvec, Ndim] = size(X);\nXcen = X(:,:);\nclass_means = zeros(Nvec*Ndim,size(design,2));\nfor k = 1:size(design,2)\n sel = design(:,k);\n tmp = Xcen(sel,:);\n class_means(:,k) = mean(tmp,1);\n Xcen(sel,:) = bsxfun(@minus,tmp,class_means(:,k).');\nend\nXcen = reshape(Xcen,[Ntrl Nvec Ndim]);\n\nfunction Y = indexed2boolean(X)\nuX = unique(X);\nY = false(numel(X),numel(uX));\nfor k = 1:size(Y,2)\n Y(X==uX(k),k) = true;\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/gcmi/mi_model_gd_vec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6230386333142487}} {"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% Test script for illustration\n\n\n% base scenario\nt=0; T=1; \nf = 0.03; \nalpha = 0.075; \nbeta = 0.5; \nnu = 0.1; \nrho = 0;\n\nsabrdensity = @(x,y) psabr3(t,T,f,x,alpha,y,beta,nu,rho);\n\nlcoeff = 1; ucoeff = 1;\nlowerbound = f-lcoeff*f;\nupperbound = f + ucoeff*f;\n\nxvals = lowerbound:.0005:upperbound;\n\nzvals1d = density1d(xvals,sabrdensity,0,1);\n\n% change rho\nrho = -.9;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dm = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dm)\nrho = .9;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dp = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dp)\nfigure('Color',[1 1 1]);\nhold on;\nplot(xvals,zvals1dm,'r','LineWidth',2); plot(xvals,zvals1d,'b','LineWidth',2); plot(xvals,zvals1dp,'g','LineWidth',2);\ntitle('Plot of SABR densities for different \\rho')\nxlabel('0\\leq x \\leq .1')\nylabel('density')\nlegend('\\rho=-0.9','\\rho=0','\\rho=0.9')\nhold off;\nrho = 0.0;\n\n% change nu\nnu = 0.05;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dm = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dm)\nnu = .15;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dp = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dp)\nfigure('Color',[1 1 1]);\nhold on;\nplot(xvals,zvals1dm,'r','LineWidth',2); plot(xvals,zvals1d,'b','LineWidth',2); plot(xvals,zvals1dp,'g','LineWidth',2);\ntitle('Plot of SABR densities for different \\nu')\nxlabel('0\\leq x \\leq .1')\nylabel('density')\nlegend('\\nu=0.05','\\nu=0.4','\\nu=0.2')\nhold off;\nnu = 0.1;\n\n% change beta\nbeta = 0.4;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dm = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dm)\nbeta = 0.8;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dp = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dp)\nfigure('Color',[1 1 1]);\nhold on;\nplot(xvals,zvals1dm,'r','LineWidth',2); plot(xvals,zvals1d,'b','LineWidth',2); plot(xvals,zvals1dp,'g','LineWidth',2);\ntitle('Plot of SABR densities for different \\beta')\nxlabel('0\\leq x \\leq .1')\nylabel('density')\nlegend('\\beta=0.4','\\beta=0.5','\\beta=0.6')\nhold off;\nbeta = 0.5;\n\n% change alpha\nalpha = 0.05;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dm = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dm)\nalpha = .1;\nsabrdensity = @(x,y) psabr30(t,T,f,x,alpha,y,beta,nu,rho);\nzvals1dp = density1d(xvals,sabrdensity,0,1);\nintdensity(xvals,zvals1dp)\nfigure('Color',[1 1 1]);\nhold on;\nplot(xvals,zvals1dm,'r','LineWidth',2); plot(xvals,zvals1d,'b','LineWidth',2); plot(xvals,zvals1dp,'g','LineWidth',2);\ntitle('Plot of SABR densities for different \\alpha')\nxlabel('0\\leq x \\leq .1')\nylabel('density')\nlegend('\\alpha=0.05','\\alpha=0.075','\\alpha=0.1')\nhold off;\nalpha = 0.075;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/scriptsabrdensity_p30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6230386122039635}} {"text": "function [Q] = CouetteBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n\n% function [Q] = CouetteBC2D(xin, yin, nxin, nyin, mapI, mapO, mapW, mapC, Q, time);\n% Purpose: evaluate solution for Couette flow\n\n% Couette flow (mach .2 at inner cylinder)\ngamma = 1.4;\n\n% extract conserved variables\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\n\nmapB = [mapI;mapO];\n\nrad = sqrt(xin(mapB).^2 + yin(mapB).^2);\ntheta = atan2(yin(mapB), xin(mapB));\n\nutheta = (-rad + 16./rad)/75;\np = 1 + (1./(75^2))*( (rad.^2)/2 - 32*log(rad) - 128./rad.^2 );\n\nrho (mapB) = 1;\nrhou(mapB) = -sin(theta).*utheta;\nrhov(mapB) = cos(theta).*utheta;\nEner(mapB) = p/(gamma-1) + 0.5*(rhou(mapB).^2 + rhov(mapB).^2)./rho(mapB);\n\n% pack modified conserved variables\nQ(:,:,1) = rho; Q(:,:,2) = rhou; Q(:,:,3) = rhov; Q(:,:,4) = Ener;\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD2D/CouetteBC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6230368816413937}} {"text": "function [E,L,G]=GenPCBasis(S,A)\n% this function computes the conditional principal portfolios\n% see A. Meucci - \"Managing Diversification\", Risk Magazine, June 2009\n% available at www.ssrn.com\n\n% Code by A. Meucci. This version March 2009. \n% Last version available at MATLAB central as \"Managing Diversification\"\n\n% inputs\n% S : covariance matrix\n% A : conditioning matrix\n\n% outputs\n% E : conditional principal portfolios composition\n% L : conditional principal portfolios variances\n% G : map weights -> conditional diversification distribution (square root of, not normalized)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif isempty(A)\n N=size(S,1);\n K=0;\n [E_,L_]=eig(S);\n E=E_;\n for n=1:N\n E(:,n)=E_(:,N-n+1);\n L(n)=L_(N-n+1,N-n+1);\n end\n\nelse\n\n [K,N]=size(A);\n E=[];\n B=A;\n for n=1:N-K\n if ~isempty(E)\n B=[A\n E'*S];\n end\n e=GenFirstEigVect(S,B);\n E=[E e];\n end\n\n for n=N-K+1:N\n B=E'*S;\n e=GenFirstEigVect(S,B);\n E=[E e];\n end\n\n % swap order\n E=[E(:,N-K+1:N) E(:,1:N-K)];\nend\n\nL=diag(E'*S*E);\n\nG=diag(sqrt(L))*inv(E);\nG=G(K+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/23271-managing-diversification/MeanDiversifFrontier/GenPCBasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6230021409015705}} {"text": "%TROTY Rotation about Y axis\n%\n% T = TROTY(THETA) is a homogeneous transformation (4x4) representing a rotation \n% of THETA radians about the y-axis.\n%\n% T = TROTY(THETA, 'deg') as above but THETA is in degrees.\n%\n% Notes::\n% - Translational component is zero.\n%\n% See also ROTY, TROTX, TROTZ, TROT2.\n\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 T = troty(t, varargin)\n\tT = [roty(t, varargin{:}) [0 0 0]'; 0 0 0 1];\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/troty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6228950539928075}} {"text": "%% DEMO 7: Algorithms 02. SART\n%\n%\n% In this demo the usage of the algorithms on the SART family among with\n% their options are presented. \n% \n% \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri \n%--------------------------------------------------------------------------\n%% Initialize\nclear;\nclose all;\n\n%% Define Geometry\ngeo=defaultGeometry('nVoxel',[128;128;128]); \n\n%% Load data and generate projections \n% see previous demo for explanation\nangles=linspace(0,2*pi,100);\nhead=headPhantom(geo.nVoxel);\nprojections=Ax(head,geo,angles,'interpolated');\nnoise_projections=addCTnoise(projections);\n%% SART family of algorithms\n%\n% There are 3 algorithms in this damily included in TIGRE: SART,SIRT and\n% OS-SART.\n%\n% The main difference between them is the update process. \n% SART: Updates the image projection by projection\n% SIRT: Updates the image using the whole set of projections at once\n% OS-SART: middle ground. Updates the image using a subset of the\n% projections\n%\n% Of these algorithms, SART is generally the one reaching a better image\n% (less L2 error) for the same amount of iterations, and SIRT is the\n% worst (still relatively similar). However, SART needs increased\n% computational time per iteration, as it needs to update the image very often,\n% while SIRT only updates the emage ones for the whole sets of projections.\n% OS-SART lies in the middle, reaching similar convergence (L2 error per\n% iteration) than SART but with less computational time than SART.\n%\n%% Usage, with optional parameters.\n% In the three algorithms, there are 4 mandatory input arguments:\n% Projections, geometry, angles and number of iterations.\n%\n%\n% Optional arguments for all of them\n%==========================================================================\n% 'lambda': hyperparameter. The update will be multiplied by this number\n% every iteration, to make the steps bigger or smaller. Default: 1\n%\nlambda=1;\n\n\n% 'lambdared': reduction multiplier for the hyperparameter.\n% lambda=lambda*lambdared every iterations, so the steps can be smaller\n% the further the update. Default=0.99\nlambdared=0.999;\n\n% 'Init' : Initialization method. Possible options are\n% 'none' (default). There will be no initialization method, just\n% the algorithm\n% \n% 'FDK' Initialize the image with the result of FDK algorithm\n%\n% 'multigrid' Initialize using the multigrid method. The image\n% will be solved in a small scale, and the size of it\n% will increase until the desired size is reached.\n%\n% 'image' Initialzies with a user given image. Not recoomended\n% unless you really know what you are doing.\n\ninitmode='none';\n\n% 'InitImg' : related to init. The image to use for initializing the\n% algorithm.\n\n% 'verbose': boolean to make the algorithm display (or not) running state. \n% default true.\n\nverbose=true;\n% 'QualMeas' Asks the algorithm for a set of quality measurement\n% parameters. Input should contain a cell array of desired\n% quality measurement names. Example: {'CC','RMSE','MSSIM'}\n% These will be computed in each iteration. \nqualmeas={'RMSE'};\n\n% SIRT and SART both have no extra input parameters.\n% =========================================================================\n[imgSIRT,errL2SIRT,qualitySIRT]=SIRT(projections,geo,angles,20,...\n 'lambda',lambda,'lambda_red',lambdared,'verbose',verbose,'QualMeas',qualmeas);\n[imgSART,errL2SART,qualitySART]=SART(projections,geo,angles,20,...\n 'lambda',lambda,'lambda_red',lambdared,'verbose',verbose,'QualMeas',qualmeas);\n% OS-SART\n% ========================================================================\n% Additionally OS-SART includes a couple of other parameters, related to\n% the subsets.\n%\n% 'BlockSize': Sets the projection block size used simultaneously. If\n% BlockSize = 1 OS-SART becomes SART and if BlockSize = size(angles,2)\n% then OS-SART becomes SIRT. Default is 20.\nblcks=8;\n% 'OrderStrategy': Chooses the subset ordering strategy. Options are\n% 'ordered' :uses them in the input order, but divided\n% 'random' : orders them randomply\n% 'angularDistance': chooses the next subset with the \n% biggest angular distance with the\n% ones used. (default)\norder='angularDistance';\n[imgOSSART,errL2OSSART,qualityOSSART]=OS_SART(projections,geo,angles,20,...\n 'lambda',lambda,'lambda_red',lambdared,'verbose',verbose,'QualMeas',qualmeas,...\n 'BlockSize',blcks,'OrderStrategy',order);\n%% Lets have a brief show of the results\n% set(0,'DefaultTextInterpreter', 'latex')\n\nsubplot(211)\nplot(log10([errL2SIRT;[errL2OSSART nan(1,length(errL2SIRT)-length(errL2OSSART))];[errL2SART nan(1,length(errL2SIRT)-length(errL2SART))]]'));\ntitle('Convergence')\nxlabel('Iteration')\nylabel('$ log_{10}(|Ax-b|) $','interpreter','latex')\nlegend('SIRT','OS-SART','SART')\nsubplot(212)\nplot(log10([qualitySIRT;[qualityOSSART nan(1,length(qualitySIRT)-length(qualityOSSART))];[qualitySART nan(1,length(qualitySIRT)-length(qualitySART))]]'));\ntitle('Evolution of RMSE')\nlegend('SIRT','OS-SART','SART')\nxlabel('Iteration')\nylabel('$ log_{10}(RMSE) $','interpreter','latex')\n\n%% plot the results\n\n% It is clear that SART will get to better results for the same amoutn of\n% iterations, however, it takes x7 more time to run.\n\n% SART \n% OS-SART\n% SIRT\n\nplotImg([imgSIRT; imgOSSART; imgSART;],'Dim','Z','Savegif','sarts.gif');\n\n% plot error\nplotImg(abs([head-imgSIRT; head-imgOSSART; head-imgSART; ]),'Dim','Z');\n\n\n\n ", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Demos/d07_Algorithms02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6228834973094957}} {"text": "function hermite_cubic_test10 ( )\n\n%*****************************************************************************80\n%\n%% HERMITE_CUBIC_TEST10 tests HERMITE_CUBIC_SPLINE_INTEGRAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_CUBIC_TEST10:\\n' );\n fprintf ( 1, ' HERMITE_CUBIC_SPLINE_INTEGRAL integrates a Hermite\\n' );\n fprintf ( 1, ' cubic spline over the definition interval [X1,XNN].\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' If the subintervals are equally spaced, the derivative\\n' );\n fprintf ( 1, ' information has no effect on the result, except for\\n' );\n fprintf ( 1, ' the first and last values, DN(1) and DN(NN).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Exact Computed\\n' );\n fprintf ( 1, ' X1 XNN Integral Integral Comment\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : 5\n%\n% Equal spacing.\n%\n if ( test == 1 )\n nn = 11;\n xn = linspace ( 0.0, pi, nn );\n fn = sin ( xn );\n dn = cos ( xn );\n integral_exact = - cos ( xn(nn) ) + cos ( xn(1) );\n comment = 'Equal spacing, correct DN';\n%\n% Equal spacing, reset DN(2:NN-1) to random numbers.\n%\n elseif ( test == 2 )\n nn = 11;\n xn = linspace ( 0.0, pi, nn );\n fn = sin ( xn );\n dn = cos ( xn );\n [ dn(2:nn-1), seed ] = r8vec_uniform_01 ( nn - 2, seed );\n dn(2:nn-1) = 1000.0 * dn(2:nn-1);\n integral_exact = - cos ( xn(nn) ) + cos ( xn(1) );\n comment = 'Equal spacing, DN(2:N-1) random';\n%\n% Equal spacing, now reset all of DN to random numbers.\n%\n elseif ( test == 3 )\n\n nn = 11;\n xn = linspace ( 0.0, pi, nn );\n fn = sin ( xn );\n [ dn, seed ] = r8vec_uniform_01 ( nn, seed );\n dn(1:nn) = 1000.0 * dn(1:nn);\n integral_exact = - cos ( xn(nn) ) + cos ( xn(1) );\n comment = 'Equal spacing, DN(1:N) random';\n%\n% Variable spacing, correct data.\n%\n elseif ( test == 4 )\n nn = 11;\n xn = linspace ( 0.0, pi^2, nn );\n xn = sqrt ( xn );\n fn = sin ( xn );\n dn = cos ( xn );\n integral_exact = - cos ( xn(nn) ) + cos ( xn(1) );\n comment = 'Variable spacing, correct DN';\n%\n% Variable spacing, change one entry in DN.\n%\n elseif ( test == 5 )\n nn = 11;\n xn = linspace ( 0.0, pi^2, nn );\n xn = sqrt ( xn );\n fn = sin ( xn );\n dn = cos ( xn );\n [ r, seed ] = r8_uniform_01 ( seed );\n dn( floor ( nn + 1 ) / 2 ) = 1000.0 * r;\n integral_exact = - cos ( xn(nn) ) + cos ( xn(1) );\n comment = 'Variable spacing, a single internal DN randomized.';\n end\n\n integral_computed = hermite_cubic_spline_integral ( nn, xn, fn, dn );\n\n fprintf ( 1, ' %10f %10f %10.6g %10.6g %s\\n', ...\n xn(1), xn(nn), integral_exact, integral_computed, comment );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hermite_cubic/hermite_cubic_test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6228329128583703}} {"text": "function [x_best, psi_best, out] = CSDF(mapp, x0, options)\n% CSDF is a derivative-free algorithm for solving systems of nonlinear\n% equations :math:`f(x) = 0`, x in :math:`R^m`\n% using the nonlinear unconstrained minimization :math:`\\textrm{min}\\ \\psi(x) = 1/2 ||f(x)||^2` s.t. `x` in :math:`R^m`.\n%\n% USAGE:\n%\n% [x_best, psi_best, out] = CSDF(mapp, x0, options)\n%\n% INPUTS:\n% mapp: function handle provides `f(x)` and gradient `f(x)`\n% x0: initial point\n% options: structure including the parameteres of scheme\n%\n% * .MaxNumIter - maximum number of iterations\n% * .MaxNumMapEval - maximum number of function evaluations\n% * .TimeLimit - maximum running time\n% * .epsilon - accuracy parameter\n% * .x_opt - optimizer\n% * .psi_opt - optimum\n% * .sigma - strong duplomonotone parameter\n% * .l - Lipschitz continuity constant of `f`\n% * .tauBar - a constant for determining the step-size\n% * .flag_x_error - 1: saves :math:`x_{error}`, 0: do not saves :math:`x_{error}` (default)\n% * .flag_psi_error - 1:saves :math:`\\psi_{error}`, 0: do not saves :math:`\\psi_{error}` (default)\n% * .flag_time - 1: saves :math:`\\psi_{error}`, 0: do not saves :math:`\\psi_{error}` (default)\n% * .Stopping_Crit - stopping criterion:\n%\n% 1. stop if :math:`||nfxk|| \\leq \\epsilon`\n% 2. stop if `MaxNumIter` is reached\n% 3. stop if `MaxNumMapEval` is reached\n% 4. stop if `TimeLimit` is reached\n% 5. stop if (default) :math:`||hxk|| \\leq \\epsilon` or `MaxNumIter` is reached\n%\n% OUTPUTS:\n% x_best: the best approximation of the optimizer\n% psi_best: the best approximation of the optimum\n% out: structure including more output information\n%\n% * .T - running time\n% * .Niter - total number of iterations\n% * .Nmap - total number of mapping evaluations\n% * .merit_func - array including all merit function values\n% * .x_error - relative error :math:`norm(x_k(:)-x_{opt}(:))/norm(x_{opt})`\n% * .psi_error - relative error :math:`(\\psi_k-\\psi_{opt})/(\\psi_0-\\psi_{opt}))`\n% * .Status - reason of termination\n%\n% .. REFERENCE:\n% .. Algorithm 2 of [1]: F.J. Aragon Artacho, R.M.T. Fleming, Globally convergent algorithms for finding zeros of duplomonotone mappings, Optimization Letter, 9, 569-584 (2015)\n% .. Author: - Masoud Ahookhosh, System Biochemistry Group, Luxembourg Center for System Biomedicine, University of Luxembourg, Luxembourg\n% - Update July 2017 - M. Ahookhosh\n\nformat longG ;\n\n% ================ Error messages for input and output =================\nif nargin > 3\n error('The number of input arguments is more than what is needed');\nelseif nargin < 3\n error('The number of input arguments is not enough');\nend;\n\nif isempty(mapp)\n error('the function handle mapp has to be defined');\nelseif ~isa(mapp,'function_handle')\n error('mapp should be a function handle');\nend\n\nif isempty(x0)\n error('The starting point x0 has to be defined');\nelseif ~isa(x0,'numeric')\n error('x0 should be a numeric vector');\nend\n\n% =================== initializing the parameters ======================\n% ===== user has requested viewing the default values of \"options\" =====\n[MaxNumIter,MaxNumMapEval,TimeLimit,epsilon,alpha, ...\n beta,sigma,l,tauBar,lambda_min,lambda_max,flag_x_error, ...\n flag_psi_error,flag_time,Stopping_Crit] = InitialDuplo(options);\n\nif isfield(options,'x_opt')\n x_opt=options.x_opt;\nelseif flag_x_error==1\n error('x_error requires to x_opt be specified');\nend\n\nif flag_x_error == 1\n Nxopt = sqrt(sum(x_opt(:).^2));\n x_error(1) = sqrt(sum((x0(:)-x_opt(:)).^2))/Nxopt;\nend\n\nif flag_psi_error == 1\n psi_error(1) = 1;\nend\n\nif flag_time == 1\n Time(1) = 0;\nend\n\n\nxk = x0;\nXk = xk;\nNiter = 1;\nfx0 = mapp(x0);\nNmap = 1;\nnfx0 = norm(fx0);\nfxk = fx0;\nnfxk = nfx0;\nmerit_func = 0.5*nfxk^2;\nlambda = min(sigma/l^2,tauBar);\nStopFlag = 0;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%% Main body of CSDF.m %%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nT0 = tic;\n\n% ======================= start of the main loop =======================\nwhile ~StopFlag\n\n xk = xk-lambda*fxk;\n Niter = Niter+1\n fxk = mapp(xk);\n Nmap = Nmap+1;\n nfxk2 = norm(fxk)^2;\n\n % ================= Gathering output information ===================\n psik = 0.5*nfxk2;\n merit_func(Niter) = psik;\n if flag_time == 1\n Time(Niter+1) = toc(T0);\n end\n\n if flag_x_error == 1\n Nx_opt = norm(x_opt);\n x_error(Niter+1) = sqrt(sum((xk(:)-x_opt(:)).^2))/Nx_opt;\n end\n\n if flag_psi_error == 1\n psi_error(Niter+1) = (psik-psi_opt)/(psi0-psi_opt);\n end\n\n\n % ================== checking stopping criteria ====================\n T = toc(T0);\n\n [StopFlag,Status] = StopCritDuplo(nfxk,Niter,Nmap,T, ...\n MaxNumIter,MaxNumMapEval,TimeLimit,epsilon,Stopping_Crit);\n\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Outputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nStatus\nx_best = xk;\npsi_best = psik;\nout.Xk = Xk;\nout.T = T;\nout.nhx = nfxk;\nout.merit_func = merit_func';\nout.Niter = Niter;\nout.Nmap = Nmap;\nout.Status = Status;\n\nif flag_x_error == 1\n out.x_error = x_error;\nend\nif flag_psi_error == 1\n out.psi_error = psi_error;\nend\nif flag_time == 1\n out.Time = Time;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of CSDF.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/solvers/varKin/derFreeMethods/CSDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6228274254428569}} {"text": "function [xi, em, gx, gy] = surface_interpolation(x, PARAM, INTERP, res, KLIM, nlev)\n% surface_interpolation Interpolate a surface from a scattered set of points\n%\n% [XI, EM, GX, GY] = surface_interpolation(X)\n%\n% X is a 3-row matrix. Each column has the coordinates of a point that\n% belongs to the surface we want to interpolate.\n%\n% XI is a 3-row matrix with the coordinates of the interpolated points.\n%\n% EM is a 2-row matrix with the coordinates of the X points projected\n% onto the interpolation domain. Note that the interpolation domain may\n% change between methods, so don't expect results to be aligned if you do\n% e.g. plot3(gx(:), gy(:), y(:, 3), 'o').\n%\n% GX, GY are the grid for the box that contains EM.\n%\n% ... = surface_interpolation(X, PARAM, INTERP, RES, KLIM, NLEV)\n%\n% PARAM is a string with the method used to parametrize the surface and\n% X:\n%\n% 'xy' (default): No change, the X coordinates are kept the same.\n%\n% 'pca': X points are rotated according to their eigenvectors to make\n% the dominant plane of the points X as horizontal as possible before\n% interpolating.\n%\n% 'isomap': Use the Isomap method by [1] to \"unfold\" the curved surface\n% defined by X before interpolating. (This option requires function\n% IsomapII).\n%\n% INTERP is a string with the interpolation method:\n%\n% 'tps' (default): Thin-plate spline. Global support.\n%\n% 'tsi': Matlab's TriScatteredInterp() function. Local support,\n% limited to the convex hull of the scattered points 2D projection on\n% the interpolation domain.\n%\n% 'gridfit': John D'Errico's gridfit() function [3] (note:\n% approximation, rather than interpolation). Local support with\n% extrapolation outside the convex hull.\n%\n% 'mba': Multilevel B-Spline Approximation Library by SINTEF ICT [4].\n% Local support, limited to a rectangle that tighly contains the\n% scattered points 2D projection on the interpolation domain.\n%\n% 'mbae': Like the 'mba' method, but first a thin-plate spline is used \n% to extrapolate values on the interpolation domain boundary. Then MBA\n% is used for the local support interpolation of X and the boundary\n% values set by the thin-plate spline.\n%\n% RES is a 2-vector with the grid spacing in the x- and y-directions. By\n% default, RES=[1 1].\n%\n% KLIM is a scalar factor for the extension of the interpolation domain.\n% By default, KLIM=1 and the interpolation domain is a rectangle that\n% tightly contains X. Sections of the interpolated surface that protude\n% from the image volume are removed.\n%\n% NLEV is the number of levels in the hierarchical construction of 'mba'\n% and 'mbae'. For other INTERP options, it will be ignored. By default,\n% NLEV = 7.\n%\n%\n% [1] J.B. Tenenbaum, V. de Silva and J.C. Langford, \"A Global Geometric\n% Framework for Nonlinear Dimensionality Reduction\", Science 290(5500):\n% 2319-2323, 2000.\n%\n% [2] Isomap Homepage, http://isomap.stanford.edu/\n%\n% [3] Surface Fitting using gridfit by John D'Errico 11 Nov 2005 (Updated\n% 29 Jul 2010). Code covered by the BSD License\n% http://www.mathworks.com/matlabcentral/fileexchange/8998-surface-fitting-using-gridfit\n%\n% [4] MBA - Multilevel B-Spline Approximation Library\n% http://www.sintef.no/Projectweb/Geometry-Toolkits/MBA/\n\n% Author: Ramon Casero \n% Copyright © 2010-2011 University of Oxford\n% Version: 0.2.0\n% $Rev: 782 $\n% $Date: 2012-06-02 22:55:03 +0100 (Sat, 02 Jun 2012) $\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n% check arguments\nerror(nargchk(2, 6, nargin, 'struct'));\nerror(nargoutchk(0, 4, nargout, 'struct'));\n\n% defaults\nif (nargin < 2 || isempty(PARAM))\n PARAM = 'xy';\nend\nif (nargin < 3 || isempty(INTERP))\n INTERP = 'tps';\nend\nif (nargin < 4 || isempty(res))\n res = [1 1];\nend\nif (nargin < 5 || isempty(KLIM))\n KLIM = 1;\nend\nif (nargin > 5 && ~isempty(nlev) ...\n && ~(strcmp(INTERP, 'mba') || strcmp(INTERP, 'mbae')))\n warning('NLEV input argument ignored for this INTERP option')\nend\nif (nargin < 6 || isempty(nlev))\n nlev = 7;\nend\n\n%% map the 3D points (x,y,z) to a 2D domain (u,v)\n\n% this is analogous to computing the knot vector for a curve interpolation.\n% The idea is that (x,y)->z is not necessarily a function, due to the valve\n% folding over. However, we hope that (u,v)->(x,y,z) is a function\nswitch PARAM\n \n case 'xy'\n \n % (u,v) is simply (x,y)\n em = x(1:2, :);\n \n case 'pca'\n \n % rotate valve points to make the valve surface as horizontal as\n % possible\n m = mean(x, 2);\n em = x - m(:, ones(1, size(x, 2)));\n eigv = pts_pca(em);\n if any(isnan(eigv(:)))\n error('Cannot interpolate surface');\n end\n em = eigv' * em;\n em = em(1:2, :);\n \n case 'isomap'\n \n % compute distance matrix\n d = dmatrix(x, x, 'euclidean');\n \n % compute 2-d projection of the 3-d data\n options.dims = 2;\n options.display = 0;\n options.overlay = 0;\n options.verbose = 0;\n em = IsomapII(d, 'k', round(size(x, 2)/3), options);\n em = em.coords{1};\n \n otherwise\n error('Parametrization method not implemented')\nend\n\n%% compute interpolation domain\n\n% find box that contains embedded coordinates\nemmin = min(em, [], 2);\nemmax = max(em, [], 2);\n\n% box size and centroid\ndelta = emmax - emmin;\nboxm = mean([emmax emmin], 2);\n\n% extend the box\nemmin = boxm - delta/2*KLIM;\nemmax = boxm + delta/2*KLIM;\n\n% generate grid for the embedding box\n[gy, gx] = ndgrid(emmin(2):res(1):emmax(2), emmin(1):res(2):emmax(1));\n\n\n%% compute interpolating surface\n\n% source and target points that will define the warp\n%s = em; % don't duplicate data in memory\n%t = x; % don't duplicate data in memory\n\n% interpolate\nswitch INTERP\n case 'tps' % thin-plate spline\n xi = pts_tps_map(em', x', [gx(:) gy(:)]);\n case 'tsi' % Matlab's TriScatteredInterp\n fx = TriScatteredInterp(em(1, :)', em(2, :)', x(1, :)', 'natural');\n fy = TriScatteredInterp(em(1, :)', em(2, :)', x(2, :)', 'natural');\n fz = TriScatteredInterp(em(1, :)', em(2, :)', x(3, :)', 'natural');\n fx = fx(gx, gy);\n fy = fy(gx, gy);\n fz = fz(gx, gy);\n xi = [fx(:) fy(:) fz(:)];\n case 'gridfit'\n fx = gridfit(em(1, :)', em(2, :)', x(1, :)', ...\n emmin(1):res(2):emmax(1), emmin(2):res(1):emmax(2), ...\n 'tilesize', 150);\n fy = gridfit(em(1, :)', em(2, :)', x(2, :)', ...\n emmin(1):res(2):emmax(1), emmin(2):res(1):emmax(2), ...\n 'tilesize', 150);\n fz = gridfit(em(1, :)', em(2, :)', x(3, :)', ...\n emmin(1):res(2):emmax(1), emmin(2):res(1):emmax(2), ...\n 'tilesize', 150);\n xi = [fx(:) fy(:) fz(:)];\n case 'mba' % Multilevel B-Spline Approximation Library\n xi = [...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(1, :)', gx(:), gy(:), nlev) ...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(2, :)', gx(:), gy(:), nlev) ...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(3, :)', gx(:), gy(:), nlev)];\n case 'mbae' % MBA extrapolated using a TPS\n % use TPS to interpolate the points, but we are only interested in\n % the edges and corners of the interpolation, where the TPS is\n % extrapolating linearly; also, we decimate the points in the edges\n em2 = [gx(1, 1:end)' gy(1, 1:end)' ; ... % top edge\n gx(2:end, end) gy(2:end, end) ; ... % right edge\n gx(end, 1:end-1)' gy(end, 1:end-1)' ; ... % bottom edge\n gx(2:end-1, 1) gy(2:end-1, 1) ; ... % left edge\n ]';\n xi = pts_tps_map(em', x', em2')';\n x = [x xi(:, 1:10:end)];\n % local support interpolation with boundary conditions provided by\n % the TPS\n em = [em em2(:, 1:10:end)];\n xi = [...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(1, :)', gx(:), gy(:), nlev) ...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(2, :)', gx(:), gy(:), nlev) ...\n mba_surface_interpolation(em(1, :)', em(2, :)', x(3, :)', gx(:), gy(:), nlev)];\n otherwise\n error('Interpolation method not implemented')\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/gerardus/matlab/PointsToolbox/surface_interpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.622827420450846}} {"text": "function ttf = friedman_test(n_problem, r, n)\n%FRIEDMAN regression\n\nfun = @(i, j, x) x^(j-1);\n\nif n_problem == 1\n %Friedman 1\n d = 10;\n N = 20000;\n x = rand(d,N);\n y = 10*sin(pi*x(1,:).*x(2,:)) + 20*(x(3,:) - 0.5*ones(1,N)).^2 + 10*x(4,:) + 5*x(5,:);\n \n tt_rank = [1 ; r*ones(d-1,1) ; 1];\n n_basis = n*ones(d,1);\n basis_ps = cumsum([1 ; n_basis*N]);\n basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);\n for dim = 1: d\n t = zeros(n, N);\n for i = 1: n\n t(i,:) = x(dim,:).^(i-1);\n end\n basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);\n end\nelseif n_problem == 2\n %Friedman 2\n d = 4;\n N = 20000;\n x = rand(d,N);\n x1 = x(1,:)*100;\n x2 = x(2,:)*520*pi + 40*pi*ones(1,N);\n x3 = x(3,:);\n x4 = x(4,:)*10 + ones(1,N);\n y = sqrt(x1.^2 + (x2.*x3 - 1./(x2.*x4)).^2);\n \n tt_rank = [1 ; r*ones(d-1,1) ; 1];\n n_basis = n*ones(d,1);\n basis_ps = cumsum([1 ; n_basis*N]);\n basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);\n for dim = 1: d\n t = zeros(n, N);\n for i = 1: n\n t(i,:) = x(dim,:).^(i-1);\n end\n basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);\n end\nelse\n %Friedman 3\n d = 4;\n N = 20000;\n x = rand(d,N);\n x1 = x(1,:)*100;\n x2 = x(2,:)*520*pi + 40*pi*ones(1,N);\n x3 = x(3,:);\n x4 = x(4,:)*10 + ones(1,N);\n y = atan((x2.*x3 - 1./(x2.*x4))./x1);\n \n tt_rank = [1 ; r*ones(d-1,1) ; 1];\n n_basis = n*ones(d,1);\n basis_ps = cumsum([1 ; n_basis*N]);\n basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);\n for dim = 1: d\n t = zeros(n, N);\n for i = 1: n\n t(i,:) = x(dim,:).^(i-1);\n end\n basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);\n end\nend\n\ncoeff = reg_als(basis_cr, y, tt_rank, n_basis);\nttf = tt_function(fun, coeff);\n\nend\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tt_regression/friedman_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6228043828470786}} {"text": "%converts frequency to mel\n%>\n%> @param fMel: frequency\n%> @param cModel: 'Fant','Shaughnessy', or 'Umesh'\n%>\n%> @retval Hertz value\n% ======================================================================\nfunction [fInHz] = ToolMel2Freq(fMel, cModel)\n\n if (nargin < 2)\n cModel = 'Fant';\n end\n\n % set function handle\n hPitchFunc = str2func (['aca' cModel '_I']);\n \n fInHz = hPitchFunc(fMel);\nend\n\nfunction [f] = acaFant_I(m)\n %mel = 1000 * log2(1 + f/1000);\n f = 1000 * (2.^(m/1000)-1);\nend\n\nfunction [f] = acaShaughnessy_I(m)\n %mel = 2595 * log10(1 + f/700);\n f = 700 * (10.^(m/2595)-1);\nend\n\nfunction [f] = acaUmesh_I(m)\n %mel = f./(2.4e-4*f + 0.741);\n f = m*.741 ./ (1 - m * 2.4e-4);\nend", "meta": {"author": "alexanderlerch", "repo": "ACA-Code", "sha": "85d7258d5fcee1ca52bac52f651d26b665717687", "save_path": "github-repos/MATLAB/alexanderlerch-ACA-Code", "path": "github-repos/MATLAB/alexanderlerch-ACA-Code/ACA-Code-85d7258d5fcee1ca52bac52f651d26b665717687/ToolMel2Freq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.6228043817506664}} {"text": "function [nQb, pos, vel, q] = ins(w_b, f_b, nQb, pos, vel, gravity, dt)\n%% 捷联更新\nrotate_vector = w_b*dt;\nrotate_vector_norm = norm(rotate_vector);\nif(rotate_vector_norm <1e-10) % fix nan issue\n q = [1 0 0 0];\nelse\n q = [cos(rotate_vector_norm/2); rotate_vector/rotate_vector_norm*sin(rotate_vector_norm/2)]';\nend\n\n% 姿态更新\nnQb = ch_qmul(nQb, q); %四元数更新(秦永元《惯性导航(第二版)》P260公式9.3.3)\nnQb = ch_qnormlz(nQb); %单位化四元数\n\n% 速度更新\nf_n = ch_qmulv(nQb, f_b);\ndv = (f_n + [0; 0; -gravity]); %比力方程\nvel = vel + dv*dt;\n\n% 位置更新\npos = pos + vel*dt;\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/eskf156/ins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6227833629228002}} {"text": "function [z_Tji_Ground_m,r_I_IRji_m,r_I_ITji_m] = Rotation_Position_ToTireFixed(z_I_Ground_m,A_K_I,A_F_I,r_I_IAji_m,h_ji_m,re_ji_m)\n%% Rotation ground displacement from inertial fixed coordinate system into tire fixed coordinate systems\n% Input parameters:\n% A_K_I [---] Rotation Matrix from Inertial Frame to VehicleFixed Frame\n% A_F_I [---] Rotation Matrix from Inertial Frame to RearAxleFixed Frame\n% h_ji_m [m] Suspension Height [SuspHFL SuspHFR SuspHRL SuspHRR]\n% re_ji_m [m] Effective Wheel Radii [ReFL ReFR ReRL ReRR]\n% r_I_IAji [m] Absolut Position of Axles in Inertial Reference Frame [r_I_IAFL r_I_IAFR r_I_IARL r_I_IARR] [3x4]\n% z_Ground_I_m [---] z-Coordinate of Road Displacement in Inertial Reference Frame [1x4]\n% Output parameters:\n% z_Ground_Tji_m [---] Transformed Displacement Vector [r_TFL_ITFL r_TFR_ITFR r_TRL_ITRL r_TRR_ITRR] [1x4]\n\n%% Wheel center points in inertial reference frame\n\n% Quarter Vehicle Model along VehicleFixed z-Axis: Rotation from VehicleFixed Axis System into Inertial Frame\n% r_I_IRji_m = [(r_I_IAji_m(:,1) + transpose(A_K_I)*[0;0;1]*(h_ji_m(1))) (r_I_IAji_m(:,2) + transpose(A_K_I)*[0;0;1]*(h_ji_m(2))) (r_I_IAji_m(:,3) + transpose(A_K_I)*[0;0;1]*(h_ji_m(3))) (r_I_IAji_m(:,4) + transpose(A_K_I)*[0;0;1]*(h_ji_m(4)))];\n\n% Quarter Vehicle Model along RearAxleFixed z-Axis: Rotation from RearAxleFixed Axis System into Inertial Frame\nr_I_IRji_m = [(r_I_IAji_m(:,1) + transpose(A_F_I)*[0;0;1]*(h_ji_m(1))) (r_I_IAji_m(:,2) + transpose(A_F_I)*[0;0;1]*(h_ji_m(2))) (r_I_IAji_m(:,3) + transpose(A_F_I)*[0;0;1]*(h_ji_m(3))) (r_I_IAji_m(:,4) + transpose(A_F_I)*[0;0;1]*(h_ji_m(4)))];\n\n%% Contact points of road-tire-interface in inertial reference frame\n\n% Quarter Vehicle Model along VehicleFixed z-Axis: Rotation from VehicleFixed Axis System into Inertial Frame\n% r_I_ITji_m = [(r_I_IAji_m(:,1) + transpose(A_K_I)*[0;0;1]*(re_ji_m(1)+h_ji_m(1))) (r_I_IAji_m(:,2) + transpose(A_K_I)*[0;0;1]*(re_ji_m(2)+h_ji_m(2))) (r_I_IAji_m(:,3) + transpose(A_K_I)*[0;0;1]*(re_ji_m(3)+h_ji_m(3))) (r_I_IAji_m(:,4) + transpose(A_K_I)*[0;0;1]*(re_ji_m(4)+h_ji_m(4)))];\n\n% Quarter Vehicle Model along RearAxleFixed z-Axis: Rotation from RearAxleFixed Axis System into Inertial Frame\nr_I_ITji_m = [(r_I_IAji_m(:,1) + transpose(A_F_I)*[0;0;1]*(re_ji_m(1)+h_ji_m(1))) (r_I_IAji_m(:,2) + transpose(A_F_I)*[0;0;1]*(re_ji_m(2)+h_ji_m(2))) (r_I_IAji_m(:,3) + transpose(A_F_I)*[0;0;1]*(re_ji_m(3)+h_ji_m(3))) (r_I_IAji_m(:,4) + transpose(A_F_I)*[0;0;1]*(re_ji_m(4)+h_ji_m(4)))];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %% Elaborate Computation of Vertical Displacement \n% % The computation of the position vector of the road-tire interface\n% % requires information about the rx_I_ITji_m and ry_I_ITji_m coordinates of the\n% % road-tire-interface relative to the inertial frame and the vertical\n% % displacement z_Ground_I_m.\n% \n% %% Position Vector of Road-Tire-Interface around Orientation of the Quarter Vehicle Model\n% \n% % Extracting (x,y)-Coordinates of r_I_ITji_m\n% % rx_I_ITji_m = r_I_ITji_m(1,:);\n% % ry_I_ITji_m = r_I_ITji_m(2,:);\n% % \n% % Quarter Vehicle Model along VehicleFixed z-Axis: Rotation from Inertial Frame into VehicleFixed Axis System\n% r_Ground_m = A_K_I*vertcat(rx_I_ITji_m,ry_I_ITji_m,+z_Ground_I_m);\n% \n% % Quarter Vehicle Model along RearAxleFixed z-Axis: Rotation from Inertial Frame into RearAxleFixed Axis System\n% r_Ground_m = A_F_I*vertcat(rx_I_ITji_m,ry_I_ITji_m,+z_Ground_I_m);\n% \n% %% Orientation Change from z-down-Orientation to z-up-Orientation\n% z_Ground_Tji_m = -r_Ground_m(3,:);\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Robust Computation of Vertical Displacement \n% A more robust computation of the Vertical Displacement is possible with\n% the simplified z-displacement vector [0;0;1]*z_Ground_I_m under\n% neglection of the rx_I_ITji_m and ry_I_ITji_m coordinates of the\n% road-tire-interface relative to the inertial frame.\n\n%% Vertical z-Displacement of Road-Tire-Interface around Orientation of the Quarter Vehicle Model\n\n% Quarter Vehicle Model along VehicleFixed z-Axis: Rotation from Inertial Frame into VehicleFixed Axis System\n% r_Ground_m = A_K_I*[0;0;1]*z_Ground_I_m;\n\n% Quarter Vehicle Model along RearAxleFixed z-Axis: Rotation from Inertial Frame into RearAxleFixed Axis System\nr_Ground_m = A_F_I*[0;0;1]*z_I_Ground_m;\n\n%% Orientation Change from z-down-Orientation to z-up-Orientation\nz_Tji_Ground_m = -r_Ground_m(3,:);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend\n\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/Rotation_Position_ToTireFixed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6227692137434457}} {"text": "function [F, G] = F_update(upd, DCMbn, imu)\n% F_update: updates F and G matrices before the execution of Kalman filter.\n%\n% INPUT\n% upd, 1x8 vector with data from the INS.\n% DCMbn, DCM body-to-nav.\n% imu, IMU data structure.\n%\n% OUTPUT\n% F, 15x15 state transition matrix.\n% G, 15x12 control-input matrix.\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n%\n% Groves, P.D. (2013), Principles of GNSS, Inertial, and\n% Multisensor Integrated Navigation Systems (2nd Ed.). Artech House. \n% Matrix F from Eq. 14.63.\n%\n% \tFarrell, J. (2008). Aided Navigation: GPS With High Rate\n% Sensors. McGraw-Hill Professional, USA. Matrix G from Eq. 11.108.\n%\n% Version: 010\n% Date: 2022/03/06\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nVn = upd(1);\nVe = upd(2);\nVd = upd(3);\nlat = upd(4);\nh = upd(5);\n\nfn = upd(6:8);\n% wn = upd(9:11);\n\nOm = 7.292115e-5;\nI = eye(3);\nZ = zeros(3);\n\n[RM,RN] = radius(lat);\n\nRO = sqrt(RN*RM) + h;\n\n%% ATTITUDE MATRICES\n\na11 = 0;\na12 = -( (Om * sin(lat)) + (Ve / RO * tan(lat)) );\na13 = Vn / RO;\na21 = (Om * sin(lat)) + (Ve / RO * tan(lat));\na22 = 0 ;\na23 = (Om * cos(lat)) + (Ve / RO) ;\na31 = -Vn / RO;\na32 = -Om * cos(lat) - (Ve / RO);\na33 = 0;\nF11 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\n% Groves, 14.64\n% F11 = skewm(wn);\n\na11 = 0;\na12 = 1 / RO;\na13 = 0;\na21 = -1 / RO;\na22 = 0;\na23 = 0;\na31 = 0;\na32 = -tan(lat) / RO;\na33 = 0;\nF12 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\na11 = -Om * sin(lat);\na12 = 0;\na13 = -Ve / (RO^2);\na21 = 0 ;\na22 = 0 ;\na23 = Vn / (RO^2);\na31 = -Om * cos(lat) - (Ve / ((RO) * (cos(lat))^2));\na32 = 0 ;\na33 = (Ve * tan(lat)) / (RO^2) ;\nF13 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\n%% VELOCITY MATRICES\n\nF21 = skewm(fn);\n\na11 = Vd / RO;\na12 = -2 * ((Om * sin(lat)) + ((Ve / RO) * tan(lat))) ;\na13 = Vn / RO ;\na21 = (2 * Om * sin(lat)) + ( (Ve / RO) * tan(lat) );\na22 = (1 / RO) * ((Vn * tan(lat)) + Vd) ;\na23 = 2 * Om * cos(lat) + (Ve / RO);\na31 = (-2 * Vn) / RO;\na32 = -2 * (Om * cos(lat) + (Ve / RO)) ;\na33 = 0;\nF22 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\ne = 0.0818191908425; % WGS84 eccentricity\nres = RN * sqrt( cos(lat)^2 + (1-e^2)^2 * sin(lat)^2);\ng = gravity(lat,h);\ng0 = g(3);\n\na11 = -Ve * ((2 * Om * cos(lat)) + (Ve / (RO * (cos(lat))^2)));\na12 = 0 ;\na13 = (1 / RO^2) * ( (Ve^2 * tan(lat)) - (Vn * Vd) );\na21 = 2 * Om * ( (Vn * cos(lat)) - (Vd * sin(lat)) ) + ( (Vn * Ve) / (RO * (cos(lat))^2) ) ;\na22 = 0 ;\na23 = -(Ve / RO^2) * (Vn * tan(lat) + Vd);\na31 = 2 * Om * Ve * sin(lat);\na32 = 0;\n% a33 = (1 / RO^2) * (Vn^2 + Ve^2);\na33 = Ve^2 / (RN+h)^2 + Vn^2 / (RM+h)^2 - 2 * g0 / res;\nF23 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\n%% POSITIONING MATRICES\n\nF31 = zeros(3);\n\na11 = 1 / RO;\na12 = 0;\na13 = 0;\na21 = 0;\na22 = 1 / (RO * cos(lat));\na23 = 0;\na31 = 0;\na32 = 0;\na33 = -1;\nF32 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\na11 = 0;\na12 = 0;\na13 = -Vn / RO^2;\na21 = (Ve * tan(lat)) / (RO * cos(lat));\na22 = 0;\na23 = -Ve / (RO^2 * cos(lat));\na31 = 0;\na32 = 0;\na33 = 0;\nF33 = [a11 a12 a13; a21 a22 a23; a31 a32 a33;];\n\nFbg = I;\nFba = I;\n\nif (isinf(imu.gb_corr))\n Fgg = Z;\nelse\n Fgg = -diag( 1./ imu.gb_corr);\n % Fbg = -diag(sqrt (2 ./ imu.gb_corr .* imu.gb_dyn.^2));\nend\n\nif (isinf(imu.ab_corr))\n Faa = Z;\nelse\n Faa = -diag(1 ./ imu.ab_corr);\n % Fba = -diag(sqrt (2 ./ imu.ab_corr .* imu.ab_dyn.^2));\nend\n\n% Eq. 14.63 from Groves\nF = [F11 F12 F13 DCMbn Z ;\n F21 F22 F23 Z DCMbn ;\n F31 F32 F33 Z Z ;\n Z Z Z Fgg Z ;\n Z Z Z Z Faa ;\n ];\n\n% Eq. 11.108 from Farrell\nG = [DCMbn Z Z Z ;\n Z DCMbn Z Z ;\n Z Z Z Z ;\n Z Z Fbg Z ;\n Z Z Z Fba ;\n ];\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/ins-gnss/F_update.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.6226457623490682}} {"text": "function [y,e] = powspec(x, sr, wintime, steptime, dither)\n%[y,e] = powspec(x, sr, wintime, steptime, sumlin, dither)\n%\n% compute the powerspectrum and frame energy of the input signal.\n% basically outputs a power spectrogram\n%\n% each column represents a power spectrum for a given frame\n% each row represents a frequency\n%\n% default values:\n% sr = 8000Hz\n% wintime = 25ms (200 samps)\n% steptime = 10ms (80 samps)\n% which means use 256 point fft\n% hamming window\n%\n% $Header: /Users/dpwe/matlab/rastamat/RCS/powspec.m,v 1.3 2012/09/03 14:02:01 dpwe Exp dpwe $\n\n% for sr = 8000\n%NFFT = 256;\n%NOVERLAP = 120;\n%SAMPRATE = 8000;\n%WINDOW = hamming(200);\n\nif nargin < 2\n sr = 8000;\nend\nif nargin < 3\n wintime = 0.025;\nend\nif nargin < 4\n steptime = 0.010;\nend\nif nargin < 5\n dither = 1;\nend\n\nwinpts = round(wintime*sr);\nsteppts = round(steptime*sr);\n\nNFFT = 2^(ceil(log(winpts)/log(2)));\n%WINDOW = hamming(winpts);\n%WINDOW = [0,hanning(winpts)'];\nWINDOW = [hanning(winpts)'];\n% hanning gives much less noisy sidelobes\nNOVERLAP = winpts - steppts;\nSAMPRATE = sr;\n\n% Values coming out of rasta treat samples as integers, \n% not range -1..1, hence scale up here to match (approx)\ny = abs(specgram(x*32768,NFFT,SAMPRATE,WINDOW,NOVERLAP)).^2;\n\n% imagine we had random dither that had a variance of 1 sample \n% step and a white spectrum. That's like (in expectation, anyway)\n% adding a constant value to every bin (to avoid digital zero)\nif (dither)\n y = y + winpts;\nend\n% ignoring the hamming window, total power would be = #pts\n% I think this doesn't quite make sense, but it's what rasta/powspec.c does\n\n% that's all she wrote\n\n% 2012-09-03 Calculate log energy - after windowing, by parseval\ne = log(sum(y));\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/matlabCode/bark_domain_exploration/rastamat/powspec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.6225459277169196}} {"text": "function p = lbfgsbprod(H,g)\n%lbfgshprod computes products with the L-BFGS matrix B.\n%\n% p = lbfgsbprod(H,g) returns p = B*g.\n%\n% The product is computed using the factoriation\n% [(9.15),p.231] described in Nocedal and Wright, 1999.\n\n% See also lbfgsadd, lbfgsdel, lbfgsupdate, lbfgsinit.\n\n% $Id$\n\n% ----------------------------------------------------------------------\n% Explicit matrix formulation\n% ----------------------------------------------------------------------\n\n%jMax = H.jMax;\n%jNew = H.jNew;\n%jOld = H.jOld;\n\n% |---|---|---|---|---|\n% ^ ^\n% | |\n% old new\n% 4 5 1 2 3 1=newest, 2=2nd newest,... 5=oldest\n\n%if false\n% Sk = H.S(:,[jNew-1:-1:1,jMax:-1:jNew]);\n% Yk = H.Y(:,[jNew-1:-1:1,jMax:-1:jNew]);\n% Lk = (Sk' * Yk) .* (repmat((1:jMax)',1,jMax) > repmat((1:jMax),jMax,1)) ;\n% Dk = diag(sum(Sk.*Yk));\n\n% deltak = H.delta;\n\n% M = [deltak*Sk'*Sk, Lk; Lk', -Dk];\n\n% p = [deltak*Sk'; Yk'] * g;\n% p = M \\ p;\n% p = [deltak*Sk, Yk] * p;\n% p = deltak * g - p;\n%end\n\n% ----------------------------------------------------------------------\n% Formulation directly based on arrays in permuted form :-)\n% ----------------------------------------------------------------------\n\nif ~isempty(H.ML)\n\n % This code works much faster for larger problems\n v1 = H.delta * (g' * H.S)';\n v2 = (g' * H.Y)';\n p = [v1(H.valid); v2(H.valid)];\n\n% v1 = H.delta * (g' * H.S(:,H.valid))';\n% v2 = (g' * H.Y(:,H.valid))';\n% q = [v1; v2];\n\n p = H.MU \\ (H.ML \\ p); % H.M \\ p (optionally: use linsolve)\n\n% v1 = H.S(:,H.valid) * p(1:H.rank) * H.delta;\n% v2 = H.Y(:,H.valid) * p(H.rank+1:2*H.rank); \n% q = v1 + v2;\n\n % This code works much faster for larger problems\n pe = zeros(size(H.S,2),1); pe(H.valid) = p(1:H.rank);\n v1 = H.S * (pe * H.delta);\n pe = zeros(size(H.Y,2),1); pe(H.valid) = p(H.rank+1:2*H.rank);\n v2 = H.Y * pe; \n p = v1 + v2;\nelse\n p = 0;\nend\n\np = H.delta * g - p;", "meta": {"author": "mpf", "repo": "spgl1", "sha": "361a5980667288857e4f4f84c53b536ddfac1d53", "save_path": "github-repos/MATLAB/mpf-spgl1", "path": "github-repos/MATLAB/mpf-spgl1/spgl1-361a5980667288857e4f4f84c53b536ddfac1d53/private/lbfgsbprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6225421812741021}} {"text": "function zz=lpcss2zz(ss)\n%LPCSS2ZZ Convert s-place poles to z-plane poles ZZ=(SS)\n%the s-plane is in units of Normalized Hz and so the imaginary part\n% of each ss() value is in the range +-0.5\n%\n% If you multiply ss by the sample frequency, a formant with\n% frequency f and bandwidth b will give an s-plane pole-pair\n% of approximately -b/2 +- j f\n\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: lpcss2zz.m,v 1.4 2007/05/04 07:01:39 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nzz=exp(2*pi*ss);\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/lpcss2zz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6225421751679215}} {"text": "function [Q, R, E] = qr(f, varargin)\n%QR QR factorisation of an array-valued BNDFUN.\n% [Q, R] = QR(F) returns a QR factorisation of F such that F = Q*R, where the\n% BNDFUN Q is orthogonal (with respect to the continuous L^2 norm on the\n% domain of F) and of the same size as F and R is an m x m upper-triangular\n% matrix when F has m columns.\n%\n% [Q, R, E] = QR(F) produces unitary Q, upper-triangular R, and a permutation\n% matrix E so that F*E = Q*R. The column permutation E is chosen to reduce\n% fill-in in R.\n%\n% [Q, R, E] = QR(F, 'vector') returns the permutation information as a vector\n% instead of a matrix. That is, E is a row vector such that F(:,E) = Q*R.\n% Similarly, [Q, R, E] = QR(F, 'matrix') returns a permutation matrix E. This\n% is the default behavior.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\n% Deal with empty case:\nif ( isempty(f) )\n Q = [];\n R = [];\n E = [];\n return\nend\n\n% Initialise Q to be a BNDFUN:\nQ = f;\n\n% Rescaling factor, (b - a)/2.\nrescaleFactor = .5*diff(f.domain);\n\n% Call QR on the ONEFUN of f:\nif ( nargout == 3 )\n [Q.onefun, R, E] = qr(f.onefun, varargin{:});\nelse\n [Q.onefun, R] = qr(f.onefun, varargin{:});\nend\n\n% Rescale so that columns of Q will be orthonormal (rather than orthogonal):\nQ = Q/sqrt(rescaleFactor);\n\n% Rescale R so that f = QR:\nR = R*sqrt(rescaleFactor);\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/@bndfun/qr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.622542173658915}} {"text": "function [Model, Info] = linear_map_sparse_cov_pinv(X,Y,Model,parm)\n% Estimate linear weight matrix for input-output mapping\n% Automatic Relevance Prior for each input dimension\n% is imposed to get sparse weight matrix\n%\n% [Model, Info] = linear_map_sparse_cov_pinv(X,Y,Model,parm)\n%\n% --- Input\n% X : Input data ( M x T )\n% Y : Output data ( N x T )\n% N = # of output\n% M = # of input\n% T = # of data\n%\n% Model : Structure for estimated model\n% Model.SY0 : Output data variance ( 1 x 1 )\n% Model.A0 : (Output data var)/(Input data var) ( 1 x 1 )\n%\n% parm : Structure for learning parameter\n% parm.Ntrain : # of training\n% parm.Nskip : skip # for print\n% parm.a_min : Min value for pruning small variance component\n% parm.Prune : = 1 : Prune small variance & irrelevant input dimension\n%\n% --- Output\n% Model : Structure for estimated model\n% Model.SY : Noise variance ( 1 x 1 )\n% Model.SW : Weight variance ( M x M )\n% Model.W : Weight matrix ( N x M )\n% Model.A : Prior weight variance ( N x M ) ARD hyper parameter\n%\n% Info : Structure for learning process history\n% Info.FE = LP + H : Free energy\n% Info.LP = - (Log error)\n% Info.H = - (# of effective weight parameters)\n%\n% 2007/1/26 Made by M. Sato\n\n% Constants\nMINVAL = 1.0e-15;\nMinCond = 1.0e-10;\n\n% # of total training iteration\nNtrain = parm.Ntrain;\n\nNskip = 100; % skip steps for display info\na_min = 1e-10; % Minimum value for weight pruning\nFdiff = 1e-10; % Threshold for convergence\nNcheck = 100; % Minimum number of training iteration\nFstep = 5; % Free energy convergence check step\nPrune = 1; % Prune mode\n\nif isfield(parm,'Nskip'), Nskip = parm.Nskip; end;\nif isfield(parm,'Fdiff'), Fdiff = parm.Fdiff; end;\nif isfield(parm,'a_min'), a_min = parm.a_min ; end;\nif isfield(parm,'Prune'), Prune = parm.Prune; end;\nif isfield(parm,'Ncheck'), Ncheck = parm.Ncheck; end\nif isfield(parm,'Fstep'),Fstep = parm.Fstep ; end\n\n% # of embedding dimension\nif isfield(parm,'Dtau')\n\tD = parm.Dtau; \n\ttau = parm.Tau;\nelse\n\tD = 1;\n\ttau = 1;\nend\n\n% Dimension\n[M ,Tx ,Nx ]= size(X); % input dim\n[N ,Ty ,Ny ]= size(Y); % output dim\n\nif Nx~=Ny, error('Trial number is different for input & output'); end\nif Tx~=Ty, error('Time sample is different for input & output'); end\n\n% Reshape into 2D matrix\nT = Tx*Nx; % # of data\nX = reshape(X, [M T]);\nY = reshape(Y, [N T]);\n\n% # of stable VB-update in initial training\nif isfield(parm,'Npre_train')\n\tNpre_train = parm.Npre_train;\nelse\n%\tNpre_train = Ntrain;\n%\tNpre_train = 0;\n\tif T >= 2*M*D\n\t\tNpre_train = 0;\n\telseif T >= M*D\n\t\tNpre_train = fix(Ntrain/2);\n\telse\n\t\tNpre_train = Ntrain;\n\tend\nend\nif Npre_train > Ntrain, Npre_train = Ntrain; end;\n\nfprintf('linear map sparse covariance_pinv start\\n')\nfprintf('--- Output Dimension = %d\\n',N)\nfprintf('--- Input Dimension = %d\\n',M)\nfprintf('--- Embedding Dimension = %d\\n',D)\nfprintf('--- Number of trials = %d\\n',Nx)\nfprintf('--- Number of training sample = %d\\n',Tx)\nfprintf('--- Total update iteration = %d (%d)\\n',Ntrain,Npre_train)\n\n% \n% --- Initialization\n% A : Initial variable to use 1st update\n% : 1 x M\n\n% Input/Output variance\nsx = mean(repadd(X, - mean(X,2)).^2, 2);\nsy = mean(repadd(Y, - mean(Y,2)).^2, 2);\n\nA0 = 1./mean(sx);\nSY0 = mean(sy);\n\nif isempty(Model)\n\tA = repmat(A0, [1,M]);\n\tW = zeros(N,M);\n\tSY = SY0;\nelse\n\tA = Model.A ;\t % 1 x M\n\tW = Model.W ; % N x M\n\tSY = mean(Model.SY); % 1 x 1\nend\n\nif isfield(parm,'Ta0') && parm.Ta0 > 0,\n\tTa0 = parm.Ta0;\n\ta0 = parm.a0 * A0;\nelse\n\tTa0 = 0;\n\ta0 = 1;\nend\n\n% --- Initialization by other method ---\n% Model.mode = 'scalar': ARD term = alpha * W^2 \n% Model.mode = 'cov' : ARD term = alpha * W^2 * SY(^-1) \n%\nif isfield(Model, 'mode') && strcmp(Model.mode,'scalar')==1,\n\tfprintf('Old result is used as initial value\\n')\n\tfprintf('Old method = %s\\n', Model.method)\n\tA = sum(A,1)./(sum(SY));\nend\n\nA = max(A,MINVAL);\n\n% Original input dimension\nM_ALL = M;\n\nif isfield(Model,'ix_act')\n\t% Active index\n\tIX_act = Model.ix_act;\n\n\tX = X(IX_act,:); \t% M x T\n\tM = length(IX_act);\nelse\n\tIX_act = 1:M;\nend\n\n% Initial active index\nM_all = M;\nA_all = A/max(A) ;\nix_act_old = 1:M;\n\nix_act = find( A_all > a_min ); % effective indices\nMnew = length(ix_act); \t\t% # of effective input\n\nif Mnew < M,\n % convert to relative index\n jx_act = trans_index(ix_act,ix_act_old,M_all);\n \n M = Mnew;\n A = A(jx_act) ; \t\t\t% 1 x M\n W = W(:,jx_act) ; \t\t% N x M\n\tX \t= X(jx_act,:);\t\t\t% M x T\nend\n\n% Input variance\n%XX = (X * X')/T; \t% M x M\n%YX = (Y * X')/T; % N x M\n%YY = sum(Y.^2,2)/T; % N x 1\n% Covariance matrix (not normalised)\nYX = (Y * X'); % N x M\nYY = sum(Y.^2,2); % N x 1\n\nfprintf('a_min = %g\\n', a_min)\nfprintf('SY0 = %g\\n', SY0)\nfprintf('SY = %g\\n', SY)\n\n% Working variable\nif T <= M\n\tXX = []; \n\tCinv= zeros(T,T);\n\tSW = zeros(T,T);\nelse\n\tXX = (X * X'); \t % M x M\n\tCinv= zeros(M,M);\n\tSW = zeros(M,M);\nend\n\nG_A = zeros(1,M); % 1 x M\nlog_a = 0;\nA_old = A;\n\n% Free energy histry\nFE = zeros(Ntrain,1);\nLP = zeros(Ntrain,1);\nH = zeros(Ntrain,1);\nMM = zeros(Ntrain,1);\nErr = zeros(Ntrain,1);\n\n% ARD hyper param. history\nif isfield(parm,'Debug') & ~isempty(parm.Debug) & parm.Debug > 0\n\tDebug = 1;\n\tA_tmp = zeros(M_all, ceil(Ntrain/Nskip));\nelse\n\tDebug = 0;\nend\n\nk_save = 0;\n\n%%%%%% Learning Loop %%%%%%\nfor k=1:Ntrain\n\t% ARD hyper variance parameter\n\t% A = 1/alpha\n\n\tif T < M\n\t % Weight variance\n\t % inv(X*X' + 1./A) = A - A * X * inv(X'*A*X + 1) * X' * A\n\t\t% C = ( X' *A* X + eye(T) ); \n\t\tXA = repmultiply(X' , A); % T x M\n\t Cinv = XA * X + eye(T); % T x T\n\t \n \tif rcond(Cinv) > MinCond,\n\t\t\tCinv = inv( Cinv ); % M x M\n\t\telse\n\t\t\tCinv = pinv( Cinv );\n\t\tend\n\t\t\n\t\t% Weight update\n\t % inv(X*X' + 1./A) = A - A * X * Cinv * X' * A\n\t\t% W0 = YX .* A;\n\t\t% W = W0 - (((W0 * X) * Cinv) * X') .* A;\n\t\t% W = W0 - ((W0 * X) * Cinv) * (X'.* A);\n\t\tW = repmultiply(YX , A);\n\t\tW = W - ((W * X) * Cinv) * XA;\n%\t\tW = W - ((W * X) / C ) * XA;\n%\t\tW = W - repmultiply( ((W * X) * Cinv) * X' , A);\n\t\t\n\t\t% C = ( X' *A* X + eye(T) ); \n\t\t% G_A = diag( X * inv(C) * X' *A )\n\t\t% G_A = A .* sum(X .* (X / C), 2)';\n\t\tG_A = A .* sum(X .* (X * Cinv), 2)';\n\t\t\n\t\t% Log variance\n\t\tlog_sw = log_det(Cinv) ;\n\t\tif mod(k, Nskip)==0, fprintf('- '); end\n\telse\n\t\tif isempty(XX)\n\t\t\t% covariance matrix in reduced space\n\t\t\tXX = X * X';\n\t\t\t% save original index\n\t\t\tIX_act = IX_act(ix_act);\n\t\t\t% new active index in reduced space\n\t\t\tix_act = 1:M;\n\t\t\tM_all = M;\n\t\t\tA_all = A;\n\t\tend\n \tSW = XX + diag(1./A);\n \t\n \tif rcond(SW) > MinCond,\n\t\t\tSW = inv( SW ); % M x M\n\t\telse\n\t\t\tSW = pinv( SW );\n\t\tend\n\t\t\n\t\t% Weight update\n\t\tW = YX * SW;\n\t\t\n\t\t% SW = X*X' + diag(1./A)\n\t\t% G_A = diag(inv(SW) * X*X')\n\t\t% = 1 - diag(inv(SW)) ./A\n\t\t% G_A = diag( XX /SW );\n\t\tG_A = sum( SW .* XX ,1);\n\t\t%G_A = 1 - diag(SW)' ./A;\n\t\t\n\t\tlog_sw = log_det(SW) - sum(log(A));\n\t\tif mod(k, Nskip)==0, fprintf('+ '); end\n\tend\n\t\n\tWW = sum(W.^2, 1);\n % Noise variance update\n% SY = (sum(YY) - sum(sum(W.*YX)))/(N*T);\n% \n% if (SY/SY0) <= MINVAL,\n\t % Error\n\t dY = Y - W * X; % N x T\n\t dYY = sum(dY.^2, 2); \t% N x 1\n\t\n\t SY = (sum(dYY) + sum( WW./A ))/(N*T);\n\t % Prevent zero variance\n\t SY = max( SY, MINVAL);\n%\t fprintf('*')\n%\tend\n\t\n\t% Log variance\n log_sy = N * log(SY) ;\n if Ta0 > 0,\n\t log_a = Ta0 * sum( - log(A./a0) - a0./A + 1);\n\tend\n\t\n % Free energy\n H(k) = 0.5*N * (log_sw - M);\n LP(k) = - 0.5*(T * log_sy) ;\n FE(k) = LP(k) + H(k);\n Err(k) = (SY)./(SY0);\n MM(k) = M;\n\n % Hyper parameter for weight variance (ARD)\n G_A = max((G_A), MINVAL);\n\n\tif k <= Npre_train,\n\t\t% VB update rule\n\t\t% \tN * A = (W.^2)./SY + N * (A - A.*G_A) ; \n \t\t%A = WW./SY + N * (A - A.*G_A) ; \n\t\tif T < M\n\t\t\tA = (WW./SY + N * A.*(1 - G_A) + 2*Ta0*a0)./( N + 2*Ta0 );\n\t\telse\n\t\t\tA = (WW./SY + N * diag(SW)' + 2*Ta0*a0)./( N + 2*Ta0 );\n\t\tend\n\t\t%\tA^2 = A .* (1./SY)' * (W.^2) ./ (G_A * N);\t\n\telse\n\t % Accelerated update rule\n\t\t%\tA = (1./SY)' * (W.^2) ./ (G_A * N);\t\n\t A = sqrt(A.*(WW./SY)./(G_A * N));\n\t %A = ((WW./SY) + 2*Ta0*a0)./(G_A * N + 2*Ta0);\n\tend\n\t\n % Prune small variance\n if Prune == 1\n\t ix_act_old = ix_act;\n\n\t % Recover all component\n\t switch\tPrune\n\t case\t1\n\t\t A_all(ix_act) = WW/max(WW); % Prune by Weight\n\t case\t2\n\t\t A_all(ix_act) = A /max(A);\t % Prune by Alpha\n\t case\t3\n\t\t A_all(ix_act) = A * (1/SX); % Prune by Alpha\n\t end\n\t \n\t % Find active input dimension (absolute index)\n\t ix_act = find( A_all > a_min ); % effective indices\n\t Mnew = length(ix_act); \t\t% # of effective input\n\t \n\t if Mnew < M,\n\t\t % convert to relative index\n\t\t jx_act = trans_index(ix_act,ix_act_old,M_all);\n\t\t \n\t\t M = Mnew;\n\t\t A = A(jx_act) ; \t\t\t% 1 x M\n\t\t W = W(:,jx_act) ; \t\t% N x M\n\t\t\tX \t= X(jx_act,:);\t\t\t% M x T\n\t\t\tYX = YX(:,jx_act); \t \t% N x M\n\t\t\tif ~isempty(XX)\n\t\t\t\tXX\t= XX(jx_act,jx_act);\t% M x M\n\t\t\tend\n\t\tend\n end\n\n\tA = max(A,MINVAL);\n\n if mod(k, Nskip)==0\n % Save history\n\t\tif Debug == 1\n \tk_save = k_save + 1;\n \tA_tmp(:,k_save) = A_all(:);\n\t\tend\n\t\t\n fprintf('Iter = %4d, M = %4d, err = %g, F = %g, H = %g\\n', ...\n k, M, Err(k), FE(k), - H(k));\n end\n\n\tif k > Ncheck && M == MM(k-1)\n\t\tAdif = max(abs(A - A_old));\n\telse\n\t\tAdif = 1;\n\tend\n\tif Adif < Fdiff, \n\t\tfprintf('Converged : Alpha change = %g\\n',Adif)\n\t\tbreak; \n\tend;\n\t\n\tA_old = A;\n\t\n%\t\tFdif = (FE(k) - FE(k-Fstep))/abs(FE(k));\n%\telse\n%\t\tFdif = Fdiff + 1;\n%\tend\nend\n\n% convert to relative index\nix_act = IX_act(ix_act);\n\n% Active index\nModel.ix_act = ix_act;\nModel.M_all = M_ALL ;\n\n% Save trained variable\n% W & A is sufficient for cov-method initialization\nModel.A = A ;\nModel.W = W ;\nModel.SY = SY;\n\nModel.method = 'linear_map_sparse_cov';\nModel.mode = 'cov';\nModel.sparse = 'sparse';\n\n% Save history\nInfo.FE = FE(1:k);\nInfo.LP = LP(1:k);\nInfo.H = H(1:k) ;\nInfo.Err = Err(1:k);\nInfo.M = MM(1:k);\n\nif exist('A_tmp','var')\n\tInfo.A = A_tmp(:,1:k_save) ;\nend\n\n\n%%% ---- Index transformation from old active_index to current active_index\nfunction\tjx = trans_index(ix,ix_old,M)\n\nN = length(ix_old);\nItrans = zeros(M,1);\nItrans(ix_old) = 1:N;\n\njx = Itrans(ix);\n", "meta": {"author": "KamitaniLab", "repo": "GenericObjectDecoding", "sha": "c98f24370668109fd9978bc8b43a33bd43926f47", "save_path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding", "path": "github-repos/MATLAB/KamitaniLab-GenericObjectDecoding/GenericObjectDecoding-c98f24370668109fd9978bc8b43a33bd43926f47/code/matlab/lib/SPR_2009_12_17/linear_map_sparse_cov_pinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6225096910237348}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% function [y,dy] = affine3D(w,x,varargin)\n%\n% computes y = Q*w and the derivative wrt. w.\n% x = reshape(x,[],3); \n% Q = [x(:,1),x(:,2),x(:,3),1, 0 0 0 0 0 0 0\n% 0 0 0, 0, x(:,1),x(:,2,1),x(:,3),1, 0 0 0 \n% 0 0 0, 0, 0 0 0 0, x(:,1),x(:,2,1),x(:,3),1]\n% dy = Q:\n% if no arguments are given, the parameters for the identity map are returned.\n%\n% see also transformations/contents.m, trafo.m \n%==============================================================================\n\nfunction [y,dy] = affine3D(w,x,varargin)\n\n% the persitent variable stores the matrix \n% Q(x) = kron( I_2 , [x(:,1),x(:,2),1] );\npersistent Q\n\nif nargin==0\n help(mfilename)\n runMinimalExample; \n return;\nelse\n y = mfilename('fullfile'); \n dy = reshape(eye(4,3),[],1); % parameterization of identity\n if ischar(w), Q = []; w = []; end; % reset Q\n if isempty(w), return; end; \nend;\n\nif isempty(w) || (size(Q,1) ~= numel(x)),\n n = length(x)/3; x = reshape(x,n,3);\n Q = sparse(kron(speye(3),[x,ones(n,1)]));\n if nargout == 0, return; end;\nend;\ny = Q*w;\ndy = Q;\n\n%------------------------------------------------------------------------------\nfunction runMinimalExample\nfprintf('%s: minimal example\\n',mfilename)\n\nomega = [0,10,0,8,0,6]; m = [8,7,6]; \nw = 22/pi;c = (omega(2:2:end)-omega(1:2:end))'/2;\nR = [ cos(w),-sin(w),0;sin(w),cos(w),0;0,0,1];\ng = (eye(3)-R)*reshape(c,[],1);\nw = reshape([R,g]',[],1)\nx = getNodalGrid(omega,m);\nz = feval(mfilename,w,x);\nFAIRfigure(1); clf;\nplotGrid(x,omega,m,'color','r'); axis image; hold on;\nplotGrid(z,omega,m,'color','b'); axis image; hold off; \n\nfctn = @(w) feval(mfilename,w,x);\nw = w + randn(size(w));\ncheckDerivative(fctn,w,'fig',2);\n\n%==============================================================================\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/transformations/affine3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6225096888985393}} {"text": "function value = legendre_integral ( d )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_INTEGRAL returns the Legendre integral of a test function.\n%\n% Discussion:\n%\n% The same function, integrated over [-1,+1]^D, has an integral that\n% is a factor of 2^D times as large as this result.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer D, the spatial dimension.\n%\n% Output, real VALUE, the value of the integral.\n%\n value = ( 0.5 * erf ( 0.5 / sqrt ( 2.0 ) ) ) .^ d;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/legendre_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6224923553597852}} {"text": "function dz = singlePendulumRhs(~,z,g,l)\n% This function is used inside of ode45 for running a simulation of a\n% single pendulum. The first argument (time) is not used.\n\nth = z(1,:);\nw = z(2,:);\n\ndth = w;\ndw = singlePendulumDynamics(th,g,l);\n\ndz = [dth;dw];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/singlePendulum/singlePendulumRhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6224923493349279}} {"text": "function [L,U,P] = lu_rightp (A)\n%LU_RIGHTP right-looking LU factorization, with partial pivoting.\n%\n% Example:\n% [L,U,P] = lu_rightp (A)\n% See also: cs_demo\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nn = size (A,1) ;\nP = eye (n) ;\nfor k = 1:n\n [x,i] = max (abs (A (k:n,k))) ; % partial pivoting\n i = i+k-1 ;\n P ([k i],:) = P ([i k], :) ;\n A ([k i],:) = A ([i k], :) ; % (6.10), (6.11)\n A (k+1:n,k) = A (k+1:n,k) / A (k,k) ; % (6.12)\n A (k+1:n,k+1:n) = A (k+1:n,k+1:n) - A (k+1:n,k) * A (k,k+1:n) ; % (6.9)\nend\nL = tril (A,-1) + eye (n) ;\nU = triu (A) ;\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/lu_rightp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7634837689358858, "lm_q1q2_score": 0.6224167872388029}} {"text": "function [ f, rank ] = rgf_successor ( m, f, rank )\n\n%*****************************************************************************80\n%\n%% RGF_SUCCESSOR generates the next restricted growth function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Donald Kreher, Douglas Simpson,\n% Combinatorial Algorithms,\n% CRC Press, 1998,\n% ISBN: 0-8493-3988-X,\n% LC: QA164.K73.\n%\n% Parameters:\n%\n% Input, integer M, the domain of the RGF is the integers\n% from 1 to M. M must be positive.\n%\n% Input/output, integer F(M), the restricted growth function.\n%\n% Input/output, integer RANK, the rank.\n% If RANK = -1 on input, then the routine understands that this is\n% the first call, and that the user wishes the routine to supply\n% the first element in the ordering, which has RANK = 0.\n% In general, the input value of RANK is increased by 1 for output,\n% unless the very last element of the ordering was input, in which\n% case the output value of RANK is 0.\n%\n\n%\n% Return the first element.\n%\n if ( rank == -1 )\n f(1:m) = 1;\n rank = 0;\n return\n end\n%\n% Check.\n%\n ierror = rgf_check ( m, f );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RGF_SUCCESSOR - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal!\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'RGF_SUCCESSOR - Fatal error!\\n' );\n end\n%\n% Find the first position from the right which can be incremented.\n%\n for i = m : -1 : 2\n\n fmax = 1;\n for j = 2 : i - 1\n fmax = max ( fmax, f(j) );\n end\n%\n% Increment the function at this position, and set later entries to 1.\n%\n if ( f(i) ~= fmax + 1 )\n f(i) = f(i) + 1;\n f(i+1:m) = 1;\n rank = rank + 1;\n return\n end\n\n end\n%\n% The final element was input.\n% Return the first element.\n%\n f(1:m) = 1;\n rank = 0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/rgf_successor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.6224167759968765}} {"text": "function fem1d_bvp_linear_test03 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_BVP_LINEAR_TEST03 carries out test case #3.\n%\n% Location:\n%\n% http://people.sc.fsu.edu/~jburkardt/m_src/fem1d_bvp_linear/fem1d_bvp_linear_test03.m\n%\n% Discussion:\n%\n% Use A3, C3, F3, EXACT3, EXACT_UX3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dianne O'Leary,\n% Scientific Computing with Case Studies,\n% SIAM, 2008,\n% ISBN13: 978-0-898716-66-5,\n% LC: QA401.O44.\n%\n n = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_BVP_LINEAR_TEST03\\n' );\n fprintf ( 1, ' Solve -( A(x) U''(x) )'' + C(x) U(x) = F(x)\\n' );\n fprintf ( 1, ' for 0 < x < 1, with U(0) = U(1) = 0.\\n' );\n fprintf ( 1, ' A3(X) = 1.0\\n' );\n fprintf ( 1, ' C3(X) = 2.0 * X\\n' );\n fprintf ( 1, ' F3(X) = - X * ( 2 * X * X - 3 * X - 3 ) * exp ( X )\\n' );\n fprintf ( 1, ' U3(X) = X * ( 1 - X ) * exp ( X )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', n );\n%\n% Geometry definitions.\n%\n x_first = 0.0;\n x_last = 1.0;\n x = linspace ( x_first, x_last, n );\n x = x(:);\n\n u = fem1d_bvp_linear ( n, @a3, @c3, @f3, x );\n\n uexact = exact3 ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X U Uexact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %4d %8f %8f %8f %8e\\n', ...\n i, x(i), u(i), uexact(i), abs ( u(i) - uexact(i) ) );\n end\n\n e1 = l1_error ( n, x, u, @exact3 );\n e2 = l2_error_linear ( n, x, u, @exact3 );\n h1s = h1s_error_linear ( n, x, u, @exact_ux3 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' l1 norm of error = %g\\n', e1 );\n fprintf ( 1, ' L2 norm of error = %g\\n', e2 );\n fprintf ( 1, ' Seminorm of error = %g\\n', h1s );\n\n return\nend\nfunction value = a3 ( x )\n\n%*****************************************************************************80\n%\n%% A3 evaluates A function #3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of A(X).\n%\n value = 1.0;\n\n return\nend\nfunction value = c3 ( x )\n\n%*****************************************************************************80\n%\n%% C3 evaluates C function #3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of C(X).\n%\n value = 2.0 * x;\n\n return\nend\nfunction value = exact3 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT3 evaluates exact solution #3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of U(X).\n%\n value = x .* ( 1.0 - x ) .* exp ( x );\n\n return\nend\nfunction value = exact_ux3 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT_UX3 evaluates the derivative of exact solution #3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX(X).\n%\n value = ( 1.0 - x - x .* x ) .* exp ( x );\n\n return\nend\nfunction value = f3 ( x )\n\n%*****************************************************************************80\n%\n%% F3 evaluates right hand side function #3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n value = - x .* ( 2.0 * x .* x - 3.0 * x - 3.0 ) .* exp ( x );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_bvp_linear/fem1d_bvp_linear_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6224167735294492}} {"text": "function fem_basis_q4_display ( prefix )\n\n%*****************************************************************************80\n%\n%% FEM_BASIS_Q4_DISPLAY displays a finite element Q4 basis function.\n%\n% Discussion:\n%\n% This program reads a data file defining a set of nodes, and a\n% data file defining the triangulation of those nodes using 3 node triangles\n% (or 6 node triangles, as long as the vertices are listed first).\n%\n% The program then asks the user interactively to select one of the\n% nodes. It computes the basis function associated with that node\n% and displays it over the entire mesh. Of course, the basis function\n% will only be nonzero over a small number of the elements, but it\n% is instructive to see the entire mesh.\n%\n% The display is initially \"flat\", but by using the manipulator\n% on the graphics menu, the user can easily get some dramatic images\n% of the basis function.\n%\n% Usage:\n%\n% fem_basis_q4_display ( 'prefix' )\n%\n% where 'prefix' is the common prefix for the FEM files:\n%\n% * 'prefix'_nodes.txt, the node coordinates.\n% * 'prefix'_elements.txt, the nodes that make up each element;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string PREFIX, the common file prefix.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM_BASIS_Q4_DISPLAY:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Display basis functions associated with \\n' );\n fprintf ( 1, ' a finite element grid of linear quadrilaterals (\"Q4\").\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies a basis function by node index, and\\n' );\n fprintf ( 1, ' the program displays a surface plot of that basis function.\\n' );\n fprintf ( 1, ' (Use the 3D ROTATE option to see the full picture!\\n' );\n%\n% Get the prefix if missing.\n%\n if ( nargin < 1 )\n prefix = input ( ' Enter the common file prefix: ' );\n end\n%\n% Construct the file names.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n element_filename = strcat ( prefix, '_elements.txt' );\n%\n% Read the nodes.\n%\n [ dim_num, node_num ] = r8mat_header_read ( node_filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension = %d\\n', dim_num );\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n if ( dim_num ~= 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM_BASIS_Q4_DISPLAY - Fatal error!\\n' );\n fprintf ( 1, ' The spatial dimension is not 2.\\n' );\n error ( 'FEM_BASIS_Q4_DISPLAY - Fatal error!' );\n end\n\n node_xy = r8mat_data_read ( node_filename, dim_num, node_num );\n%\n% Read the elements.\n%\n [ element_order, element_num ] = i4mat_header_read ( element_filename );\n\n if ( element_order ~= 4 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM_BASIS_Q4_DISPLAY\\n' );\n fprintf ( 1, ' This program requires that the elements have order 4.\\n' );\n fprintf ( 1, ' Your elements have order %d\\n', element_order );\n error ( 'FEM_BASIS_Q4_DISPLAY - Fatal error!' );\n end\n\n element_node = i4mat_data_read ( element_filename, element_order, ...\n element_num );\n%\n% Set up the graph.\n%\n x_min = min ( node_xy(1,:) );\n x_max = max ( node_xy(1,:) );\n y_min = min ( node_xy(2,:) );\n y_max = max ( node_xy(2,:) );\n z_min = 0.0;\n z_max = 1.0;\n\n node_min = min ( min ( element_node ) );\n node_max = max ( max ( element_node ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Every basis function is associated with a node.\\n' );\n fprintf ( 1, ' To chooose a basis function, you specify a node.\\n' );\n fprintf ( 1, ' Nodes range in value from %d to %d.\\n', node_min, node_max );\n\n while ( 1 )\n\n fprintf ( 1, '\\n' );\n prompt = sprintf ( 'Enter a node between %d and %d: ', node_min, node_max );\n node_index = input ( prompt );\n\n if ( node_index < node_min | node_max < node_index )\n break\n end\n%\n% Clear the graphics page.\n%\n clf\n \n fprintf ( 1, '\\n' );\n \n for element = 1 : element_num\n \n local = 0;\n for j = 1 : element_order\n if ( element_node(j,element) == node_index )\n fprintf ( 1, ' Node %d occurs as local node %d in element %d.\\n', ...\n node_index, j, element );\n local = j;\n end \n end\n\n z(1:2,1:2) = 0.0;\n\n x(1,1) = node_xy(1,element_node(1,element)); \n y(1,1) = node_xy(2,element_node(1,element));\n x(2,1) = node_xy(1,element_node(2,element)); \n y(2,1) = node_xy(2,element_node(2,element));\n x(1,2) = node_xy(1,element_node(4,element)); \n y(1,2) = node_xy(2,element_node(4,element));\n x(2,2) = node_xy(1,element_node(3,element)); \n y(2,2) = node_xy(2,element_node(3,element));\n\n if ( local ~= 0 )\n if ( local == 1 )\n z(1,1) = 1.0;\n elseif ( local == 2 )\n z(2,1) = 1.0;\n elseif ( local == 3 )\n z(2,2) = 1.0;\n else\n z(1,2) = 1.0;\n end\n end\n \n caxis ( [ -0.4, 1.2 ] )\n surface ( x, y, z, 'FaceColor', 'interp' )\n\n end\n\n axis ( [ x_min, x_max, y_min, y_max, z_min, z_max ] );\n axis equal\n\n xlabel ( '--X axis--' );\n ylabel ( '--Y axis--' );\n zlabel ( '--Z axis--' );\n\n title_string = sprintf ( 'Q4 basis function for node %d', node_index );\n title ( title_string );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM_BASIS_Q4_DISPLAY:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n column_num = -1;\n return;\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n row_num = -1;\n return;\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction table = i4mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% I4MAT_DATA_READ reads data from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns in the data.\n%\n% Output, integer TABLE(M,N), the point coordinates.\n%\n table = [];\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %d' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the input file.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n return;\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' End of input while reading data.\\n' );\n error ( 'I4MAT_DATA_READ - Error!' );\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = i4mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% I4MAT_HEADER_READ reads the header from an I4MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = [];\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n return;\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction len = s_len_trim ( s )\n\n%*****************************************************************************80\n%\n% S_LEN_TRIM returns the length of a character string to the last nonblank.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be measured.\n%\n% Output, integer LENGTH, the length of the string up to the last nonblank.\n%\n len = length ( s );\n\n while ( 0 < len )\n if ( s(len) ~= ' ' )\n return\n end\n len = len - 1;\n end\n\n return\nend\nfunction word_num = s_word_count ( s )\n\n%*****************************************************************************80\n%\n%% S_WORD_COUNT counts the number of \"words\" in a string.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S, the string to be examined.\n%\n% Output, integer WORD_NUM, the number of \"words\" in the string.\n% Words are presumed to be separated by one or more blanks.\n%\n FALSE = 0;\n TRUE = 1;\n\n word_num = 0;\n s_length = length ( s );\n\n if ( s_length <= 0 )\n return;\n end\n\n blank = TRUE;\n\n for i = 1 : s_length\n\n if ( s(i) == ' ' )\n blank = TRUE;\n elseif ( blank == TRUE )\n word_num = word_num + 1;\n blank = FALSE;\n end\n\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem_basis_q4_display/fem_basis_q4_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.6224167657148612}} {"text": "function [intersects, inds] = intersectEdgePolygon(edge, poly, varargin)\n%INTERSECTEDGEPOLYGON Intersection point of an edge with a polygon\n%\n% INTER = intersectEdgePolygon(EDGE, POLY)\n% Computes intersection(s) point(s) between the edge EDGE and the polygon\n% POLY. EDGE is given by [x1 y1 x2 y2]. POLY is a N-by-2 array of vertex\n% coordinates.\n% INTER is a M-by-2 array containing coordinates of intersection(s). It\n% can be empty if no intersection is found.\n%\n% [INTER, INDS] = intersectEdgePolygon(EDGE, POLY)\n% Also returns index/indices of edge(s) involved in intersections.\n%\n% Example\n% % Intersection of an edge with a square\n% poly = [0 0;10 0;10 10;0 10];\n% edge = [9 2 9+3*1 2+3*2];\n% exp = [10 4];\n% inter = intersectEdgePolygon(edge, poly)\n% ans =\n% 10 4\n%\n% See also\n% edges2d, polygons2d, intersectLinePolygon, intersectRayPolygon\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2012-02-24, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% get computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% get supporting line of edge\nline = edgeToLine(edge);\n\n% compute all intersections of supporting line with polygon\n[intersects, inds] = intersectLinePolygon(line, poly, tol);\n\n% keep only intersection points located on the edge\nif ~isempty(intersects)\n pos = linePosition(intersects, line);\n keep = pos >= -tol & pos <= (1+tol);\n intersects = intersects(keep, :);\n inds = inds(keep);\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/polygons2d/intersectEdgePolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6223986708355136}} {"text": "% ========================================================================= \n% (c) 2016 Ronald Nissel, ronald.nissel@gmail.com\n% ========================================================================= \n% This script simulates an FBMC and OFDM transmission over a doubly-flat\n% channel, including channel estimation. The pilot symbol aided channel \n% estimation in FBMC is based on R. Nissel, M. Rupp, \"On Pilot-Symbol Aided\n% Channel Estimation in FBMC-OQAM\", IEEE ICASSP, 2016.\n\nclear; close all;\naddpath('./Theory');\n\nM_SNR_OFDM_dB = [0:5:30]; % Signal-to-Noise Ratio in dB\nNrRepetitions = 1000; % Number of Monte Carlo repetition (different channel realizations) \nQAM_ModulationOrder = 16; % QAM signal constellation order, 4, 16, 64, 256, 1024,...\n\n%% FBMC Object\nFBMC = Modulation.FBMC(...\n 12,... % Number subcarriers\n 30,... % Number FBMC symbols\n 15e3,... % Subcarrier spacing (Hz)\n 15e3*14*12,... % Sampling rate (Samples/s)\n 15e3*20,... % Intermediate frequency first subcarrier (Hz)\n false,... % Transmit real valued signal \n 'Hermite-OQAM',... % Prototype filter (Hermite, PHYDYAS, RRC) and OQAM or QAM, \n 8, ... % Overlapping factor (corresponding to the prototype filter length)\n 0, ... % Initial phase shift\n true ... % Polyphase implementation\n );\n\n%% OFDM Object\nOFDM = Modulation.OFDM(...\n 12,... % Number subcarriers\n 15,... % Number OFDM Symbols\n 15e3,... % Subcarrier spacing (Hz)\n 15e3*14*12,... % Sampling rate (Samples/s)\n 15e3*20,... % Intermediate frequency first subcarrier (Hz)\n false,... % Transmit real valued signal\n 0, ... % Cyclic prefix length (s), LTE: 1/15e3/14\n (8-1/2)*1/15e3*1/2 ... % Zero guard length (s)\n );\n\n%% PAM and QAM Object\nPAM = Modulation.SignalConstellation(sqrt(QAM_ModulationOrder),'PAM');\nQAM = Modulation.SignalConstellation(QAM_ModulationOrder,'QAM');\n\n%% Channel Estimation Objects\nChannelEstimation_OFDM = ChannelEstimation.PilotSymbolAidedChannelEstimation(...\n 'Diamond',... % Pilot pattern\n [... % Matrix that represents the pilot pattern parameters\n OFDM.Nr.Subcarriers,... % Number of subcarriers\n 6; ... % Pilot spacing in the frequency domain\n OFDM.Nr.MCSymbols,... % Number of FBMC/OFDM Symbols\n 4 ... % Pilot spacing in the time domain\n ],... \n 'linear'... % Interpolation(Extrapolation) method 'linear','spline','FullAverage,'MovingBlockAverage'\n );\nChannelEstimation_FBMC = ChannelEstimation.PilotSymbolAidedChannelEstimation(...\n 'Diamond',... % Pilot pattern\n [... % Matrix that represents the pilot pattern parameters\n FBMC.Nr.Subcarriers,... % Number of subcarriers\n 6; ... % Pilot spacing in the frequency domain\n FBMC.Nr.MCSymbols,... % Number of FBMC/OFDM Symbols\n 8 ... % Pilot spacing in the time domain\n ],... \n 'linear'... % Interpolation(Extrapolation) method 'linear','spline','FullAverage,'MovingBlockAverage',...\n );\n\n%% Imaginary Interference Cancellation Objects\nAuxiliaryMethod = ChannelEstimation.ImaginaryInterferenceCancellationAtPilotPosition(...\n 'Auxiliary', ... % Cancellation method\n ChannelEstimation_FBMC.GetAuxiliaryMatrix(1), ... % PilotMatrix\n FBMC.GetFBMCMatrix, ... % Imaginary interference matrix\n 16, ... % Cancel 16 closest interferers\n 2 ... % Pilot to data power offset\n );\nCodingMethod = ChannelEstimation.ImaginaryInterferenceCancellationAtPilotPosition(...\n 'Coding', ... % Cancellation method\n ChannelEstimation_FBMC.PilotMatrix, ... % PilotMatrix\n FBMC.GetFBMCMatrix, ... % Imaginary interference matrix\n 16, ... % Cancel 16 closest interferers\n 2 ... % Pilot to data power offset\n );\n\nBER_FBMC_Aux = nan(length(M_SNR_OFDM_dB),NrRepetitions);\nBER_FBMC_Cod = nan(length(M_SNR_OFDM_dB),NrRepetitions);\nBER_FBMC_perfect = nan(length(M_SNR_OFDM_dB),NrRepetitions);\nBER_OFDM = nan(length(M_SNR_OFDM_dB),NrRepetitions);\nBER_OFDM_perfect = nan(length(M_SNR_OFDM_dB),NrRepetitions);\nfor i_rep = 1:NrRepetitions\n for i_SNR = 1:length(M_SNR_OFDM_dB)\n SNR_OFDM_dB = M_SNR_OFDM_dB(i_SNR);\n Pn_time = OFDM.PHY.SamplingRate/(OFDM.PHY.SubcarrierSpacing*OFDM.Nr.Subcarriers)*10^(-SNR_OFDM_dB/10); \n\n %% Generate Random BitStream\n BinaryDataStream_FBMC_Aux = randi([0 1],AuxiliaryMethod.NrDataSymbols*log2(PAM.ModulationOrder),1);\n BinaryDataStream_FBMC_Cod = randi([0 1],CodingMethod.NrDataSymbols*log2(PAM.ModulationOrder),1);\n BinaryDataStream_OFDM = randi([0 1],(OFDM.Nr.Subcarriers*OFDM.Nr.MCSymbols-ChannelEstimation_OFDM.NrPilotSymbols)*log2(QAM.ModulationOrder),1);\n\n %% Transmitted Data Symbols\n xD_FBMC_Aux = PAM.Bit2Symbol(BinaryDataStream_FBMC_Aux);\n xD_FBMC_Cod = PAM.Bit2Symbol(BinaryDataStream_FBMC_Cod);\n xD_OFDM = QAM.Bit2Symbol(BinaryDataStream_OFDM);\n\n %% Transmitted Pilot Symbols\n xP_FBMC = PAM.SymbolMapping(randi(PAM.ModulationOrder,[ChannelEstimation_FBMC.NrPilotSymbols 1]));\n xP_FBMC = xP_FBMC./abs(xP_FBMC);\n xP_OFDM = QAM.SymbolMapping(randi(QAM.ModulationOrder,[ChannelEstimation_OFDM.NrPilotSymbols 1]));\n xP_OFDM = xP_OFDM./abs(xP_OFDM); \n\n %% Transmitted Symbols\n x_FBMC_Aux = reshape(AuxiliaryMethod.PrecodingMatrix*[xP_FBMC;xD_FBMC_Aux],[FBMC.Nr.Subcarriers FBMC.Nr.MCSymbols]);\n x_FBMC_Cod = reshape(CodingMethod.PrecodingMatrix*[xP_FBMC;xD_FBMC_Cod],[FBMC.Nr.Subcarriers FBMC.Nr.MCSymbols]);\n x_OFDM = nan(OFDM.Nr.Subcarriers,OFDM.Nr.MCSymbols);\n x_OFDM(ChannelEstimation_OFDM.PilotMatrix==1) = xP_OFDM;\n x_OFDM(ChannelEstimation_OFDM.PilotMatrix==0) = xD_OFDM;\n\n %% Transmitted FBMC Signal (time domain)\n s_FBMC_Aux = FBMC.Modulation(x_FBMC_Aux); \n s_FBMC_Cod = FBMC.Modulation(x_FBMC_Cod); \n s_OFDM = OFDM.Modulation(x_OFDM);\n\n %% Channel (doubly flat fading and AWGN) \n h = sqrt(1/2)*(randn+1j*randn);\n % h = 1; % Pure AWGN\n n_FBMC = sqrt(Pn_time/2)*(randn(size(s_FBMC_Cod))+1j*randn(size(s_FBMC_Cod)));\n n_OFDM = sqrt(Pn_time/2)*(randn(size(s_OFDM))+1j*randn(size(s_OFDM)));\n\n r_FBMC_Aux = h*s_FBMC_Aux + n_FBMC;\n r_FBMC_Cod = h*s_FBMC_Cod + n_FBMC; \n r_OFDM = h*s_OFDM + n_OFDM;\n\n %% Demodulate OFDM and FBMC signal\n y_FBMC_Aux = FBMC.Demodulation(r_FBMC_Aux);\n y_FBMC_Cod = FBMC.Demodulation(r_FBMC_Cod);\n y_OFDM = OFDM.Demodulation(r_OFDM);\n\n %% LS channel estimates at pilot positions\n hP_LS_FBMC_Aux = y_FBMC_Aux(ChannelEstimation_FBMC.PilotMatrix==1)./xP_FBMC/sqrt(AuxiliaryMethod.PilotToDataPowerOffset*AuxiliaryMethod.DataPowerReduction);\n hP_LS_FBMC_Cod = y_FBMC_Cod(ChannelEstimation_FBMC.PilotMatrix==1)./xP_FBMC/sqrt(CodingMethod.PilotToDataPowerOffset);\n hP_LS_OFDM = y_OFDM(ChannelEstimation_OFDM.PilotMatrix==1)./xP_OFDM;\n\n %% Channel Estimation using Interpolation\n h_FBMC_Aux = ChannelEstimation_FBMC.ChannelInterpolation(hP_LS_FBMC_Aux);\n h_FBMC_Cod = ChannelEstimation_FBMC.ChannelInterpolation(hP_LS_FBMC_Cod);\n h_OFDM = ChannelEstimation_OFDM.ChannelInterpolation(hP_LS_OFDM);\n\n %% Equalized received symbols at data position\n y_EQ_FBMC_Aux = real(y_FBMC_Aux(AuxiliaryMethod.PilotMatrix==0)./h_FBMC_Aux(AuxiliaryMethod.PilotMatrix==0)/sqrt(AuxiliaryMethod.DataPowerReduction));\n y_EQ_FBMC_Cod = real(CodingMethod.PrecodingMatrix(:,CodingMethod.NrPilotSymbols+1:end)'*(y_FBMC_Cod(:)./h_FBMC_Cod(:)));\n y_EQ_FBMC_perfect = real(CodingMethod.PrecodingMatrix(:,CodingMethod.NrPilotSymbols+1:end)'*(y_FBMC_Cod(:)./h));\n\n y_EQ_OFDM = y_OFDM(ChannelEstimation_OFDM.PilotMatrix==0)./h_OFDM(ChannelEstimation_OFDM.PilotMatrix==0);\n y_EQ_OFDM_perfect = y_OFDM(ChannelEstimation_OFDM.PilotMatrix==0)./h;\n\n %% Detect BitStream\n DetectedBitStream_FBMC_Aux = PAM.Symbol2Bit(real(y_EQ_FBMC_Aux(:)));\n DetectedBitStream_FBMC_Cod = PAM.Symbol2Bit(real(y_EQ_FBMC_Cod(:)));\n DetectedBitStream_FBMC_perfect = PAM.Symbol2Bit(real(y_EQ_FBMC_perfect(:)));\n\n DetectedBitStream_OFDM = QAM.Symbol2Bit(y_EQ_OFDM(:));\n DetectedBitStream_OFDM_perfect = QAM.Symbol2Bit(y_EQ_OFDM_perfect(:));\n\n %% Calculate BER\n BER_FBMC_Aux(i_SNR,i_rep) = mean(BinaryDataStream_FBMC_Aux~=DetectedBitStream_FBMC_Aux);\n BER_FBMC_Cod(i_SNR,i_rep) = mean(BinaryDataStream_FBMC_Cod~=DetectedBitStream_FBMC_Cod);\n BER_FBMC_perfect(i_SNR,i_rep) = mean(BinaryDataStream_FBMC_Cod~=DetectedBitStream_FBMC_perfect);\n\n BER_OFDM(i_SNR,i_rep) = mean(BinaryDataStream_OFDM~=DetectedBitStream_OFDM); \n BER_OFDM_perfect(i_SNR,i_rep) = mean(BinaryDataStream_OFDM~=DetectedBitStream_OFDM_perfect); \n\n end\n \n if mod(i_rep,100)==0\n disp([int2str(i_rep/NrRepetitions*100) '%']);\n end\nend\n\n%% Theoretical BEP for perfect channel knowledge \n% BEP_4QAM = 1/2-1./(2*sqrt(2*(1+10.^(-M_SNR_OFDM_dB/10))-1));\nM_SNR_OFDM_dB_morePoints = min(M_SNR_OFDM_dB):0.5:max(M_SNR_OFDM_dB);\nBEP_perfect = BitErrorProbabilityDoublyFlatRayleigh(M_SNR_OFDM_dB_morePoints,QAM.SymbolMapping,QAM.BitMapping);\n\n\n%% Plot BER and BEP\nfigure();\nsemilogy(M_SNR_OFDM_dB,mean(BER_FBMC_Aux,2),'red -o');\nhold on;\nsemilogy(M_SNR_OFDM_dB,mean(BER_FBMC_Cod,2),'blue -o');\nsemilogy(M_SNR_OFDM_dB,mean(BER_OFDM,2),'black -o'); \nsemilogy(M_SNR_OFDM_dB,mean(BER_FBMC_perfect,2),'blue -x');\nsemilogy(M_SNR_OFDM_dB,mean(BER_OFDM_perfect,2),'black -x');\nsemilogy(M_SNR_OFDM_dB_morePoints,BEP_perfect','black');\nxlabel('SNR for OFDM (dB)'); \nylabel('BER, BEP');\nlegend('Simulation: FBMC Auxiliary','Simulation: FBMC Coding','Simulation: OFDM', 'Simulation FBMC perfect CSI', 'Simulation OFDM perfect CSI','Theory perfect CSI','Location','SouthWest');\n\n%% Plot Pilot Pattern\nfigure();\nChannelEstimation_OFDM.PlotPilotPattern;\ntitle('OFDM');\nfigure();\nChannelEstimation_FBMC.PlotPilotPattern(AuxiliaryMethod.PilotMatrix)\ntitle('FBMC Auxiliary');\nfigure();\nChannelEstimation_FBMC.PlotPilotPattern(-(CodingMethod.ConsideredInterferenceMatrix<0)+(CodingMethod.ConsideredInterferenceMatrix>0))\ntitle('FBMC Coding');\n\n%% Calculate and Plot Expected Transmit Power Over Time\n[Power_FBMC_Aux,t_FBMC] = FBMC.PlotTransmitPower(AuxiliaryMethod.PrecodingMatrix*AuxiliaryMethod.PrecodingMatrix');\n[Power_FBMC_Cod,~] = FBMC.PlotTransmitPower(CodingMethod.PrecodingMatrix*CodingMethod.PrecodingMatrix');\n[Power_OFDM,t_OFDM] = OFDM.PlotTransmitPower;\nfigure();\nplot(t_FBMC,Power_FBMC_Aux,'red');\nhold on;\nplot(t_FBMC,Power_FBMC_Cod,'blue');\nplot(t_OFDM,Power_OFDM,'black ');\nlegend({'FBMC Auxiliary','FBMC Coding','OFDM'});\nylabel('Transmit Power');\nxlabel('Time(s)');\n\n%% Calculate Power Spectral Density\n[PSD_FBMC_Aux,t_FBMC] = FBMC.PlotPowerSpectralDensity(AuxiliaryMethod.PrecodingMatrix*AuxiliaryMethod.PrecodingMatrix');\n[PSD_FBMC_Cod,~] = FBMC.PlotPowerSpectralDensity(CodingMethod.PrecodingMatrix*CodingMethod.PrecodingMatrix');\n[PSD_OFDM,t_OFDM] = OFDM.PlotPowerSpectralDensity;\nfigure();\nplot(t_FBMC,10*log10(PSD_FBMC_Aux),'red');\nhold on;\nplot(t_FBMC,10*log10(PSD_FBMC_Cod),'blue');\nplot(t_OFDM,10*log10(PSD_OFDM),'black ');\nlegend({'FBMC Auxiliary','FBMC Coding','OFDM'});\nylabel('Power Spectral Density (dB)');\nxlabel('Frequency (Hz)');\n\n", "meta": {"author": "rnissel", "repo": "Channel-Estimation", "sha": "d11759b8cf13fb357728285c2afa65da1cd68621", "save_path": "github-repos/MATLAB/rnissel-Channel-Estimation", "path": "github-repos/MATLAB/rnissel-Channel-Estimation/Channel-Estimation-d11759b8cf13fb357728285c2afa65da1cd68621/SimpleVersion_DoublyFlat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6223703313088079}} {"text": "function PCs = pca(this, cutoff, pcDimension)\n% Computes principal component analysis (PCA) of image time series\n%\n% Y = MrImage()\n% PCs = pca(this, cutoff, pcDimension)\n%\n% This is a method of class MrImage.\n%\n% Spatial PCA (default):\n% The principal component analysis report representative spatial\n% distributions (\"principal components\") of fluctuation patterns that explain most variance in the\n% data (over all time points).\n% The corresponding temporal evolution of weights (or scores or\n% projections) describes how each of these spatial patterns fluctuates over\n% time.\n%\n% Temporal PCA (?)\n% The principal component analysis reports the representative time series\n% (\"principal components\") that explain most of the variance in the data\n% (pooled over all voxels).\n% The corresponding spatial maps of weights (or scores or projections) give\n% the relative contribution of this particular time series to the variance\n% in each voxel\n%\n% IN\n% cutoff value determining number of principal components extracted\n% 0 < cutoff < 1 interpreted as relative amount of\n% variance explained;\n% nPCs will be determined as the number\n% of components that explain at least\n% cutoff*100 % of the variance in the\n% data\n% cutoff = 1,2,3... interpreted as number of PCs extracted\n% pcDimension 'spatial' (default) or 'temporal'\n% determines which dimension i.e. spatial image or time\n% (volumes) will be principal component, and consequently,\n% which other one will be the projection dimension\n% Technically, the non-PC dimension is the one considered to\n% \"generate the variance\", in that the covariance matrix\n% entries would relate PC vector components, co-varying over\n% the non-PC dimension,\n% e.g. spatial PCA: How do two voxels co-vary over time\n% temporal PCA: How do two time-points co-vary over\n% space\n% Typically, the 1st projection of the temporal PCA looks\n% like the mean, and for the other components, it usually\n% holds:\n% PC_spatial(n) approximately equal to Proj_temporal(n+1)\n% OUT\n% PCs cell(nPCs,1) of MrImages\n% Each element is a 4D image, the nth volume is computed as\n% PCs{k}_n = PC{k}*Projection_n,\n% i.e. for\n% spatial PCA: principal component * nth time point pf\n% projection\n% temporal PCA: nth element of principal component *\n% projection vector of all voxels\n%\n% EXAMPLE\n% pca\n%\n% See also MrImage\n\n% Author: Lars Kasper\n% Created: 2015-08-13\n% Copyright (C) 2015 Institute for Biomedical Engineering\n% University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public License (GPL), version 3.\n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n% .\n\n\n% if number of components specified explicity, no additional variance\n% threshold is needed\n\nif nargin < 2\n cutoff = 1;\nend\n\nisSpatialPca = nargin < 3 || strcmpi(pcDimension, 'spatial');\n\nhasVarianceThreshold = cutoff<1;\n\nif hasVarianceThreshold\n nComponents = 1;\nelse\n nComponents = cutoff;\n cutoff = 0;\nend\n\n% created reshaped data matrix for PCA\n\n% data matrix X: [nVoxels, nVolumes] for 4D, [nVoxel2D, nSlices] for 3D...\napplicationDimension = find(this.geometry.nVoxels>1, 1, 'last');\nX = reshape(this.data, [], this.geometry.nVoxels(applicationDimension));\n\n% [nVolumes, nVoxels] for spatial PCA...\nif isSpatialPca\n X = X';\nend\n\n% remove invalid data for PCA\nX(isinf(X)) = 0;\nX(isnan(X)) = 0;\n\n% iteratively increase number of components, if variance threshold given,\n% otherwise compute once with number of components specified\ndoPca = 1;\nwhile doPca\n \n \n % Explanation for temporal PCA\n % COEFF = [nVolumes, nPCs] principal components (PCs) ordered by variance\n % explained\n % SCORE = [nVoxel, nPCs] loads of each component in each voxel, i.e.\n % specific contribution of each component in\n % a voxel's variance\n % LATENT = [nPCs, 1] eigenvalues of data covariance matrix,\n % stating how much variance was explained by\n % each PC overall\n % TSQUARED = [nVoxels,1] Hotelling's T-Squared test whether PC\n % explained significant variance in a voxel\n % EXPLAINED = [nPCs, 1] relative amount of variance explained (in\n % percent) by each component\n % MU = [1, nVolumes] mean of all time series\n [COEFF, SCORE, LATENT, TSQUARED, EXPLAINED, MU] = ...\n pca(X, 'NumComponents', nComponents);\n \n explainedVariance = sum(EXPLAINED(1:nComponents))/100;\n doPca = hasVarianceThreshold && ...\n (explainedVariance < cutoff);\n \n if doPca\n nComponents = nComponents + 1;\n \n % somehow, pca also gives out EXPLAINED variance also for more than one\n % component, jump to 1st achieved cutoff-threshold\n nComponentsTemp = find(cumsum(EXPLAINED) >= cutoff*100, 1, 'first');\n if ~isempty(nComponentsTemp)\n nComponents = nComponentsTemp;\n end\n end\nend\n\n% create 4D PCs i.e. 3D Pcs which are co-varied along the volume\n% dimension with the computed projections\n\nPCs = cell(nComponents,1);\nfor c = 1:nComponents\n PCs{c} = this.copyobj;\n PCs{c}.rois = {};\n PCs{c}.name = sprintf(['PC %d (explained variance: %5.2f %%, ', ...\n 'cumulative %5.2f %%)) - %s'], ...\n c, EXPLAINED(c), sum(EXPLAINED(1:c)), this.name);\n \n % multiply the PC with each weight entry to generate whole time series\n Y = kron(SCORE(:,c)', COEFF(:,c));\n \n if ~isSpatialPca\n Y = Y';\n end\n \n PCs{c}.data = reshape(Y, this.geometry.nVoxels);\nend", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImage/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6221827271656155}} {"text": "function [SNR] = snr_mean( target, masked )\n% SNR Computes signal-to-noise ratio.\n%\n% S=SNR(TARGET,MASKED) returns signal-to-noise ratio \n% given target and masked speech signals.\n% \n% Inputs\n% TARGET is a target signal as vector.\n%\n% MASKED is a target+masker signal as vector.\n%\n% Outputs \n% S is the signal-to-noise ratio (dB).\n%\n% Example\n% % read target and masker signals from wav files\n% [ target, fs ] = wavread( 'sp10.wav' );\n% [ masker, fs ] = wavread( 'ssn.wav' );\n%\n% % desired SNR level (dB)\n% dSNR = 5; \n%\n% % generate mixture signal: noisy = signal + noise\n% [ masked, masker ] = addnoise( target, masker, dSNR ); \n%\n% % compute SNR (dB)\n% SNR = snr( target, masked );\n%\n% % display the result \n% fprintf( 'SNR: %0.2f dB\\n', SNR );\n%\n% See also ADDNOISE, SEGSNR.\n\n% Author: Kamil Wojcicki, November 2011.\n\n % compute the masker (assumes additive noise model)\n masker = masked(:) - target(:); \n\n % compute target and masker frame energies\n energy.target = target.' * target;\n energy.masker = masker.' * masker + eps;\n\n % compute frame signal-to-noise ratio (dB)\n SNR = 10*log10( energy.target ./ energy.masker + eps );\n SNR\n% SNR = 123123123;\n\n\n% EOF\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/segsnr/snr_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6221827233421788}} {"text": "function [yn,en,S] = FXNLMSadapt(un,dn,S)\n\n% FXNLMSadapt Normalized FXLMS Algorithm \n%\n% Perform over the entire length of the input sequence. The\n% history of output, square error and coefficients of FIR \n% filters are passed out to extenal\n% Arguments:\n% un Input signal\n% dn Desired signal\n% S Adptive filter parameters as defined in NLMSinit.m\n% yn History of output signal\n% en History of error signal\n%\n% by Lee, Gan, and Kuo, 2008\n% Subband Adaptive Filtering: Theory and Implementation\n% Publisher: John Wiley and Sons, Ltd\n\nM = length(S.coeffs); % Length of input sequence\nmu = S.step; % Step size of NLMS algorithm (between 0 and 2)\nleak = S.leakage; % Leaky factor for leaky LMS algorithm\nalpha = S.alpha; % Small constant\nAdaptStart = S.AdaptStart;\nw = S.coeffs; % Coefficients of FIR filter\nu = zeros(M,1); \nfu = zeros(M,1);\n\nITER = length(un); % Length of input sequence\nyn = zeros(1,ITER); % Initialize output sequence to zero\nen = zeros(1,ITER); % Initialize error sequence to zero\n%filt_un = zeros(1,ITER); % Initialize filtered input to zero\n%est_filt_un = zeros(1,ITER); % Initialize filtered input to zero (est)\nfilt_un = filter(S.sec_num,S.sec_den,un); % Filtered input \nest_filt_un = filter(S.estsec,1,un); % Filtered input (est)\n\nif isfield(S,'unknownsys')\n b = S.unknownsys;\n norm_b = norm(b);\n eml = zeros(1,ITER);\n ComputeEML = 1;\nelse\n ComputeEML = 0;\nend\n\nfor n = 1:ITER \n u = [filt_un(n); u(1:end-1)]; % Input signal vector (through the actual \n % secondary path)\n fu = [est_filt_un(n); fu(1:end-1)]; % Filtered input signal vector (through \n % the estimated secondary path)\n yn(n) = w'*u; % Inner product of filter coefficients and \n % tappd delay line \n en(n) = dn(n)-yn(n); % Compute error signal\n if ComputeEML == 1;\n eml(n) = norm(b-w)/norm_b; % System error norm (normalized)\n end\n if n >= AdaptStart\n w = (1-mu*leak)*w + ((mu*en(n))/(fu'*fu+alpha))*fu; \n % LMS algorithm in leaky mode\n S.iter = S.iter + 1;\n end \nend\n\nS.coeffs = w; % Coefficient values at the final iteration\nif ComputeEML == 1;\n S.eml = eml;\nend\n\n", "meta": {"author": "CharlesThaCat", "repo": "acoustic-interference-cancellation", "sha": "edb394499ea6f9c96445a3e9613bd64a854c289e", "save_path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation", "path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation/acoustic-interference-cancellation-edb394499ea6f9c96445a3e9613bd64a854c289e/Subband processing/Common Code/FXNLMSadapt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6221478331969676}} {"text": "function M = spectrahedronfactory(n, k)\n% Manifold of n-by-n symmetric positive semidefinite matrices of rank k\n% with trace (sum of diagonal elements) equal to 1.\n%\n% function M = spectrahedronfactory(n, k)\n%\n% A point X on the manifold is parameterized as YY^T where Y is a matrix of\n% size nxk. As such, X is symmetric, positive semidefinite. We restrict to\n% full-rank Y's, such that X has rank exactly k. The point X is numerically\n% represented by Y (this is more efficient than working with X, which may\n% be big). Tangent vectors are represented as matrices of the same size as\n% Y, call them Ydot, so that Xdot = Y Ydot' + Ydot Y and trace(Xdot) == 0.\n% The metric is the canonical Euclidean metric on Y.\n% \n% The trace constraint on X (trace(X) == 1) translates to a unit Frobenius\n% norm constraint on Y: trace(X) = norm(Y, 'fro')^2 == 1. The set of such\n% Y's forms the unit sphere in R^(nxk): see spherefactory. But because for\n% any orthogonal Q of size k, it holds that (YQ)(YQ)' = YY', we \"group\" all\n% matrices of the form YQ in an equivalence class. The set of equivalence\n% classes is a Riemannian quotient manifold, implemented here.\n%\n%\n% Note that this geometry formally breaks down at rank-deficient Y's.\n% As an alternative, you may use the sphere manifold (it has larger\n% dimension (by 1), but does not break down at rank drop.)\n%\n% The geometry is taken from the 2010 paper:\n% M. Journee, P.-A. Absil, F. Bach and R. Sepulchre,\n% \"Low-Rank Optimization on the Cone of Positive Semidefinite Matrices\".\n% Paper link: http://www.di.ens.fr/~fbach/journee2010_sdp.pdf\n% \n% \n% Please cite the Manopt paper as well as the research paper:\n% @Article{journee2010low,\n% Title = {Low-rank optimization on the cone of positive semidefinite matrices},\n% Author = {Journ{\\'e}e, M. and Bach, F. and Absil, P.-A. and Sepulchre, R.},\n% Journal = {SIAM Journal on Optimization},\n% Year = {2010},\n% Number = {5},\n% Pages = {2327--2351},\n% Volume = {20},\n% Doi = {10.1137/080731359}\n% }\n% \n%\n% See also: spherefactory elliptopefactory symfixedrankYYfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, July 11, 2013.\n% Contributors: Nicolas Boumal\n% Change log:\n%\n% Apr. 2, 2015 (NB):\n% Replaced trace(A'*B) by A(:)'*B(:) (equivalent but faster).\n% Updated documentation.\n%\n% Apr. 17, 2018 (NB):\n% Removed dependence on lyap.\n%\n% Sep. 6, 2018 (NB):\n% Removed M.exp() as it was not implemented.\n \n \n \n M.name = @() sprintf('YY'' quotient manifold of %dx%d psd matrices of rank %d with trace 1', n, k);\n \n M.dim = @() n*k - 1 - k*(k-1)/2;\n \n % Euclidean metric on the total space\n M.inner = @(Y, eta, zeta) eta(:)'*zeta(:);\n \n M.norm = @(Y, eta) sqrt(M.inner(Y, eta, eta));\n \n M.dist = @(Y, Z) error('spectrahedronfactory.dist not implemented yet.');\n \n M.typicaldist = @() 10*k;\n \n M.proj = @projection;\n function etaproj = projection(Y, eta)\n % Projection onto the tangent space, i.e., on the tangent space of\n % ||Y|| = 1\n \n eta = eta - (eta(:)'*Y(:))*Y;\n \n % Projection onto the horizontal space\n YtY = Y'*Y;\n SS = YtY;\n AS = Y'*eta - eta'*Y;\n % Omega = lyap(SS, -AS);\n Omega = lyapunov_symmetric(SS, AS);\n etaproj = eta - Y*Omega;\n end\n \n M.tangent = M.proj;\n M.tangent2ambient = @(Y, eta) eta;\n \n M.retr = @retraction;\n function Ynew = retraction(Y, eta, t)\n if nargin < 3\n t = 1.0;\n end\n Ynew = Y + t*eta;\n Ynew = Ynew/norm(Ynew, 'fro');\n end\n \n \n M.egrad2rgrad = @(Y, eta) eta - (eta(:)'*Y(:))*Y;\n \n M.ehess2rhess = @ehess2rhess;\n function Hess = ehess2rhess(Y, egrad, ehess, eta)\n \n % Directional derivative of the Riemannian gradient\n Hess = ehess - (egrad(:)'*Y(:))*eta - ( (ehess(:)'*Y(:)) + (eta(:)'*egrad(:)) )*Y;\n Hess = Hess - (Hess(:)'*Y(:))*Y;\n \n % Project on the horizontal space\n Hess = M.proj(Y, Hess);\n \n end\n \n \n % Notice that the hash of two equivalent points will be different...\n M.hash = @(Y) ['z' hashmd5(Y(:))];\n \n M.rand = @random;\n \n function Y = random()\n Y = randn(n, k);\n Y = Y/norm(Y,'fro');\n end\n \n M.randvec = @randomvec;\n function eta = randomvec(Y)\n eta = randn(n, k);\n eta = projection(Y, eta);\n nrm = M.norm(Y, eta);\n eta = eta / nrm;\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(Y) zeros(n, k);\n \n M.transp = @(Y1, Y2, d) projection(Y2, d);\n \n M.vec = @(Y, u_mat) u_mat(:);\n M.mat = @(Y, u_vec) reshape(u_vec, [n, k]);\n M.vecmatareisometries = @() true;\n \nend\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/manopt/manifolds/symfixedrank/spectrahedronfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6221478255300024}} {"text": "function [aVal,aJacob,aHess,papt]=aPoly(x,numDim)\n%%APOLY The drift function for a linear continuous-time motion model of a\n% given order in a specified number of Cartesian dimensions. The\n% order of the linear filter, that is the number of moments of\n% position, does not need to be explicitly specified.\n%\n%INPUTS: x The xDimXN state vector of N targets in the order of\n% [position;velocity;acceleration;etc] for however many\n% derivatives of position there are.\n% numDim The number of dimensions of the simulation problem. If the\n% numDim parameter is omitted, then numDim=3 (3D motion) is\n% assumed. The dimensionality of the state must be an integer\n% multiple of numDim.\n%\n%OUTPUTS: aVal The xDimXN time-derivative of the N state vectors under the\n% linear motion model.\n% aJacob The xDimXxDim Jacobian of aVal (it is the same for all x and\n% is not repeated N times). This is such that aJacob(:,k) is\n% the partial derivative of aVal with respect to the kth\n% element of x.\n% aHess The xDimXxDimXxDim hypermatrix such that aHess(:,k1,k2) is\n% the second partial derivative of aVal with respect to\n% elements k1 and k2 of x (all zero in this instance). It is\n% the same for all x.\n% papt The xDimX1 partial derivative of aVal with respect to time\n% (all zero in this instance). It is the same for all x.\n%\n%The drift function corresponds to the state transition given in\n%discrete-time by the function FPolyKal.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2)\n numDim=3; \nend\n\nnumTar=size(x,2);\nxDim=size(x,1);\n\naVal=[x((numDim+1):(xDim),:);zeros(numDim,numTar)];\n\nif(nargout>1)\n aJacob=[zeros(xDim,numDim),[eye(xDim-numDim,xDim-numDim);zeros(numDim,xDim-numDim)],zeros(xDim,numDim)];\n\n if(nargout>2)\n aHess=zeros(xDim,xDim,xDim);\n\n if(nargout>3)\n papt=zeros(xDim,1);\n end\n end\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Models/Continuous_Time/aPoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6221250657766999}} {"text": "function r_size = nwspgr_size ( type, dim, k, sym, compress )\n\n%*****************************************************************************80\n%\n%% NWSPGR_SIZE determines the size of a sparse grid rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2014\n%\n% Author:\n%\n% Original MATLAB version by Florian Heiss, Viktor Winschel.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Florian Heiss, Viktor Winschel,\n% Likelihood approximation by numerical integration on sparse grids,\n% Journal of Econometrics,\n% Volume 144, 2008, pages 62-80.\n%\n% Parameters:\n% \n% Input, string TYPE, selects the 1D integration rule:\n% func: any function name. Function must accept level l and return nodes N \n% and weights W for univariate quadrature rule with polynomial exactness \n% 2*L-1 as [n, w] = feval(func,level)\n%\n% Input, integer DIM, the dimension of the integration problem.\n%\n% Input, integer K, the level. \n%\n% Input, integer SYM. If the rule is \n% symmetric, specifying SYM to be 1 will allow the code to run faster.\n% But this also requires that the user quadrature rule function only \n% return the nonnegative abscissas and their weights.\n%\n% Input, integer COMPRESS,\n% 0, do not compress the rule ( = do not merge duplicate points.)\n% 1, compress the rule.\n%\n% Output, integer R_SIZE, the \"size\" of the rule.\n%\n sym = logical ( sym );\n%\n% Retrieve the 1D rules of levels 1 to K.\n% Create cell arrays X1D and W1D containing the node and weight information.\n% The array N1D stores the length or order of each rule.\n%\n% If the user indicates that it's a symmetric rule, \n% keep only the positive orthant.\n%\n n1d = zeros ( 1, k );\n x1d = cell ( k, 1 ); \n w1d = cell ( k, 1 ); \n\n for level = 1 : k\n\n [ x, w ] = feval ( type, level );\n\n if ( sym )\n [ numnew, dummy ] = size ( x );\n [ x, sortvec ] = sortrows ( x );\n w = w ( sortvec );\n x = x((floor(numnew/2)+1):numnew,:);\n w = w((floor(numnew/2)+1):numnew,:);\n end\n\n n1d(level) = length ( w );\n x1d{level} = x;\n w1d{level} = w;\n\n end\n%\n% Initialization.\n%\n minq = max ( 0, k - dim );\n maxq = k - 1;\n nodes = [];\n weights = [];\n%\n% Loop for max ( 0, K - DIM ) <= Q <= K - 1.\n%\n for q = minq : maxq\n\n r = length ( weights );\n%\n% BQ is the combinatorial coefficient applied to the component\n% product rules which have level Q.\n%\n bq = ( -1 )^( maxq - q ) * nchoosek ( dim - 1, dim + q - k );\n%\n% Compute the D-dimensional row vectors that sum to DIM+Q.\n%\n is = get_seq ( dim, dim + q );\n%\n% Preallocate new rows for nodes and weights.\n%\n Rq = prod ( n1d(is), 2 );\n sRq = sum ( Rq );\n nodes = [ nodes; zeros(sRq,dim) ];\n weights = [ weights; zeros(sRq,1) ];\n%\n% Generate each of the product rules indicated by IS, and\n% insert them into NODES and WEIGHTS.\n%\n for j = 1 : size(is,1)\n midx = is(j,:);\n [ newn, neww ] = tensor_product ( x1d(midx), w1d(midx) );\n nodes((r+1):(r+Rq(j)),:) = newn;\n weights((r+1):(r+Rq(j))) = bq .* neww;\n r = r + Rq(j);\n end\n%\n% Sort the nodes and merge repeated values.\n%\n [ nodes, sortvec ] = sortrows ( nodes );\n weights = weights(sortvec);\n keep = 1; \n lastkeep = 1;\n\n for j = 2 : size(nodes,1)\n if ( compress )\n\n if ( nodes(j,:) == nodes(j-1,:) ) \n weights(lastkeep) = weights(lastkeep) + weights(j);\n else\n lastkeep = j;\n keep = [ keep ; j ];\n end\n else\n lastkeep = j;\n keep = [ keep ; j ];\n end\n end\n\n nodes = nodes(keep,:);\n weights = weights(keep);\n\n end\n%\n% The rule has been computed.\n% If we used symmetry, we now have to extend the rule.\n%\n if ( sym )\n\n nr = length ( weights );\n m = x1d{1};\n\n for j = 1 : dim\n\n keep = zeros(nr,1);\n numnew = 0;\n\n for r = 1 : nr \n if ( nodes(r,j) ~= m )\n numnew = numnew + 1;\n keep(numnew) = r;\n end\n end\n\n if ( 0 < numnew )\n nodes = [nodes ; nodes(keep(1:numnew),:)];\n nodes(nr+1:nr+numnew,j) = 2*m - nodes(nr+1:nr+numnew,j);\n weights = [weights ; weights(keep(1:numnew))]; \n nr = nr + numnew;\n end\n\n end\n\n [ nodes, sortvec ] = sortrows ( nodes );\n weights = weights(sortvec);\n\n end\n\n r_size = length ( weights );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/truncated_normal_sparse_grid/nwspgr_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.622084162186855}} {"text": "function [ n_data, x, fx ] = tran09_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TRAN09_VALUES returns some values of the order 9 transportation function.\n%\n% Discussion:\n%\n% The function is defined by:\n%\n% TRAN09(x) = Integral ( 0 <= t <= x ) t^9 * exp(t) / ( exp(t) - 1 )^2 dt\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Allan McLeod,\n% Algorithm 757, MISCFUN: A software package to compute uncommon\n% special functions,\n% ACM Transactions on Mathematical Software,\n% Volume 22, Number 3, September 1996, pages 288-301.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 20;\n\n fx_vec = [ ...\n 0.26469772870084897671E-22, ...\n 0.11367943653594246210E-12, ...\n 0.74428246255329800255E-08, ...\n 0.48022728485415366194E-03, ...\n 0.11700243014358676725E+00, ...\n 0.27648973910899914391E+01, ...\n 0.24716631405829192997E+02, ...\n 0.12827119828849828583E+03, ...\n 0.46842894800662208986E+03, ...\n 0.31673967371627895718E+04, ...\n 0.46140886546630195390E+04, ...\n 0.11952718545392302185E+05, ...\n 0.20001612666477027728E+05, ...\n 0.31011073271851366554E+05, ...\n 0.10352949905541130133E+06, ...\n 0.19743173017140591390E+06, ...\n 0.33826030414658460679E+06, ...\n 0.36179607036750755227E+06, ...\n 0.36360622124777561525E+06, ...\n 0.36360880558827162725E+06 ];\n\n x_vec = [ ...\n 0.0019531250E+00, ...\n 0.0312500000E+00, ...\n 0.1250000000E+00, ...\n 0.5000000000E+00, ...\n 1.0000000000E+00, ...\n 1.5000000000E+00, ...\n 2.0000000000E+00, ...\n 2.5000000000E+00, ...\n 3.0000000000E+00, ...\n 4.0000000000E+00, ...\n 4.2500000000E+00, ...\n 5.0000000000E+00, ...\n 5.5000000000E+00, ...\n 6.0000000000E+00, ...\n 8.0000000000E+00, ...\n 10.0000000000E+00, ...\n 15.0000000000E+00, ...\n 20.0000000000E+00, ...\n 30.0000000000E+00, ...\n 50.0000000000E+00 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n fx = 0.0;\n else\n x = x_vec(n_data);\n fx = fx_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/tran09_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6220841516739906}} {"text": "function price = PROJ_Parisian(N, call, down, S_0, W, H, M, r, rnCHF, T, Gamm, resetting, alph)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for Parisian-style barrier options using PROJ method\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n% Author: Justin Lars Kirkby\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% S_0 = initial stock price (e.g. 100)\n% W = strike (e.g. 100)\n% r = interest rate (e.g. 0.05)\n% T = time remaining until maturity (in years, e.g. T=1)\n% M = number of subintervals of [0,T] (total of M+1 monitoring points in time grid, including S_0)\n% call = 1 for call (else put)\n% down = 1 for down and out (otherwise it's up and out)\n% H = barrier\n% Gamm = maximum number of discretely monitored excursions into the knockout region allowed (more than this results in knockout)\n% resetting = 1 if a reseting type parisian option (otherwise its cumulative, ie never resets)\n% rnCHF = risk netural characteristic function (function handle with single argument)\n%\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% alph = grid with is 2*alph\n% N = number of grid/basis points (power of 2, e.g. 2^12), resolution = 2*alph/(N-1)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~(down == 1 && call ~= 1) && ~(down ~=1 && call == 1)\n fprintf('Sorry, currently only Up and out calls, and down and out puts have been coded \\n')\n return\nend\n\ngamm0 = 1; %HARDCODED: this param would allow us to specify an inital consumed budget, in case of in-progress valuation\n\ndt = T/M;\nnrdt = -r*dt;\nh = log(H/S_0);\nlws = log(W/S_0);\n\n%%%%%% Gaussian Quad Constants\nq_plus = (1 + sqrt(3/5))/2; q_minus = (1 - sqrt(3/5))/2;\nb3 = sqrt(15); b4 = b3/10;\n\ndx = 2*alph/(N-1); \nxmin = -alph/2;\n\nn_h = floor((h-xmin)/dx +1); \nxmin = h - (n_h -1)*dx; %realign so that h is on the grid (this is important for the case where h = 0)\n\n\nif h~= 0 %Realign so that h and 0 are both members of grid (if possible)\n nnot = floor(1-xmin/dx);\n if abs(h) > dx %so that n_h ~= nnot\n dx = (h - 0)/(n_h - nnot);\n xmin = dx*(1-nnot); %hence nnot should remain on the grid\n %n_h = floor((h-xmin)/dx +1); %NOT Numerically Stable\n n_h = floor(nnot + h/dx); %Numerically Stable\n end\nelse \n nnot = n_h; \nend\n\na = 1/dx;\na2 = a^2;\nzmin = (1 - N/2)*dx; %Kbar corresponds to zero\n\n%Cons = 24*a2/N;\nCons2 = 24*a2*exp(nrdt)/N;\ndw = 2*pi*a/N;\ngrand = dw*(1:N-1);\ngrand = exp(-1i*zmin*grand).*rnCHF(grand).*(sin(grand/(2*a))./grand).^2./(2+cos(grand/a));\nbeta = Cons2*real(fft([1/(24*a2) grand])); %%%% NOTE: all toep matrices incorporate exp(-r*dt)\n\n\ninterp_Atend = 0;\nif 0 < abs(h) && abs(h) 100 Extreme evidence for H1\n% 30 – 100 Very strong evidence for H1\n% 10 – 30 Strong evidence for H1\n% 3 – 10 Moderate evidence for H1\n% 1 – 3 Anecdotal evidence for H1\n% 1 No evidence\n% 1/3 – 1 Anecdotal evidence for H0\n% 1/3 – 1/10 Moderate evidence for H0\n% 1/10 – 1/30 Strong evidence for H0\n% 1/30 – 1/100 Very strong evidence for H0\n% < 1/100 Extreme evidence for H0\n%\n% Use this function by calling one of the high-level statistics functions as\n% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)\n% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)\n% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)\n% with the following configuration option:\n% cfg.statistic = 'ft_statfun_bayesfactor'\n%\n% The experimental design is specified as:\n% cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1)\n% cfg.uvar = optional, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2)\n%\n% The labels for the independent variable should be specified as the number 1 and 2.\n% The labels for the unit of observation should be integers ranging from 1 to the\n% total number of observations (subjects or trials).\n%\n% The cfg.uvar option is only needed for paired data, you should leave it empty\n% for non-paired data.\n%\n% See https://www.statisticshowto.datasciencecentral.com/bayes-factor-definition/ for some background.\n%\n% See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS\n\n% Copyright (C) 2020, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% ensure that the required toolbox dependency is on the path\nft_hastoolbox('bayesFactor', 1);\n\n% set the defaults\ncfg.ivar = ft_getopt(cfg, 'ivar', 1);\ncfg.uvar = ft_getopt(cfg, 'uvar', []); % default is empty, which means non-paired\n\nif isempty(cfg.uvar)\n sel1 = find(design(cfg.ivar,:)==1); % select replications that belong to condition 1\n sel2 = find(design(cfg.ivar,:)==2); % select replications that belong to condition 2\n n1 = length(sel1);\n n2 = length(sel2);\n \n x1 = dat(:,sel1);\n x2 = dat(:,sel2);\n \n nchan = size(x1, 1);\n bf10 = nan(nchan, 1);\n prob = nan(nchan, 1);\n ci_lo = nan(nchan, 1);\n ci_hi = nan(nchan, 1);\n tstat = nan(nchan, 1);\n diff = mean(x1, 2) - mean(x2, 2); % this is the raw effect size\n \n for i=1:nchan\n [bf10(i), prob(i), CI, stats] = bf.ttest2(x1(i,:), x2(i,:));\n ci_lo(i) = CI(1);\n ci_hi(i) = CI(2);\n tstat(i) = stats.tstat;\n end\n \nelse\n subj = unique(design(cfg.uvar,:)); % it can also be paired over trials\n \n n = length(subj);\n sel1 = nan(size(subj));\n sel2 = nan(size(subj));\n for i=1:n\n sel1(i) = find(design(cfg.uvar,:)==subj(i) & design(cfg.ivar,:)==1);\n sel2(i) = find(design(cfg.uvar,:)==subj(i) & design(cfg.ivar,:)==2);\n end\n x1 = dat(:,sel1);\n x2 = dat(:,sel2);\n \n nchan = size(x1, 1);\n bf10 = nan(nchan, 1);\n prob = nan(nchan, 1);\n ci_lo = nan(nchan, 1);\n ci_hi = nan(nchan, 1);\n tstat = nan(nchan, 1);\n diff = mean(x1 - x2, 2); % this is the raw effect size\n \n for i=1:nchan\n [bf10(i), prob(i), CI, stats] = bf.ttest(x1(i,:) - x2(i,:));\n ci_lo(i) = CI(1);\n ci_hi(i) = CI(2);\n tstat(i) = stats.tstat;\n end\n \nend % if uvar\n\n% return the results for all channel-time-frequency points, for all voxels, or for all source locations\nstat.bf10 = bf10(:);\nstat.prob = prob(:);\nstat.diff = diff(:);\nstat.ci_lo = ci_lo(:);\nstat.ci_hi = ci_hi(:);\nstat.tstat = tstat(:);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/statfun/ft_statfun_bayesfactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321936479701, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6218219745451526}} {"text": "function [logp, yhat, res] = tapas_logrt_linear_whatworld(r, infStates, ptrans)\n% Calculates the log-probability of log-reaction times y (in units of log-ms) according to the\n% linear log-RT model developed with Louise Marshall and Sven Bestmann\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2014 Christoph Mathys, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Transform zetas to their native space\nbe0 = ptrans(1);\nbe1 = ptrans(2);\nbe2 = ptrans(3);\nbe3 = ptrans(4);\nze = exp(ptrans(5));\n\n% Initialize returned log-probabilities, predictions,\n% and residuals as NaNs so that NaN is returned for all\n% irregualar trials\nn = size(infStates,1);\nlogp = NaN(n,1);\nyhat = NaN(n,1);\nres = NaN(n,1);\n\n% Weed irregular trials out from responses and inputs\ny = r.y(:,1);\ny(r.irr) = [];\n\nu = r.u(:,1);\nu(r.irr) = [];\n\n% Extract trajectories of interest from infStates\nmu1hat = squeeze(infStates(:,1,:,:,1));\nmu1 = squeeze(infStates(:,1,:,:,3));\nmu2 = squeeze(infStates(:,2,:,:,3));\nsa2 = squeeze(infStates(:,2,:,:,4));\nmu3 = squeeze(infStates(:,3,1,1,3));\n\n% Surprise\n% ~~~~~~~~\n\n% mu1 contains the actually occurring transition -> multiply with\n% mu1hat to get probability of that transition (other elements are\n% zero)\notp = mu1.*mu1hat; % observed transition probabilities (3-dim)\notps3 = sum(otp, 3, 'omitnan'); % sum over 3rd dim\notps23 = sum(otps3, 2, 'omitnan'); % sum over 2nd dim\n\nsurp = -log(otps23);\nsurp(r.irr) = [];\n\n% Expected uncertainty\n% ~~~~~~~~~~~~~~~~~~~~\neuo = mu1.*sa2; % expected uncertainty of observed transition (3-dim)\neuos3 = sum(euo, 3, 'omitnan'); % sum over 3rd dim\neuos23 = sum(euos3, 2, 'omitnan'); % sum over 2nd dim\n\nto = mu1.*mu2; % tendency of observed transition (3-dim)\ntos3 = sum(to, 3, 'omitnan'); % sum over 3rd dim\ntos23 = sum(tos3, 2, 'omitnan'); % sum over 2nd dim\n\neu = tapas_sgm(tos23,1).*(1-tapas_sgm(tos23,1)).*euos23; % transform down to 1st level\neu(r.irr) = [];\n\n% Unexpected uncertainty\n% ~~~~~~~~~~~~~~~~~~~~~~\nueu = tapas_sgm(tos23,1).*(1-tapas_sgm(tos23,1)).*exp(mu3); % transform down to 1st level\nueu(r.irr) = [];\n\n% Calculate predicted log-reaction time\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nlogrt = be0 +be1.*surp +be2.*eu +be3.*ueu;\n\n% Calculate log-probabilities for non-irregular trials\n% Note: 8*atan(1) == 2*pi (this is used to guard against\n% errors resulting from having used pi as a variable).\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = -1/2.*log(8*atan(1).*ze) -(y-logrt).^2./(2.*ze);\nyhat(reg) = logrt;\nres(reg) = y-logrt;\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_logrt_linear_whatworld.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6218093599108958}} {"text": "gammaln(0.1) - 2.2527126517342059598697\ngammaln(0.6) - .39823385806923489961685\ngammaln(0.7) - .26086724653166651438573\ngammaln(1.0)\ngammaln(2.0)\ngammaln(3.4) - 1.0923280598027415674947\ngammaln(4.0) - 1.791759469228055000812477\ngammaln(8.0) - 8.525161361065414300165531\ngammaln(64.0) - 201.00931639928152667928\ngammaln(256.0) - 1161.71210111840065079\nif gammaln(0) ~= Inf\n error('gammaln(0) should be Inf');\nend\nif ~isnan(gammaln(-1))\n error('gammaln(-1) should be NaN');\nend\nif gammaln(Inf) ~= Inf\n error('gammaln(Inf) should be Inf');\nend\n% should be NaN?\ngammaln(-Inf)\nif ~isnan(gammaln(NaN))\n error('gammaln(NaN) should be NaN');\nend\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/endres/proposals/external/lightspeed/tests/test_gammaln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6217814473841744}} {"text": "function phi = basis_brick27 ( n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_BRICK20: BRICK20 basis functions at natural coordinates.\n%\n% Discussion:\n%\n% 8----19---7\n% /| /\n% 20 | 26 /|\n% / / |\n% 5----17----6 |\n% | | | |\n% | 16---24-|-15\n% | /| | /|\n% |25 | 27 |23| t\n% |/ |/ | | s\n% 13----22---14 | | /\n% | | | | | /\n% | | | | |/\n% | 4--11--|--3 0---------r\n% | / | /\n% | 12 21 |10\n% |/ |/\n% 1----9-----2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real P(3,N), natural coordinates of evaluation points.\n%\n% Output, real PHI(27,N), the basis function values.\n%\n rm(1:n) = p(1,1:n) + 1.0;\n rz(1:n) = p(1,1:n);\n rp(1:n) = p(1,1:n) - 1.0;\n\n sm(1:n) = p(2,1:n) + 1.0;\n sz(1:n) = p(2,1:n);\n sp(1:n) = p(2,1:n) - 1.0;\n\n tm(1:n) = p(3,1:n) + 1.0;\n tz(1:n) = p(3,1:n);\n tp(1:n) = p(3,1:n) - 1.0;\n\n phi(1,1:n) = rz .* rp .* sz .* sp .* tz .* tp / 8.0;\n phi(2,1:n) = rm .* rz .* sz .* sp .* tz .* tp / 8.0;\n phi(3,1:n) = rm .* rz .* sm .* sz .* tz .* tp / 8.0;\n phi(4,1:n) = rz .* rp .* sm .* sz .* tz .* tp / 8.0;\n phi(5,1:n) = rz .* rp .* sz .* sp .* tm .* tz / 8.0;\n phi(6,1:n) = rm .* rz .* sz .* sp .* tm .* tz / 8.0;\n phi(7,1:n) = rm .* rz .* sm .* sz .* tm .* tz / 8.0;\n phi(8,1:n) = rz .* rp .* sm .* sz .* tm .* tz / 8.0;\n\n phi(9,1:n) = - rm .* rp .* sz .* sp .* tz .* tp / 4.0;\n phi(10,1:n) = - rm .* rz .* sm .* sp .* tz .* tp / 4.0;\n phi(11,1:n) = - rm .* rp .* sm .* sz .* tz .* tp / 4.0;\n phi(12,1:n) = - rz .* rp .* sm .* sp .* tz .* tp / 4.0;\n phi(13,1:n) = - rz .* rp .* sz .* sp .* tm .* tp / 4.0;\n phi(14,1:n) = - rm .* rz .* sz .* sp .* tm .* tp / 4.0;\n phi(15,1:n) = - rm .* rz .* sm .* sz .* tm .* tp / 4.0;\n phi(16,1:n) = - rz .* rp .* sm .* sz .* tm .* tp / 4.0;\n phi(17,1:n) = - rm .* rp .* sz .* sp .* tm .* tz / 4.0;\n phi(18,1:n) = - rm .* rz .* sm .* sp .* tm .* tz / 4.0;\n phi(19,1:n) = - rm .* rp .* sm .* sz .* tm .* tz / 4.0;\n phi(20,1:n) = - rz .* rp .* sm .* sp .* tm .* tz / 4.0;\n\n phi(21,1:n) = rm .* rp .* sm .* sp .* tz .* tp / 2.0;\n phi(22,1:n) = rm .* rp .* sz .* sp .* tm .* tp / 2.0;\n phi(23,1:n) = rm .* rz .* sm .* sp .* tm .* tp / 2.0;\n phi(24,1:n) = rm .* rp .* sm .* sz .* tm .* tp / 2.0;\n phi(25,1:n) = rz .* rp .* sm .* sp .* tm .* tp / 2.0;\n phi(26,1:n) = rm .* rp .* sm .* sp .* tm .* tz / 2.0;\n\n phi(27,1:n) = - rm .* rp .* sm .* sp .* tm .* tp;\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/fem3d_pack/basis_brick27.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.621781441688667}} {"text": "function alpha = backtracking_line_search_prox(problem, w, alpha, rho) \n% This is a proximal backtracking algorithm.\n%\n% Inputs:\n% problem function (cost/grad/hess)\n% w current point\n% alpha current stepsize\n% rho shrink constant (<1)\n% Output:\n% alpha new stepsize\n%\n% References:\n% \n% \n% This file is part of SGDLibrary.\n% \n% Created by H.Kasai on Nov. 19, 2018.\n% \n% F(x) := f(x) + g(x);\n \n \n w0 = w;\n \n %% f0\n % calculate f0\n% F0 = problem.calculate_cost(w0);\n% reg0 = problem.calculate_reg(w0);\n% g0 = problem.lambda * reg0;\n% f0 = F0 - g0;\n f0 = problem.differentiable_cost(w0); \n \n % calculate g0\n grad0 = problem.full_grad(w0);\n \n % w = w - alpha * grads0\n w_out = w0 - alpha * grad0;\n \n % prox\n w_out = problem.prox(w_out, alpha); \n \n \n %% f1\n fk = problem.differentiable_cost(w_out);\n \n diff = w_out - w0;\n \n while fk > f0 + grad0'*diff + 1/(2*alpha) * (diff'*diff)\n alpha = rho * alpha;\n \n % w = w - alpha * grads0\n w_out = w0 - alpha * grad0;\n \n % prox\n w_out = problem.prox(w_out, alpha); \n \n %% fk\n fk = problem.differentiable_cost(w_out);\n diff = w_out - w0;\n \n end \n \n \n% while fk >= f0 + grad_f(x)'*z + (0.5/step)*norm(z,2)^2\n% lambda = rho * step;\n% z = prox(x - lambda*grad_f(x),lambda*g);\n% end \n \nend\n\n", "meta": {"author": "hiroyuki-kasai", "repo": "SGDLibrary", "sha": "d19a12559c79c3726683243885b15f982f4bec3d", "save_path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary", "path": "github-repos/MATLAB/hiroyuki-kasai-SGDLibrary/SGDLibrary-d19a12559c79c3726683243885b15f982f4bec3d/gd_solver/backtracking_line_search_prox.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6217759838221469}} {"text": "function [a,ass] = bipartiteMatchingIntProg(dst, nmatches)\n% BIPARTITEMATCHINGINTPROG Use binary integer programming (linear objective) to solve for optimal linear assignment\n% function a = bipartiteMatchingIntProg(dst)\n% a(i) = best matching column for row i\n% \n% This gives the same result as bipartiteMatchingHungarian.\n%\n% function a = bibpartiteMatchingIntProg(dst, nmatches)\n% only matches the specified number (must be <= min(size(dst))).\n% This can be used to allow outliers in both source and target.\n%\n% For details, see Marciel & Costeira, \"A global solution to sparse correspondence\n% problems\", PAMI 25(2), 2003\n\nif nargin < 2, nmatches = []; end\n\n[p1 p2] = size(dst);\np1orig = p1; p2orig = p2;\ndstorig = dst;\n\nif isempty(nmatches) % no outliers allowed (modulo size difference)\n % ensure matrix is square\n m = max(dst(:));\n if p1p2\n dst = [dst m*ones(p1, p1-p2)];\n end\nend\n[p1 p2] = size(dst);\n\n\nc = dst(:); % vectorize cost matrix\n\n% row-sum: ensure each column sums to 1\nA2 = kron(eye(p2), ones(1,p1));\nb2 = ones(p2,1);\n\n% col-sum: ensure each row sums to 1\nA3 = kron(ones(1,p2), eye(p1));\nb3 = ones(p1,1);\n\nif isempty(nmatches)\n % enforce doubly stochastic\n A = [A2; A3];\n b = [b2; b3];\n Aineq = zeros(1, p1*p2);\n bineq = 0;\nelse\n nmatches = min([nmatches, p1, p2]);\n Aineq = [A2; A3];\n bineq = [b2; b3]; % row and col sums <= 1\n A = ones(1,p1*p2);\n b = nmatches; % total num matches = b (otherwise get degenerate soln)\nend\n\n\nass = bintprog(c, Aineq, bineq, A, b);\nass = reshape(ass, p1, p2);\n\na = zeros(1, p1orig);\nfor i=1:p1orig\n ndx = find(ass(i,:)==1);\n if ~isempty(ndx) & (ndx <= p2orig)\n a(i) = ndx;\n end\nend\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/KPMtools/bipartiteMatchingIntProg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6217759650055954}} {"text": "function C = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse)\n\n% fdct_wrapping.m - Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0\n%\n% Inputs\n% x M-by-N matrix\n%\n% Optional Inputs\n% is_real Type of the transform\n% 0: complex-valued curvelets\n% 1: real-valued curvelets\n% [default set to 0]\n% finest Chooses one of two possibilities for the coefficients at the\n% finest level:\n% 1: curvelets\n% 2: wavelets\n% [default set to 2]\n% nbscales number of scales including the coarsest wavelet level\n% [default set to ceil(log2(min(M,N)) - 3)]\n% nbangles_coarse\n% number of angles at the 2nd coarsest level, minimum 8,\n% must be a multiple of 4. [default set to 16]\n%\n% Outputs\n% C Cell array of curvelet coefficients.\n% C{j}{l}(k1,k2) is the coefficient at\n% - scale j: integer, from finest to coarsest scale,\n% - angle l: integer, starts at the top-left corner and\n% increases clockwise,\n% - position k1,k2: both integers, size varies with j\n% and l.\n% If is_real is 1, there are two types of curvelets,\n% 'cosine' and 'sine'. For a given scale j, the 'cosine'\n% coefficients are stored in the first two quadrants (low\n% values of l), the 'sine' coefficients in the last two\n% quadrants (high values of l). \n%\n% See also ifdct_wrapping.m, fdct_wrapping_param.m\n%\n% By Laurent Demanet, 2004\n\nX = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)));\n[N1,N2] = size(X);\nif nargin < 2, is_real = 0; end;\nif nargin < 3, finest = 2; end;\nif nargin < 4, nbscales = ceil(log2(min(N1,N2)) - 3); end;\nif nargin < 5, nbangles_coarse = 16; end;\n\n% Initialization: data structure\nnbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];\nif finest == 2, nbangles(nbscales) = 1; end;\nC = cell(1,nbscales);\nfor j = 1:nbscales\n C{j} = cell(1,nbangles(j));\nend;\n\n% Loop: pyramidal scale decomposition\nM1 = N1/3;\nM2 = N2/3;\nif finest == 1,\n\n % Initialization: smooth periodic extension of high frequencies\n bigN1 = 2*floor(2*M1)+1;\n bigN2 = 2*floor(2*M2)+1;\n equiv_index_1 = 1+mod(floor(N1/2)-floor(2*M1)+(1:bigN1)-1,N1);\n equiv_index_2 = 1+mod(floor(N2/2)-floor(2*M2)+(1:bigN2)-1,N2);\n X = X(equiv_index_1,equiv_index_2);\n % Invariant: equiv_index_1(floor(2*M1)+1) == (N1 + 2 - mod(N1,2))/2\n % is the center in frequency. Same for M2, N2.\n window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);\n window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);\n % Invariant: floor(M1) + floor(2*M1) == N1 - (mod(M1,3)~=0)\n % Same for M2, N2.\n coord_1 = 0:(1/window_length_1):1;\n coord_2 = 0:(1/window_length_2):1;\n [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;\n lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;\n lowpass = lowpass_1'*lowpass_2;\n Xlow = X .* lowpass;\n\n scales = nbscales:-1:2;\n\nelse\n \n M1 = M1/2;\n M2 = M2/2;\n window_length_1 = floor(2*M1) - floor(M1) - 1;\n window_length_2 = floor(2*M2) - floor(M2) - 1;\n coord_1 = 0:(1/window_length_1):1;\n coord_2 = 0:(1/window_length_2):1;\n [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n lowpass = lowpass_1'*lowpass_2;\n hipass = sqrt(1 - lowpass.^2);\n Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + ceil((N1+1)/2);\n Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + ceil((N2+1)/2);\n Xlow = X(Xlow_index_1, Xlow_index_2) .* lowpass;\n Xhi = X;\n Xhi(Xlow_index_1, Xlow_index_2) = Xhi(Xlow_index_1, Xlow_index_2) .* hipass;\n C{nbscales}{1} = fftshift(ifft2(ifftshift(Xhi)))*sqrt(prod(size(Xhi)));\n if is_real, C{nbscales}{1} = real(C{nbscales}{1}); end;\n \n scales = (nbscales-1):-1:2;\n\nend;\nfor j = scales,\n\n M1 = M1/2;\n M2 = M2/2;\n window_length_1 = floor(2*M1) - floor(M1) - 1;\n window_length_2 = floor(2*M2) - floor(M2) - 1;\n coord_1 = 0:(1/window_length_1):1;\n coord_2 = 0:(1/window_length_2):1;\n [wl_1,wr_1] = fdct_wrapping_window(coord_1);\n [wl_2,wr_2] = fdct_wrapping_window(coord_2);\n lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];\n lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];\n lowpass = lowpass_1'*lowpass_2;\n hipass = sqrt(1 - lowpass.^2);\n Xhi = Xlow; % size is 2*floor(4*M1)+1 - by - 2*floor(4*M2)+1\n Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;\n Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;\n Xlow = Xlow(Xlow_index_1, Xlow_index_2);\n Xhi(Xlow_index_1, Xlow_index_2) = Xlow .* hipass;\n Xlow = Xlow .* lowpass; % size is 2*floor(2*M1)+1 - by - 2*floor(2*M2)+1\n \n % Loop: angular decomposition\n l = 0;\n nbquadrants = 2 + 2*(~is_real);\n nbangles_perquad = nbangles(j)/4;\n for quadrant = 1:nbquadrants\n M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);\n M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);\n if mod(nbangles_perquad,2),\n wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];\n else\n wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);\n wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;\n wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];\n end;\n wedge_endpoints = wedge_ticks(2:2:(end-1)); % integers\n wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;\n % integers or half-integers\n \n % Left corner wedge\n l = l+1;\n first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);\n length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);\n Y_corner = 1:length_corner_wedge;\n [XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);\n width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;\n slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);\n left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));\n % integers\n [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n % Coordinates of the top-left corner of the wedge wrapped\n % around the origin. Some subtleties when the wedge is\n % even-sized because of the forthcoming 90 degrees rotation\n for row = Y_corner\n cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n admissible_cols = round(1/2*(cols+1+abs(cols-1)));\n new_row = 1 + mod(row - first_row, length_corner_wedge);\n wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols > 0);\n wrapped_XX(new_row,:) = XX(row,admissible_cols);\n wrapped_YY(new_row,:) = YY(row,admissible_cols);\n end;\n slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);\n mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);\n % not integers in general\n coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...\n (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);\n wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...\n wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;\n coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...\n (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));\n wl_left = fdct_wrapping_window(coord_corner);\n [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n wrapped_data = wrapped_data .* (wl_left .* wr_right);\n\n switch is_real\n case 0\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n case 1\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n C{j}{l} = sqrt(2)*real(x);\n C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n end;\n \n % Regular wedges\n length_wedge = floor(4*M_vert) - floor(M_vert);\n Y = 1:length_wedge;\n first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...\n mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n for subl = 2:(nbangles_perquad-1);\n l = l+1;\n width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;\n slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);\n left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));\n [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));\n first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n for row = Y\n cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n new_row = 1 + mod(row - first_row, length_wedge);\n wrapped_data(new_row,:) = Xhi(row,cols);\n wrapped_XX(new_row,:) = XX(row,cols);\n wrapped_YY(new_row,:) = YY(row,cols); \n end;\n slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);\n mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);\n coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...\n (wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);\n slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);\n mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);\n coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...\n (wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);\n wl_left = fdct_wrapping_window(coord_left);\n [wl_right,wr_right] = fdct_wrapping_window(coord_right);\n wrapped_data = wrapped_data .* (wl_left .* wr_right);\n switch is_real\n case 0\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n case 1\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n C{j}{l} = sqrt(2)*real(x);\n C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n end;\n end;\n\n % Right corner wedge\n l = l+1;\n width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);\n slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);\n left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));\n [wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));\n first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...\n mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));\n first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...\n mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));\n for row = Y_corner\n cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);\n admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));\n new_row = 1 + mod(row - first_row, length_corner_wedge);\n wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols <= (2*floor(4*M_horiz)+1));\n wrapped_XX(new_row,:) = XX(row,admissible_cols);\n wrapped_YY(new_row,:) = YY(row,admissible_cols);\n end;\n slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);\n mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);\n coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...\n (wrapped_XX - mid_line_left)./(floor(4*M_vert) + 1 - wrapped_YY);\n C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));\n C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);\n wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) = ...\n wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) - 1;\n coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...\n ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));\n wl_left = fdct_wrapping_window(coord_left);\n [wl_right,wr_right] = fdct_wrapping_window(coord_corner);\n\n wrapped_data = wrapped_data .* (wl_left .* wr_right);\n switch is_real\n case 0\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n case 1\n wrapped_data = rot90(wrapped_data,-(quadrant-1));\n x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));\n C{j}{l} = sqrt(2)*real(x);\n C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);\n end;\n\n if quadrant < nbquadrants, Xhi = rot90(Xhi); end;\n end;\nend;\n\n% Coarsest wavelet level\nC{1}{1} = fftshift(ifft2(ifftshift(Xlow)))*sqrt(prod(size(Xlow)));\nif is_real == 1,\n C{1}{1} = real(C{1}{1});\nend;\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/fdct_wrapping_matlab/fdct_wrapping.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6217706059683965}} {"text": "function [S,m,psi] = ComputeStokesQuad(HH,HV,VH,VV,SmoothSize)\n%COMPUTESTOKESQUAD: Alpha/Entropy approximation for quad pol data (used\n%Stokes for dual so we're keeping the name for consistency)\n\n%Pauli basis\nP_11 = fastrunmean(abs(HH+VV).*abs(HH+VV),[SmoothSize SmoothSize],'mean');\nP_22 = fastrunmean(abs(HH-VV).*abs(HH-VV),[SmoothSize SmoothSize],'mean');\nP_33 = fastrunmean(abs(HV-VH).*abs(HV-VH),[SmoothSize SmoothSize],'mean');\n\n%span is the trace of the Pauli basis\nS = P_11 + P_22 + P_33;\n\nN_11 = P_11./S;\nN_22 = P_22./S;\nN_33 = P_33./S;\n\nFrob = sqrt(N_11.*N_11 + N_22.*N_22 + N_33.*N_33);\nm = 1.5*(1-Frob.*Frob);\npsi = acosd(sqrt(N_11));\n%psi = (pi/2)*(1-N_11);\n\n\nend\n\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/Tools/ApertureTool/ComputeStokesQuad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.621698978835731}} {"text": "function K=compute_permutation_constraint4(V)\n\n% Copyright (C) <2007> \n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the version 3 of the GNU General Public License\n% as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details. \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, September 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\n\n\n%[B11,B12,...,B33]=lambda1*v1+lambda2*v2+lambda3*v3\n\nN=size(V,2); %dimension of the kernel\nn=4; %dimension of Bij\nidx=[1 2 3 4; 2 5 6 7; 3 6 8 9; 4 7 9 10];\n\n%1.-Generation of the first set of equations Bii.Bjj=Bij.Bii (n(n-1)/2 eqs).\nnrowsK=n*(n-1)/2+n*(n-1)*n/2;\nncolsK=N*(N+1)/2;\nK=zeros(nrowsK,ncolsK);\n\nt=1;\nfor i=1:n\n for j=i+1:n\n offset=1;\n for a=1:N\n for b=a:N\n if a==b\n K(t,offset)=V(idx(i,i),a)*V(idx(j,j),a)-V(idx(i,j),a)*V(idx(i,j),a);\n else\n K(t,offset)=V(idx(i,i),a)*V(idx(j,j),b)-V(idx(i,j),a)*V(idx(i,j),b)+...\n V(idx(i,i),b)*V(idx(j,j),a)-V(idx(i,j),b)*V(idx(i,j),a);\n end\n offset=offset+1;\n end\n \n end\n t=t+1;\n %fprintf('t:%d\\t offset:%d\\n',t,offset);\n end\nend\n\n\nfor k=1:n\n for j=k:n\n for i=1:n\n if (i~=j & i~=k)\n offset=1;\n for a=1:N\n for b=a:N\n if a==b\n K(t,offset)=V(idx(i,j),a)*V(idx(i,k),a)-V(idx(i,i),a)*V(idx(j,k),a);\n else\n K(t,offset)=V(idx(i,j),a)*V(idx(i,k),b)-V(idx(i,i),a)*V(idx(j,k),b)+...\n V(idx(i,j),b)*V(idx(i,k),a)-V(idx(i,i),b)*V(idx(j,k),a);\n end\n offset=offset+1;\n end\n \n end\n t=t+1;\n %fprintf('t:%d\\t offset:%d\\n',t,offset);\n end\n end\n end\nend\n \n \n \n \n \n", "meta": {"author": "cvlab-epfl", "repo": "EPnP", "sha": "f9d27b186d9c754b72e076b3843f47ad136e9799", "save_path": "github-repos/MATLAB/cvlab-epfl-EPnP", "path": "github-repos/MATLAB/cvlab-epfl-EPnP/EPnP-f9d27b186d9c754b72e076b3843f47ad136e9799/matlab/EPnP/compute_permutation_constraint4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6216976667847256}} {"text": "function [logp, yhat, res] = tapas_condhalluc_obs(r, infStates, ptrans)\n% Calculates the log-probability of response y=1 under the unit-square sigmoid model\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2015-2016 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Transform beta to its native space\nbe = exp(ptrans(1));\n\n% Initialize returned log-probabilities as NaNs so that NaN is\n% returned for all irregualar trials\nn = size(infStates,1);\nlogp = NaN(n,1);\nyhat = NaN(n,1);\nres = NaN(n,1);\n\n% Check input format\nif size(r.u,2) ~= 2\n error('tapas:hgf:CondHalluc:InputsIncompatible', 'Inputs incompatible with condhalluc_obs observation model. See tapas_condhalluc_obs_config.m.')\nend\n\n% Get true-positive rate corresponding to stimuli\ntp = r.u(:,2);\n\n% Weed irregular trials out\nmu1hat = infStates(:,1,1);\nmu1hat(r.irr) = [];\ny = r.y(:,1);\ny(r.irr) = [];\ntp(r.irr) = [];\n\n% Calculate belief x using Bayes' theorem\nx = tp.*mu1hat./(tp.*mu1hat + (1-mu1hat).^2);\n\n% Belief is mu1hat in trials where there is no tone\nx(find(tp==0)) = mu1hat(find(tp==0));\n\n% Calculate log-probabilities for non-irregular trials\nreg = ~ismember(1:n,r.irr);\nlogp(reg) = -log(1+exp(-be.*(2.*x-1).*(2.*y-1)));\nyhat(reg) = x;\nres(reg) = (y-x)./sqrt(x.*(1-x));\n\nreturn;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_condhalluc_obs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6216275200298526}} {"text": "function e = mgVcyclefracLap1d(A,r,pde,square,h,s,option)\n\nglobal mA\n\n%% Setting\nif ~isfield('option','smootherType')\n smootherType = option.smootherType;\nelse\n smootherType = 3; \nend\nif ~isfield('option','smootherstep')\n smoothingstep = option.smoothingstep;\nelse\n smoothingstep = 3; \nend\nif ~exist('smootherType','var'), smootherType = 3; end\n% mapping parameter\nif s == 0.5\n gamma = 1;\nelse\n gamma = 3/(2*s)+0.1;\nend\n\n%% line smoothing\nN = length(r);\nrold = r;\nx0 = square(1); x1 = square(2); \ny0 = square(3); y1 = square(4);\nnx = (x1-x0)/h+1; % number of grid points in x-direction\nny = (y1-y0)/h+1; % number of grid points in x-direction\n% 1D vector to 2D matrix\nr2d = reshape(r,ny,nx);\ne = zeros(N,1);\ne2d = reshape(e,ny,nx);\n% index for Red-Black smoothing\nnodeidx = reshape(1:N,ny,nx);\nredidx = 2:2:nx-1;\nblackidx = 3:2:nx-2; \nrlinear = nodeidx(:,redidx);\nblinear = nodeidx(:,blackidx);\nfor it = 1:smoothingstep\n switch smootherType\n case 0\n e = e + tril(A)\\r;\n r = rold - A*e;\n e2d = reshape(e,ny,nx); \n case 1\n for k = 2:nx-1 % only update interiori lines\n % form residual\n idx = (k-1)*ny+1:k*ny; % the end nodes is included?\n de = A(idx,idx)\\r2d(:,k);\n e2d(:,k) = e2d(:,k) + de;\n r2d(:,k) = 0; % exact solve\n if k2 % update left column\n % for left-to-right ordering, the left r(idx-ny) is zero\n r2d(:,k-1) = - A(idx-ny,idx)*de;\n end\n end\n case 2 % weighted Jacobi\n for k = 2:nx-1\n % form residual\n idx = (k-1)*ny+1:k*ny;\n de = A(idx,idx)\\r(idx);\n e(idx) = e(idx) + 0.25*de;\n end \n r = rold - A*e;\n case 3 % red-black block Gauss-Seidel\n idx = ny+1:2*ny;\n % 1: red lines\n de = A(idx,idx)\\r2d(:,redidx);\n e2d(:,redidx) = e2d(:,redidx) + de;\n % update residual\n r2d(:,redidx) = 0;\n r2d(:,blackidx) = r2d(:,blackidx)-reshape(A(blinear,rlinear)*de(:),ny,length(blackidx));\n % previous r2d(:,blackidx) = 0;\n % 2: black lines\n de = A(idx,idx)\\r2d(:,blackidx);\n e2d(:,blackidx) = e2d(:,blackidx) + de;\n % update residual\n r2d(:,blackidx) = 0;\n r2d(:,redidx) = -reshape(A(rlinear,blinear)*de(:),ny,length(redidx));\n % previous r2d(:,redidx) = 0; \n end\nend\n\n%% Transfer operator \n% prolongation and restriction in x-direction\nIx = prolongation1d(log2(nx-1)-1);\nRx = Ix';\n% prolongation and restriction in y-direction\nnxc = (nx - 1)/2 + 1;\nnyc = (ny - 1)/2 + 1;\n% geometric quantity\nMy = ny - 1; \nTyf = ((0:My)'/My).^gamma*(y1-y0) + y0;\nhf = diff(Tyf);\nMyc = nyc - 1;\nTyc = ((0:Myc)'/Myc).^gamma*(y1-y0) + y0;\nhc = diff(Tyc);\njc = 2:nyc-1; % interiori points in the coarse grid\nj = 2*jc-1; % index of coarse points in the fine grids\nalpha = zeros(1,nyc);\nbeta = zeros(1,nyc);\nalpha(jc) = hf(j)./hc(jc);\nbeta(jc) = hf(j-1)./hc(jc-1);\nalpha(1) = 1-beta(2);\njc = 2:(nyc-1);\njf = 2*jc-1; % index of coarse points in the fine grids\n% due to the Neumann boundary condition, 1 is included\nii = [1 jf 2 jf+1 jf-1];\njj = [1 jc 1 jc jc];\nss = [ones(1,nyc-1) alpha(1:nyc-1) beta(2:nyc-1)];\nIy = sparse(ii,jj,ss,ny,nyc);\nRy = Iy';\n\n%% Restriction\n% 1D vector to 2D matrix\n% r2d = reshape(r,ny,nx);\nrc2d = Ry*r2d*Ix;\nrc = rc2d(:);\n\n%% Coarse grid correction\n% option.solver = 'none';\n% [u,eqn] = fracLap1d(square,2*h,pde,option);\nlevel = -log2(h);\nAc = mA{level-1};\nfixedNode = [1:nyc (2:nxc-1)*nyc (nxc-1)*nyc+(1:nyc)];\nisBdNode = false(length(rc),1);\nisBdNode(fixedNode) = true;\nfreeNode = find(~isBdNode);\nif level <= 3\n ec = zeros(length(rc),1);\n ec(freeNode) = Ac(freeNode,freeNode)\\rc(freeNode);\nelse\n ec = mgVcyclefracLap1d(Ac,rc,pde,square,2*h,s,option);\nend\n\n%% Prolongation\n% 1D vector to 2D matrix\nec2d = reshape(ec,nyc,nxc);\ne2d = e2d + Iy*ec2d*Rx;\ne = e2d(:);\n% update residual when e updated. remember we are solving Ae = rold.\nr = rold - A*(e2d(:));\nr2d = reshape(r,ny,nx);\n\n%% Post-smoothing\nfor it = 1:smoothingstep\n switch smootherType\n case 0 % pointwise G-S smoothing\n e = e + triu(A)\\r;\n r = rold - A*e;\n e2d = reshape(e,ny,nx);\n case 1\n for k = nx-1:-1:2\n % form residual\n idx = (k-1)*ny+1:k*ny;\n de = A(idx,idx)\\r2d(:,k);\n e2d(:,k) = e2d(:,k) + de;\n r2d(:,k) = 0; \n if k < nx-1 % update right column\n % for right-to-left ordering, the right r(idx+ny) is zero\n r2d(:,k+1) = - A(idx+ny,idx)*de;\n end\n if k>2 % update previous column\n r2d(:,k-1) = r2d(:,k-1) - A(idx-ny,idx)*de;\n end\n end \n case 2 % weighted Jacobi\n for k = 1:nx\n % form residual\n idx = (k-1)*ny+1:k*ny;\n de = A(idx,idx)\\r(idx);\n e(idx) = e(idx) + 0.25*de;\n end \n r = rold - A*e; \n case 3 % red-black block Gauss-Seidel\n idx = ny+1:2*ny;\n % 1: red lines\n de = A(idx,idx)\\r2d(:,redidx);\n e2d(:,redidx) = e2d(:,redidx) + de;\n % update residual\n r2d(:,redidx) = 0;\n r2d(:,blackidx) = r2d(:,blackidx)-reshape(A(blinear,rlinear)*de(:),ny,length(blackidx));\n % previous r2d(:,blackidx) = 0;\n % 2: black lines\n de = A(idx,idx)\\r2d(:,blackidx);\n e2d(:,blackidx) = e2d(:,blackidx) + de;\n % update residual\n r2d(:,blackidx) = 0;\n r2d(:,redidx) = -reshape(A(rlinear,blinear)*de(:),ny,length(redidx));\n % previous r2d(:,redidx) = 0; \n end\nend\ne = e2d(:);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/mgVcyclefracLap1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6216275200298526}} {"text": "% This is material illustrating the methods from the book\n% Financial Modelling - Theory, Implementation and Practice with Matlab\n% source\n% Wiley Finance Series\n% ISBN 978-0-470-74489-5\n%\n% Date: 02.05.2012\n%\n% Authors: Joerg Kienitz\n% Daniel Wetterau\n%\n% Please send comments, suggestions, bugs, code etc. to\n% kienitzwetterau_FinModelling@gmx.de\n%\n% (C) Joerg Kienitz, Daniel Wetterau\n% \n% Since this piece of code is distributed via the mathworks file-exchange\n% it is covered by the BSD license \n%\n% This code is being provided solely for information and general \n% illustrative purposes. The authors will not be responsible for the \n% consequences of reliance upon using the code or for numbers produced \n% from using the code.\n\nfunction y = sabrtmax(asabr,b,r,nsabr,f,fbar,eps)\n% calclates the maximum time for the sabr approximation formula\n% to be valid (see Risk paper by Doust)\n\n a = asabr / eps;\n n = nsabr / eps;\n \n zF = f^(1-b)/asabr/(1-b);\n zFbar = fbar.^(1-b)/asabr/(1-b);\n \n fav = sqrt(f*fbar);\n gamma1 = b./fav;\n gamma2 = b*(b-1)./fav.^2;\n \n kH = 0.125 * (2*gamma2-gamma1.^2)*a^2.*fav.^(2*b) ...\n + 0.75 * r*n*a*gamma1.*fav.^b ...\n + 0.125*(2-3*r^2)*n^2;\n \n z = zF - zFbar;\n integral = (f^(1-b)-fbar.^(1-b)) / (1-b);\n \n xz = 1/nsabr *log((sqrt(1-2*nsabr*r*z+nsabr^2*z.^2)-r+nsabr*z)/(1-r));\n if f==fbar\n y = 12 ./(eps^2*8 * kH); \n else\n y = 12 ./(eps^2*(8 * kH + a^2*(log(f./fbar)./integral .* (z./xz)).^2)); \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/38322-the-sabr-model-densities-and-mc/Densities_Prices_MC/sabrtmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6215795214700753}} {"text": "function se3mat = VecTose3(V)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes a 6-vector (representing a spatial velocity).\n% Returns the corresponding 4x4 se(3) matrix.\n% Example Input:\n% \n% clear; clc;\n% V = [1; 2; 3; 4; 5; 6];\n% se3mat = VecTose3(V)\n% \n% Output:\n% se3mat =\n% 0 -3 2 4\n% 3 0 -1 5\n% -2 1 0 6\n% 0 0 0 0 \n\nse3mat = [VecToso3(V(1: 3)), V(4: 6); 0, 0, 0, 0];\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/VecTose3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6215795141803145}} {"text": "function [gnodes, gedges] = relativeNeighborhoodGraph(points)\n%RELATIVENEIGHBORHOODGRAPH Relative Neighborhood Graph of a set of points\n%\n% [NODES, EDGES] = relativeNeighborhoodGraph(POINTS)\n% EDGES = relativeNeighborhoodGraph(POINTS)\n%\n% The Relative Neighborhood Graph (RNG) is a subgraph of the Delaunay\n% Triangulation computed from the same set of points. The Gabriel graph\n% and the euclidean minimal spanning tree (EMST) are subgraphs of the\n% RNG.\n%\n% Example\n% nodes = rand(100, 2) * 100;\n% edges = relativeNeighborhoodGraph(nodes);\n% figure; drawGraph(nodes, edges);\n%\n% See also\n% gabrielGraph, euclideanMST\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2016-03-02, using Matlab 8.6.0.267246 (R2015b)\n% Copyright 2016 INRA - Cepia Software Platform.\n\n% first compute Delaunay triangulation to reduce further computations\nDT = delaunayTriangulation(points);\nE = edges(DT);\n\n% compute edge lengths\nnEdges = size(E, 1);\nedgeLengths = zeros(nEdges, 1);\nfor i = 1:nEdges\n edgeLengths(i) = distancePoints(points(E(i,1),:), points(E(i,2),:));\nend\n\n% identify indices of faces attached to each vertex\nvertexFaces = vertexAttachments(DT);\n\n% iterate over edges to check if the should be kept\nkeepEdge = true(nEdges, 1);\nfor iEdge = 1:nEdges\n iVertex1 = E(iEdge, 1);\n iVertex2 = E(iEdge, 2);\n vertex1 = points(iVertex1, :);\n vertex2 = points(iVertex2, :);\n \n % compute indices of faces containing one of the two vertices\n inds = [vertexFaces{iVertex1} vertexFaces{iVertex2}];\n localFaces = DT.ConnectivityList(inds, :);\n \n % compute indices of vertices is the first neighborhood of the edge\n inds = unique(localFaces);\n inds(ismember(inds, [iVertex1 iVertex2])) = [];\n \n % compute max of distances to both original vertices\n dists1 = distancePoints(vertex1, points(inds, :));\n dists2 = distancePoints(vertex2, points(inds, :));\n distsMax = max(dists1, dists2);\n \n % keep edge if all points are outside the \"lunule\" defined by the edge\n if edgeLengths(iEdge) > min(distsMax)\n keepEdge(iEdge) = false;\n end\nend\n\n% filter edges\ngedges = E(keepEdge, :);\n\n% format output\ngnodes = points;\nif nargin == 1\n gnodes = gedges;\nend\n\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/graphs/relativeNeighborhoodGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6214685291672398}} {"text": "% Calculate arena coverage (the amount of space an animal has covered during experiment)\n%\n% Calculates arena coverage.\n%\n% USAGE\n% coverage = analyses.arenaCoverage(pos, binWidth, shape, dimensions)\n% pos Position samples, matrix of size at least Nx2. Format is either [t x] or [t x y].\n% binWidth Width of horizontal and vertical bins in cm. If only one value is provided, then\n% the same bin width is used in both directions.\n% shape Arena shape, integer. One of the values of bntConstants.ArenaShape.\n% dimensions Vector of arena dimensions, the actual number of elements depends on arena shape.\n%\n% coverage Arena coverage, float in range [0..100].\n%\nfunction coverage = arenaCoverage(pos, binWidth, shape, dimensions)\n inp = inputParser;\n\n checkPosDimensions = @(x) size(x, 2) >= 2;\n checkBinWidth = @(x) helpers.isdvector(x, '>=0') && length(x) <= 2;\n checkShape = @(x) ismember(x, helpers.ArenaShape.allShapes());\n checkDims = @(x) helpers.isdvector(x, '>=0') && (x(1) > 0);\n\n addRequired(inp, 'pos', checkPosDimensions);\n addRequired(inp, 'binWidth', checkBinWidth);\n addRequired(inp, 'shape', checkShape);\n addRequired(inp, 'dimensions', checkDims);\n\n parse(inp, pos, binWidth, shape, dimensions);\n\n t = pos(:, 1);\n x = pos(:, 2);\n if size(pos, 2) > 2\n y = pos(:, 3);\n else\n y = [];\n end\n\n binWidthX = binWidth(1);\n if length(binWidth) == 1\n binWidthY = binWidthX;\n else\n binWidthY = binWidth(2);\n end\n\n % filter out points that lie outside arena. This is important for circles\n % because they do not fully cover all the bins.\n if shape == bntConstants.ArenaShape.Circle\n radius = dimensions(1)/2;\n ind = sqrt(x.^2 + y.^2) > radius;\n x(ind) = nan;\n y(ind) = nan;\n end\n\n limitsX = [-dimensions(1)/2 dimensions(1)/2];\n [xBinned, nBinsX, edgesX] = helpers.bin(x, limitsX, binWidthX);\n nBins = nBinsX;\n\n if ~isempty(y)\n if length(dimensions) == 1\n if shape == bntConstants.ArenaShape.Track\n yLength = 1;\n else\n yLength = dimensions(1);\n end\n else\n if shape == bntConstants.ArenaShape.Track && dimensions(2) == 0\n yLength = 1;\n else\n yLength = dimensions(2);\n end\n end\n\n limitsY = [-yLength/2 yLength/2];\n [yBinned, nBinsY, edgesY] = helpers.bin(y, limitsY, binWidthY);\n nBins = [nBinsX nBinsY];\n end\n\n dt = diff(t);\n dt(end+1) = dt(end);\n\n if isempty(y)\n occupancy = general.accumulate(xBinned, dt, nBinsX)';\n else\n occupancy = general.accumulate([xBinned yBinned], dt, nBins)';\n end\n\n switch shape\n case bntConstants.ArenaShape.Circle\n radius = dimensions(1)/2;\n radiusBin = ceil(radius / binWidthX) + 1;\n\n halfSize = ceil(size(occupancy)/2);\n [rr, cc] = meshgrid(1:nBinsX, 1:nBinsY);\n\n distMap = sqrt((cc - halfSize(2)).^2 + (rr - halfSize(1)).^2); % each element is the distance\n % from the middle of the map to current point\n outerCircle = distMap >= radiusBin;\n distMap(outerCircle) = nan;\n\n numBins = sum(sum(isfinite(distMap)));\n coverage = (length(find(occupancy > 0)) / numBins) * 100;\n otherwise\n coverage = length(find(occupancy > 0)) / prod(nBins) * 100;\n end\nend\n", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+analyses/arenaCoverage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6214685211746193}} {"text": "classdef matRad_EUD < DoseObjectives.matRad_DoseObjective\n% matRad_EUD Implements a penalized equivalent uniform dose objective\n% See matRad_DoseObjective for interface description\n%\n% References\n% -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2020 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n properties (Constant)\n name = 'EUD';\n parameterNames = {'EUD^{ref}', 'k'};\n parameterTypes = {'dose','numeric'};\n end\n \n properties\n parameters = {0, 3.5};\n penalty = 1;\n end\n \n methods\n function obj = matRad_EUD(penalty,eudRef, eudExponent)\n %If we have a struct in first argument\n if nargin == 1 && isstruct(penalty)\n inputStruct = penalty;\n initFromStruct = true;\n else\n initFromStruct = false;\n inputStruct = [];\n end\n \n %Call Superclass Constructor (for struct initialization)\n obj@DoseObjectives.matRad_DoseObjective(inputStruct);\n \n %now handle initialization from other parameters\n if ~initFromStruct\n if nargin >= 3 && isscalar(eudExponent)\n obj.parameters{2} = eudExponent;\n end\n \n if nargin >= 2 && isscalar(eudRef)\n obj.parameters{1} = eudRef;\n end\n \n if nargin >= 1 && isscalar(penalty)\n obj.penalty = penalty;\n end\n end\n end\n \n %% Calculates the Objective Function value\n function fDose = computeDoseObjectiveFunction(obj,dose)\n % get exponent for EUD\n k = obj.parameters{2};\n \n % calculate power sum\n powersum = sum(dose.^k);\n \n \n \n %Calculate objective\n \n %This check is not needed since dose is always positive\n %if powersum > 0\n fDose = obj.penalty * (nthroot(powersum/numel(dose),k) - obj.parameters{1})^2;\n %end\n end\n \n %% Calculates the Objective Function gradient\n function fDoseGrad = computeDoseObjectiveGradient(obj,dose)\n % get exponent for EUD\n k = obj.parameters{2};\n \n %numerical stability\n dose(dose == 0) = 0.001;\n \n % calculate power sum\n powersum = sum(dose.^k);\n \n \n %This check is not needed since dose is always positive\n %if powersum > 0\n \n %derivatives = nthroot(1/numel(dose),k) * powersum^((1-k)/k) * (dose.^(k-1));\n fDoseGrad = 2 * obj.penalty * nthroot(1/numel(dose),k) * powersum^((1-k)/k) * (dose.^(k-1)) .* (nthroot(powersum/numel(dose),k) - obj.parameters{1});\n %end\n if any(~isfinite(fDoseGrad)) % check for inf and nan for numerical stability\n error(['EUD computation failed. Reduce exponent to resolve numerical problems.']);\n end\n end\n end\n \nend\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/optimization/+DoseObjectives/matRad_EUD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6214685156044486}} {"text": "function x = vecpostproc(x, a)\n% VECPOSTPROC is post-processing of a D-dimensional vector.\n% \n% V = vecpostproc(V) outputs L2 normalized vector:\n% V = V ./ L2NORM(V);\n%\n% V = vecpostproc(V, A) outputs L2 and power-law normalized vector:\n% V = SIGN(X) .* ABS(X) .^ A;\n% V = V ./ L2NORM(V);\n%\n% Authors: F. Radenovic, G. Tolias, O. Chum. 2017. \n\n if ~exist('a'), a = 1; end\n x = replacenan (l2_normalize (powerlaw (x, a)));\n\nfunction x = l2_normalize(x)\n l = sqrt(sum(x.^2));\n x = bsxfun(@rdivide,x,l);\n x = replacenan(x);\n\nfunction x = powerlaw (x, a)\n\tif a == 1, return; end\n\tx = sign (x) .* abs(x) .^ a;\n\nfunction y = replacenan (x, v)\n\tif ~exist ('v')\n\t v = 0;\n\tend\n\ty = x;\n\ty(isnan(x)) = v;", "meta": {"author": "filipradenovic", "repo": "cnnimageretrieval", "sha": "93a7391a2f8b13ff189d0c6131b95e0363542659", "save_path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval", "path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval/cnnimageretrieval-93a7391a2f8b13ff189d0c6131b95e0363542659/cnnvecs/vecpostproc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6214685065244286}} {"text": "%{\nThis file shows an example of using the full power of TFOCS. If you\nare not familiar with basic usage of TFOCS, please see other demos\nfirst.\n\nWe make an example that uses:\n -several variables (2), and the variables are matrices, not just vectors\n -several constraints (4)\n -affine operators (linear plus offset), and two of the operators\n are matrix --> matrix operators\n -debug mode\n\n\nFor small complicated examples like this, TFOCS is not necessarily\nfaster than software like CVX, since it takes more iterations than an\ninterior point method and there is some overhead in the TFOCS software\nsince the software is meant for flexibility rather than absolute speed.\n\nHowever, if you take any complicated problem and scale the size by a factor\nof 100, then CVX won't be able to handle it at all. TFOCS will do\njust fine (and it might even be less than 100x as slow, since now the overhead\nis not significant).\n\n\nThe problem we will solve:\n\nmin_{X1, X2} smooth1(X1)+smooth2(X2) + sum_{i=1}^4 g_i( A1_i*X1 + A2_i*X2 + B_i )\n\nmeaning that we have 2 variables (X1 and X2), both of which are matrices,\nand each variable has its own smooth function.\nFor non-smooth and/or constraint terms (indexed by \"i\"), we have 4 functions\n( i = 1,2,3,4) g_i, and each has it's own affine operator in X1 and X2.\nSo each of the 4 affine operators has three parts: the portion linear in X1,\nthe portion linear in X2, and the constant offset \"B_i\".\n\nTo be explicit, the smooth functions are linear and quadratic, resp.:\n\nsmooth1(X1) = dot( s1, X1 ) + 3.4 (\"s1\" is a matrix the same size as X1)\nsmooth2(X2) = dot( X2, X2 ) + dot( s2, X2 ) + 4.5 (\"s2\" is a matrix the same size as X2)\n\nand the non-smooth/constraint terms are:\n\ng_1(z) = indicator set of the positive orthant of R^10\ng_2(z) = ||z||_2 (usual Euclidean norm) in R^15\ng_3(z) = ||z||_1 (l1 norm) in R^{10 x 20 }. This views a 10 x 20 matrix as a 200 x 1 vector.\ng_4(z) = indicator set of positive orthant of R^{20 x 22 }, i.e. each element must be >= 0 coordinate-wise\n\nThe affine operators are picked arbitrary, but some of them (#3 and #4) have a range that\nis a set of matrices, rather than a set of vectors, in order to make \nthis more interesting.\n\n%}\n\nfileName = fullfile('reference_solutions','complicatedProblem1');\nrandn('state',29324);\nrand('state',9332);\n% rng(3481); % this only works on new versions of Matlab\n\n% -- Variables --\n% Two sets of variables, X1 (a matrix of size n1 x n2 ) and X2 (matrix of N1 x N2 )\nn1 = 10; n2 = 20;\nN1 = 12; N2 = 18;\nX1 = zeros( n1, n2 );\nX2 = zeros( N1, N2 );\n\n% -- the smooth terms -- \n% Note: the inner product used is the matrix inner product\n% that induces the Frobenius norm.\ns1 = randn(n1,n2);\nsmooth1 = smooth_linear( s1, 3.4 );\ns2 = randn(N1,N2);\nsmooth2 = smooth_quad( 1, s2, 4.5 );\n% and the same thing, but in a format that CVX likes:\nsmoothF = @(X1,X2) vec(X1)'*vec(s1) + 3.4 + vec(X2)'*vec(s2) + 4.5 + ...\n sum_square(vec(X2))/2;\n\n% -- some proximal terms --\n\nnProx = 4;\nprox1 = proj_Rplus;\nprox2 = proj_l2; % primal is norm( , 2)\nprox3 = proj_linf(1); % this can take matrix varaibles...\nprox4 = proj_Rplus; % this can take matrix variables...\n% Sizes of proxes (i.e. sizes of dual variables, i.e. size of range of linear terms)\nd1 = [ 10, 1 ];\nd2 = [ 15, 1 ];\nd3 = [ n1, n2 ];\nd4 = [ 20, 22 ];\n\n\n% -- and linear terms --\n\n% for prox1:\nconst1 = randn(d1);\ntemp1 = randn( prod(d1), n1*n2);\nA1_X1 = linop_compose( linop_matrix(temp1), linop_vec([n1,n2]) );\ntemp2 = randn( prod(d1), N1*N2);\nA1_X2 = linop_compose( linop_matrix(temp2), linop_vec([N1,N2]) );\n\nA1 = @(X1,X2) temp1*vec(X1) + temp2*vec(X2) + const1;\n\n% for prox2: (matrix variable)\nconst2 = randn(d2);\ntemp1 = randn( prod(d2), n1*n2);\nA2_X1 = linop_compose( linop_matrix(temp1), linop_vec([n1,n2]) );\ntemp2 = randn( prod(d2), N1*N2);\nA2_X2 = linop_compose( linop_matrix(temp2), linop_vec([N1,N2]) );\n\nA2 = @(X1,X2) temp1*vec(X1) + temp2*vec(X2) + const2;\n\n% for prox3:\nconst3 = 0;\nA3_X1 = 63.4; % this represents abstract scaling, i.e. any size input\nA3_X2 = 0; % this reprsents the zero linear operator\n\nA3 = @(X1,X2) A3_X1*X1;\n\n% for prox4: (matrix variable)\nconst4 = randn(d4);\ntemp1 = randn( prod(d4), n1*n2);\nA4_X1 = linop_compose( linop_matrix(temp1), linop_vec([n1,n2]) );\nrs = linop_adjoint( linop_vec(d4) );\nA4_X1 = linop_compose( rs, A4_X1 );\nmat1 = @(x) reshape( x, d4(1), d4(2) );\n\ntemp2 = randn( prod(d4), N1*N2);\nA4_X2 = linop_compose( linop_matrix(temp2), linop_vec([N1,N2]) );\nrs = linop_adjoint( linop_vec(d4) );\nA4_X2 = linop_compose( rs, A4_X2 );\n\nA4 = @(X1,X2) mat1( temp1*vec(X1) + temp2*vec(X2) ) + const4;\n\n% -- set the smoothing parameter --\nmu = 1;\n\nif exist([fileName,'.mat'],'file')\n load(fileName); % contains X_CVX\n fprintf('Loaded problem from %s\\n', fileName );\nelse\n % Get reference solution in CVX\n % First, get a solution to the smoothed version:\n cvx_begin\n variables X1(n1,n2) X2(N1,N2)\n % it's important that we use norm(vec(...),1) and not just norm(...,1),\n % otherwise CVX interprets this with the wrong implicit inner product\n minimize( smoothF( X1, X2 ) + ...\n norm( A2(X1,X2), 2 ) + norm( vec(A3(X1,X2)) , 1 ) + ...\n mu*( sum_square(vec(X1)) + sum_square(vec(X2)) )/2 )\n subject to\n A1(X1,X2) >= 0 % constraint is dual of prox1\n A4(X1,X2) >= 0 % constraint is dual of prox2\n cvx_end\n X_CVX_smoothed{1} = X1;\n X_CVX_smoothed{2} = X2;\n \n % Second, get a solution to the unsmoothed version\n cvx_begin\n variables X1(n1,n2) X2(N1,N2)\n minimize( smoothF( X1, X2 ) + ...\n norm( A2(X1,X2), 2 ) + norm( vec(A3(X1,X2)) , 1 ) )\n subject to\n A1(X1,X2) >= 0\n A4(X1,X2) >= 0\n cvx_end\n X_CVX{1} = X1;\n X_CVX{2} = X2;\n \n save(fileName,'X_CVX', 'X_CVX_smoothed');\n fprintf('Saved data to file %s\\n', fileName);\nend\n\n% Verify constraint are satisfied\nfprintf('Is A1(x1,x2) >= 0? The min element is %g\\n', min( A1(X_CVX{1},X_CVX{2} )) )\nfprintf('Is A2(x1,x2) >= 0? The min element is %g\\n', min(min(A4(X_CVX{1},X_CVX{2}))) )\n%% before running TFOCS, scale the problem perhaps?\n% This is one way to see how big the norms are:\n% nrm11 = linop_test( A1_X1 ); % 15.7\n% nrm12 = linop_test( A1_X2 ); % 16.6\n% \n% nrm21 = linop_test( A2_X1 ); % 17.8\n% nrm22 = linop_test( A2_X2 ); % 18.6\n% \n% nrm31 = linop_test( A3_X1 ); % 63.4\n% nrm32 = linop_test( A3_X2 ); % 0\n% \n% nrm41 = linop_test( A4_X1 ); % 35.6\n% nrm42 = linop_test( A4_X2 ); % 34.6\n\n%% now, run TFOCS. First, try it without continuation\n\nx0 = [];\nz0 = [];\nopts = struct('continuation',false,'maxits',1500,'debug',true); % using 'debug' mode to print out useful information\nopts.printEvery = 50;\n\n% Pick a scaling factor \"s\" (optional: set to \"1\" to have no effect)\ns = .5; % helps a little bit\n% (note that if we scale prox3 by \"s\", then we multiply the corresponding\n% affine part by \"s\", rather than divide them by \"s\", since prox3\n% is really for the dual and not the primal).\n\nmu = 1;\nopts.errFcn{1} = @(f,d,p) norm( p{1}-X_CVX_smoothed{1}); % compare to smoothed reference solution\nopts.errFcn{2} = @(f,d,p) norm( p{2}-X_CVX_smoothed{2});\n\n[xAll,outParam,optsOut] = tfocs_SCD( {smooth1,smooth2}, ...\n { A1_X1, A1_X2, const1; A2_X1, A2_X2, const2; ...\n A3_X1*s, A3_X2*s, const3*s; A4_X1, A4_X2, const4 }, ...\n {prox1,prox2,prox_scale(prox3,s),prox4},...\n mu, x0, z0, opts );\n\nmnConstraint1 = min(min( A1(xAll{1},xAll{2} ) ) );\nmnConstraint2 = min(min( A4(xAll{1},xAll{2} ) ) );\nfprintf('First constraint violated by: %g\\n', mnConstraint1);\nfprintf('Second constraint violated by: %g\\n', mnConstraint2 );\n\n% Check that we are within acceptable limits\ner = sqrt(norm( xAll{1} - X_CVX_smoothed{1} )^2 + norm( xAll{2} - X_CVX_smoothed{2} )^2 )/...\n sqrt( norm(X_CVX_smoothed{1})^2 + norm(X_CVX_smoothed{2})^2 ); % should be about .006\n\nif er > 0.04 || mnConstraint1 < -.01 || mnConstraint2 < -.01\n error('Failed the test');\nelse\n disp('This test successfully passed');\nend\n\n%% run TFOCS with continuation\nx0 = [];\nz0 = [];\n% type \"tfocs\" at the command to see possible options\nopts = struct('continuation',true,'maxits',1500);\nopts.printEvery = 50;\nopts.tol = 1e-4;\nopts.stopCrit = 4;\nopts.printStopCrit = true;\n\n% type \"continuation\" at the command to see possible options\ncontOpts = struct( 'maxIts', 8 , 'muDecrement', 0.8 );\n% ask for increased accuracy on the final solve\ncontOpts.finalTol = 1e-5;\n\ns = .5; % helps a little bit\n% (note that if we scale prox3 by \"s\", then we multiply the corresponding\n% affine part by \"s\", rather than divide them by \"s\", since prox3\n% is really for the dual and not the primal).\n\nmu = 10;\nopts.errFcn{1} = @(f,d,p) norm( p{1}-X_CVX{1}); % compare to unsmoothed reference solution\nopts.errFcn{2} = @(f,d,p) norm( p{2}-X_CVX{2});\n\n[xAll,outParam,optsOut] = tfocs_SCD( {smooth1,smooth2}, ...\n { A1_X1, A1_X2, const1; A2_X1, A2_X2, const2; ...\n A3_X1*s, A3_X2*s, const3*s; A4_X1, A4_X2, const4 }, ...\n {prox1,prox2,prox_scale(prox3,s),prox4},...\n mu, x0, z0, opts, contOpts );\n\nmnConstraint1 = min(min( A1(xAll{1},xAll{2} ) ) );\nmnConstraint2 = min(min( A4(xAll{1},xAll{2} ) ) );\nfprintf('First constraint violated by: %g\\n', mnConstraint1);\nfprintf('Second constraint violated by: %g\\n', mnConstraint2 );\n\n% Check that we are within acceptable limits\ner = sqrt(norm( xAll{1} - X_CVX{1} )^2 + norm( xAll{2} - X_CVX{2} )^2 )/...\n sqrt( norm(X_CVX{1})^2 + norm(X_CVX{2})^2 ); % should be about .006\n\nif er > 0.4 || mnConstraint1 < -.01 || mnConstraint2 < -.01\n error('Failed the test');\nelse\n disp('This test successfully passed');\nend\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.", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/examples/smallscale/test_complicatedUsage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6214632258691933}} {"text": "% demo_geodet December 16, 2012\n\n% demonstrates the geocentric-to-geodetic functions\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear all;\n\nglobal req flat\n\n% conversion factor - degrees-to-radians\n\nrtd = 180.0d0 / pi;\n\n% Earth equatorial radius (kilometers)\n\nreq = 6378.1363;\n\n% Earth flattening factor (non-dimensional)\n\nflat = 1.0 / 298.257;\n\n% Earth polar axis (kilometers)\n\nrpolar = req * (1.0d0 - flat);\n\n% eci position vector (kilometers)\n\nreci(1) = -.586479273288D+04;\nreci(2) = -.178173078828D+04;\nreci(3) = -.215629990858D+04;\n\nrmag = norm(reci);\n\ndec = asin(reci(3) / rmag);\n\n[alt1, lat1] = geodet1 (rmag, dec);\n\nclc; home;\n\nfprintf('geocentric declination %14.8f degrees \\n\\n', rtd * dec);\n\nfprintf('geocentric radius %14.8f kilometers \\n\\n', rmag);\n\nfprintf('\\ngeodet1 function\\n');\nfprintf('================\\n\\n');\n\nfprintf('geodetic latitude %14.8f degrees \\n\\n', rtd * lat1);\n\nfprintf('geodetic altitude %14.8f kilometers \\n\\n', alt1);\n\n[lat2, alt2] = geodet2(dec, rmag);\n\nfprintf('\\ngeodet2 function\\n');\nfprintf('================\\n\\n');\n\nfprintf('geodetic latitude %14.8f degrees \\n\\n', rtd * lat2);\n\nfprintf('geodetic altitude %14.8f kilometers \\n\\n', alt2);\n\n[alt5, lat5] = geodet5 (req, rpolar, reci);\n\nfprintf('\\ngeodet5 function\\n');\nfprintf('================\\n\\n');\n\nfprintf('geodetic latitude %14.8f degrees \\n\\n', rtd * lat5);\n\nfprintf('geodetic altitude %14.8f kilometers \\n\\n', alt5);\n\n[alt6, lat6] = geodet6 (req, rpolar, reci);\n\nfprintf('\\ngeodet6 function\\n');\nfprintf('================\\n\\n');\n\nfprintf('geodetic latitude %14.8f degrees \\n\\n', rtd * lat6);\n\nfprintf('geodetic altitude %14.8f kilometers \\n\\n', alt6);", "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/39494-geodetic-and-geocentric-coordinates/demo_geodet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6214632235349825}} {"text": "function y = softmax(x)\n M = bsxfun(@minus, x, max(x, [], 1));\n numerator = exp(M);\n denominator = sum(numerator) + 0.00001; \n y = bsxfun(@rdivide, numerator, denominator) + 0.00001; \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/utils/softmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6214632194596045}} {"text": "function x=v_pcma2lin(p,m,s)\n%V_PCMU2LIN Convert A-law PCM to linear X=(P,M,S)\n%\tlin = v_pcma2lin(pcma,m,s) where pcma contains a vector or matrix\n%\tof A-law values in the range 0 to 255.\n%\tNo checking is performed to see that numbers are in this range.\n%\n%\tInput values are exclusive ored with m (default=85)\n%\n%\tOutput values are divided by the scale factor s:\n%\n%\t\t s\t\tOutput Range\n%\n%\t\t 1\t\t+-4032\t(integer values)\n%\t\t2017.396342\t+-1.998616 (default)\n%\t\t4032\t\t+-1\n%\t\t4096\t\t+-0.984375 (+-1 nominal full scale)\n%\n%\tThe default value of s is 2017.396342 which equals\n%\tsqrt((1120^2 + 2624^2)/2). This factor follows ITU standard G.711 and\n%\tthe sine wave with PCM-A values [225 244 244 225 97 116 116 97]\n%\thas a mean square value of unity corresponding to 0 dBm0.\n\n\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_pcma2lin.m 10865 2018-09-21 17:22:45Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<3\n t=4.95688418E-4;\n if nargin<2 m=85; end\nelse\n t=1/s;\nend\n\nif m q=bitxor(p,m); else q=p; end;\nk=rem(q,16);\ng=floor(q/128);\ne=(q-k-128*g)/16;\nf=(abs(e-1)-e+1)/2;\nx=(2*g-1).*(pow2(k+16.5,e)+f.*(k-15.5))*t;\n", "meta": {"author": "ImperialCollegeLondon", "repo": "sap-voicebox", "sha": "28f2654b7584f724277ec81de533debe28ff51ac", "save_path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox", "path": "github-repos/MATLAB/ImperialCollegeLondon-sap-voicebox/sap-voicebox-28f2654b7584f724277ec81de533debe28ff51ac/voicebox/v_pcma2lin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6213787245331004}} {"text": "function D = DLSI_updateD(D, E, F, A, lambda, opts)\n% function D = DLSI_updateD(D, E, F, A, lambda, opts)\n% problem: `D = argmin_D -2trace(ED') + trace(FD'*D) + lambda *||A*D||F^2,` \n% subject to: `||d_i||_2^2 <= 1`\n% where F is a positive semidefinite matrix\n% ========= aproach: ADMM ============================== \n% rewrite: `[D, Z] = argmin -2trace(ED') + trace(FD'*D) + lambda ||A*Z||_F^2,` \n% subject to `D = Z; ||d_i||_2^2 <= 1`\n% aproach 1: ADMM.\n% 1. D = -2trace(ED') + trace(FD'*D) + rho/2 ||D - Z + U||_F^2, \n% s.t. ||d_i||_2^2 <= 1\n% 2. Z = argmin lambda*||A*Z|| + rho/2||D - Z + U||_F^2\n% 3. U = U + D - Z\n% solve 1: D = argmin -2trace(ED') + trace(FD'*D) + rho/2 ||D - W||_F^2 \n% with W = Z - U;\n% = argmin -2trace((E - rho/2*W)*D') + \n% trace((F + rho/2 * eye())*D'D)\n% solve 2: derivetaive: 0 = 2A'AZ + rho (Z - V) with V = D + U \n% `Z = B*rhoV` with `B = (2*lambda*A'*A + rho I)^{-1}`\n% `U = U + D - Z` \n% -----------------------------------------------\n% Author: Tiep Vu, thv102@psu.edu, 5/11/2016\n% (http://www.personal.psu.edu/thv102/)\n% -----------------------------------------------\n\n if nargin == 0\n clc;\n d = 300; \n N = 10;\n k = 5;\n k2 = 495;\n load('tmp.mat');\n lambda = 0.01; \n \n opts.show = 0;\n opts.max_iter = 300; \n opts.verbose = 1;\n \n end \n if nargin == 6\n opts.lambda = lambda;\n elseif nargin == 5\n opts = lambda;\n end \n %%\n function cost = calcost(D) \n cost = -2*trace(E*D') + trace(F*D'*D) + lambda*normF2(A*D); \n end \n %%\n iter = 0;\n rho = 1.0;\n Z_old = D;\n U = zeros(size(D));\n I_k = eye(size(D,2));\n % B = inv(2*lambda*A'*A + rho*I_k2); However, this might be very expensive if size(A, 2) is big, which is common \n % Instead, we can use the Sherman–Morrison formula at\n % https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula#Generalization_(Woodbury_Matrix_Identity)\n X = 2*lambda/rho*A';\n Y = A;\n B1 = X*inv(eye(size(Y, 1)) + Y*X);\n tol = 1e-5;\n optsD.max_iter = 100;\n optsD.tol = 1e-8;\n while iter < opts.max_iter \n iter = iter + 1;\n %% ========= update D ============================== \n W = Z_old - U;\n E2 = E + rho/2 * W;\n F2 = F + rho/2*I_k; \n D = ODL_updateD(D, E2, F2, optsD);\n %% ========= update Z ==============================\n V = D + U;\n % Z_new = rho*B*V; slow \n Z_new = rho*(V - B1*(Y*V)); % fast \n e1 = normF2(D - Z_new);\n e2 = rho*normF2(Z_new - Z_old);\n if (e1 < optsD.tol && e2 < optsD.tol)\n break;\n end\n if opts.verbose\n cost = calcost(D);\n fprintf('iter = %3d | costD = %5.4f | normF2(D - Z) = %5.4f | rho(Z_new - Z_old) = %5.4f\\n', iter, cost, e1, e2);\n end \n %% ========= update U ==============================\n U = U + D - Z_new;\n Z_old = Z_new;\n end \n% disp(t1)\n% disp(t2)\n if nargin == 0\n D = [];\n end \nend \n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/DLSI/DLSI_updateD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6213787245331003}} {"text": "function [err,time,solver,eqn] = femPoisson3(mesh,pde,option,varargin)\n%% FEMPOISSON3 solve Poisson equation by various finite element methods\n%\n% FEMPOISSON3 computes approximations to the Poisson equation on a\n% sequence of meshes obtained by uniform refinement of a input mesh.\n% \n% See also Poisson, crack, Lshape\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%% Check input arguments\nif isfield(mesh,'node') && isfield(mesh,'elem')\n node = mesh.node;\n elem = double(mesh.elem);\nelse\n [node,elem] = cubemesh([0,1,0,1,0,1],0.25); % default mesh is a cube\nend\nif isfield(mesh,'bdFlag')\n bdFlag = mesh.bdFlag;\nelse\n bdFlag = setboundary3(node,elem,'Dirichlet'); \nend\nif ~exist('option','var'), option = []; end\nif ~exist('pde','var')\n pde = sincosdata3; % default data\nend\n\n%% Parameters\noption = femoption(option);\nmaxIt = option.maxIt; \nmaxN = option.maxN; \nL0 = option.L0;\nelemType = option.elemType; \nrefType = option.refType;\n\n%% Generate an initial mesh \nfor k = 1:L0\n if strcmp(refType,'red')\n [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n elseif strcmp(refType,'bisect')\n [node,elem,bdFlag] = uniformbisect3(node,elem,bdFlag);\n end\nend\n\n%% Initialize err\nerrL2 = zeros(maxIt,1); errH1 = zeros(maxIt,1); \nerruIuh = zeros(maxIt,1); errMax = zeros(maxIt,1);\nerrTime = zeros(maxIt,1); solverTime = zeros(maxIt,1); \nassembleTime = zeros(maxIt,1); meshTime = zeros(maxIt,1); \nitStep = zeros(maxIt,1); stopErr = zeros(maxIt,1); flag = zeros(maxIt,1);\nN = zeros(maxIt,1); h = zeros(maxIt,1);\n\n%% Finite Element Method \nfor k = 1:maxIt\n% bdFlag = sparse(double(bdFlag));\n % solve the equation\n switch elemType\n case 'P1' % piecewise linear function P1 element\n [soln,eqn,info] = Poisson3(node,elem,bdFlag,pde,option);\n case 'CR' % piecewise linear function CR element\n [soln,eqn,info] = Poisson3CR(node,elem,bdFlag,pde,option);\n case 'P2' % piecewise quadratic function\n [soln,eqn,info] = Poisson3P2(node,elem,bdFlag,pde,option);\n case 'WG' % weak Galerkin element\n [soln,eqn,info] = Poisson3WG(node,elem,bdFlag,pde,option); \n end\n uh = soln.u;\n % compute error\n t = cputime;\n if isfield(pde,'Du')\n if isfield(soln,'Du') && ~isempty(soln.Du) % Du is in the output\n errH1(k) = getH1error3(node,elem,pde.Du,soln.Du);\n else\n errH1(k) = getH1error3(node,elem,pde.Du,uh); \n end\n end\n if isfield(pde,'exactu')\n errL2(k) = getL2error3(node,elem,pde.exactu,uh); \n % interpolation\n switch elemType\n case 'P1'\n uI = Lagrangeinterpolate(pde.exactu,node,elem);\n case 'CR'\n uI = Lagrangeinterpolate(pde.exactu,node,elem,'CR',eqn.face);\n case 'P2'\n uI = Lagrangeinterpolate(pde.exactu,node,elem,'P2',eqn.edge);\n case 'WG'\n uI = Lagrangeinterpolate(pde.exactu,node,elem,'WG',eqn.face);\n end\n erruIuh(k) = sqrt((uh-uI)'*eqn.A*(uh-uI));\n errMax(k) = max(abs(uh-uI));\n end\n errTime(k) = cputime - t;\n % record time\n solverTime(k) = info.solverTime;\n assembleTime(k) = info.assembleTime;\n if option.printlevel>1\n fprintf('Time to compute the error %4.2g s \\n H1 err %4.2g L2err %4.2g \\n',...\n errTime(k), errH1(k), errL2(k)); \n end\n % record solver information\n itStep(k) = info.itStep;\n stopErr(k) = info.stopErr;\n flag(k) = info.flag;\n % plot \n N(k) = length(soln.u);\n h(k) = 1./(size(node,1)^(1/3)-1); \n if strcmp(elemType,'WG') % modify size for WG\n if ~isfield(option,'reducesystem') || (option.reducesystem == 1)\n N(k) = N(k) - size(elem,1); % reduced system\n end \n end \n if option.plotflag && N(k) < 2e4 % show mesh and solution for small size\n switch elemType\n case 'P1' % piecewise linear function P1 element\n figure(1); showresult3(node,elem,uh); \n case 'CR' % piecewise linear function CR element\n continue;\n case 'P2' % piecewise quadratic function\n figure(1); showresult3(node,elem,uh(1:size(node,1))); \n case 'WG' % weak Galerkin element\n continue;\n end\n end\n if N(k) > maxN\n break;\n end\n % refine mesh\n t = cputime;\n if strcmp(refType,'red')\n [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag);\n elseif strcmp(refType,'bisect')\n [node,elem,bdFlag] = uniformbisect3(node,elem,bdFlag);\n end\n meshTime(k) = cputime - t;\nend\n\n%% Plot convergence rates\nif option.rateflag\n figure;\n set(gcf,'Units','normal'); \n set(gcf,'Position',[0.25,0.25,0.55,0.4]);\n subplot(1,2,1)\n showrateh2(h(1:k),errH1(1:k),1,'-*','||Du-Du_h||',...\n h(1:k),errL2(1:k),1,'k-+','||u-u_h||');\n title(['Convergence Rate of 3D ', elemType, '-element']);\n subplot(1,2,2)\n showrateh2(h(1:k),erruIuh(1:k),1,'m-+','||Du_I-Du_h||',...\n h(1:k),errMax(1:k),1,'r-*','||u_I-u_h||_{\\infty}');\n title(['Convergence Rate of 3D ', elemType, '-element']);\nend\n\n%% Output\nerr = struct('h',h(1:k),'N',N,'H1',errH1(1:k),'L2',errL2(1:k),...\n 'uIuhH1',erruIuh(1:k),'uIuhMax',errMax(1:k));\ntime = struct('N',N,'err',errTime(1:k),'solver',solverTime(1:k), ...\n 'assemble',assembleTime(1:k),'mesh',meshTime(1:k));\nsolver = struct('N',N(1:k),'itStep',itStep(1:k),'time',solverTime(1:k),...\n 'stopErr',stopErr(1:k),'flag',flag(1:k));\n\n%% Display error and time\nif option.dispflag\n disp('Table: Error')\n colname = {'#Dof','h','||u-u_h||','||Du-Du_h||','||DuI-Du_h||','||uI-u_h||_{max}'};\n disptable(colname,err.N,[],err.h,'%0.3e',err.L2,'%0.5e',err.H1,'%0.5e',...\n err.uIuhH1,'%0.5e',err.uIuhMax,'%0.5e');\n\n disp('Table: CPU time')\n colname = {'#Dof','Assemble','Solve','Error','Mesh'};\n disptable(colname,time.N,[],time.assemble,'%0.2e',time.solver,'%0.2e',...\n time.err,'%0.2e',time.mesh,'%0.2e');\nend\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/femPoisson3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6213787034590486}} {"text": "function visible_probability = hidden_state_to_visible_probabilities(rbm_w, hidden_state)\n% is a matrix of size

1\n [E,V]=subHex(E,V,1); %Refine input mesh\n [F]=element2patch(E); %Patch data for plotting\n [indBoundary]=tesBoundary(F);\n controlParameter.indBoundary=indBoundary; %indices of the boundary faces\n end\n \n [Fs1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n \n % Visualizing input mesh and lattice structures\n \n subplot(2,2,q);\n hold on; title(['Split iteration ',num2str(q)]);\n gpatch(Fs1,Vs1,Cs1);\n colormap(cMap);\n axisGeom(gca,fontSize);\n camlight headlight; lighting flat;\n \nend\ndrawnow;\n\n%% Example: Creating a lattice structure on tetrahedral elements\n\n%%\n% Creating example geometry.\n\n[V,~]=platonic_solid(1,1); %A single tetrahedron\nE=[2 3 4 1]; %The element description\n[E,V]=subTet(E,V,1); %Refine the tetrahedron once\n[F]=element2patch(E); %Patch data for plotting\n[indBoundary]=tesBoundary(F); %Get boundary face indices\n\n%%\n% Create lattice structure\ncontrolParameter.shrinkFactor=0.2; %Strut sides are formed by shrinking the input mesh faces by this factor\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.meshType='quad'; %desired output mesh type\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\n\ncontrolParameter.latticeSide=1; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Fs1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattice structures\n\ncFigure;\ntitle('An edge lattice structure on a hexahedral element','fontSize',fontSize)\nhold on;\nhp1=gpatch(F,V,0.5*ones(1,3),'k',0.25,4);\nhp2=gpatch(Fs1(Cs1==0,:),Vs1,Cs1(Cs1==0));\nhp3=gpatch(Fs1(Cs1==1,:),Vs1,Cs1(Cs1==1));\nlegend([hp1,hp2,hp3],'Input mesh','Inner faces','Boundary faces')\ncolormap(cMap);\ncLim=caxis;\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\n\ndrawnow;\n\n%% Example: Different lattice sides\n\n%%\n% Compute other \"lattice side\"\ncontrolParameter.latticeSide=2; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n[Fs2,Vs2,Cs2]=element2lattice(E,V,controlParameter); %Get lattice structure\n\n%%\n% Visualizing input mesh and lattice structures\n\ncFigure;\nhs=subplot(2,2,1);\ntitle('The input mesh','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\nha=axis; axis off;\n\nsubplot(2,2,2);\ntitle('The two complementary lattice structures','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs1,Vs1,Cs1);\ngpatch(Fs2,Vs2,Cs2);\ncolormap(cMap);\ncLim=caxis;\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\naxis(ha); axis off;\n\nsubplot(2,2,3);\ntitle('Lattice side 1','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs1,Vs1,Cs1);\ncolormap(cMap);\ncaxis(cLim);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\naxis(ha); axis off;\n\nsubplot(2,2,4);\ntitle('Lattice side 2','fontSize',fontSize)\nhold on;\ngpatch(F,V,0.5*ones(1,3),'k',0.25,3);\ngpatch(Fs2,Vs2,Cs2);\ncolormap(cMap);\ncaxis(cLim);\naxisGeom(gca,fontSize);\ncamlight headlight; lighting flat;\naxis(ha); axis off;\n\ndrawnow;\n\n%% Example: Changing lattice strut thickness (and porosity)\n\n%%\n% The strut thickness of the lattice depends on the shrinkfactor.\n\n% Create lattice structure\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.meshType='quad'; %desired output mesh type\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\n\nshrinkFactorSet=linspace(0.1,0.5,4);\n\nfor latticeSide=1:2\n controlParameter.latticeSide=latticeSide;\n cFigure;\n gtitle('Lattice structure porosity control',fontSize);\n \n for q=1:4\n controlParameter.shrinkFactor=shrinkFactorSet(q); %Strut sides are formed by shrinking the input mesh faces by this facto\n \n [Fs1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n \n % Visualizing input mesh and lattice structures\n subplot(2,2,q);\n hold on; title(['Shrink factor ',num2str(pround(shrinkFactorSet(q),3))]);\n gpatch(Fs1,Vs1,Cs1);\n colormap(cMap);\n axisGeom(gca,fontSize);\n camlight headlight; lighting flat;\n end\n drawnow;\nend\n\n%% Example: Changing output surface mesh type\n\n%%\n% Different output mesh types are available i.e. quadrilateral and\n% triangular faces and also hexahedral elements.\n\nmeshTypeSet={'quad','tri'};\n\nboxDim=[1 1 1];\nboxEl=[1 1 1];\n[meshStruct]=hexMeshBox(boxDim,boxEl);\nE=meshStruct.E;\nV=meshStruct.V;\nF=meshStruct.F;\n[indBoundary]=tesBoundary(F);\n\nclear controlParameter\n\n% Create lattice structure\ncontrolParameter.latticeSide=2;\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\ncontrolParameter.shrinkFactor=0.3;\n\ncFigure;\ngtitle('Lattice structure mesh output type control',fontSize);\n\nfor q=1:numel(meshTypeSet)\n controlParameter.meshType=meshTypeSet{q}; %The current mesh type\n \n [Fs1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n \n % Visualizing input mesh and lattice structures\n subplot(1,numel(meshTypeSet),q);\n hold on; title(['Mesh type ',meshTypeSet{q}]);\n gpatch(Fs1,Vs1,Cs1,'k',0.8,2);\n colormap(gjet(250));\n axisGeom(gca,fontSize);\n camlight headlight; lighting flat;\nend\ndrawnow;\n\n%% Example: Exporting hexahedral elements instead of surface elements\n\n%%\n% The |element2patch| function can also be used to export hexahedral\n% elements directly by setting the meshType parameter to 'hex'.\n% Furthermore, it is possible to subdevide the ellongated hexahedral\n% elements using a certain number of split iterations. Below is an example\n% of hexahedral element output with increasing number of split iterations\n% used for the ellongated hexahedral elements.\n\nboxDim=[1 1 1];\nboxEl=[1 1 1];\n[meshStruct]=hexMeshBox(boxDim,boxEl);\nE=meshStruct.E;\nV=meshStruct.V;\nF=meshStruct.F;\n[indBoundary]=tesBoundary(F);\n\nclear controlParameter\n\n% Create lattice structure\ncontrolParameter.latticeSide=2;\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\ncontrolParameter.shrinkFactor=0.25;\ncontrolParameter.meshType='hex';\n\nhexSplitSet=[0 1 2];\ncFigure;\ngtitle('Lattice structure hex element output and element mesh refinement',fontSize);\n\nc=1; %counter for plotting\nfor latticeSide=1:2\n controlParameter.latticeSide=latticeSide;\n for q=1:numel(hexSplitSet)\n controlParameter.hexSplit=hexSplitSet(q); %The current mesh type\n \n [Es1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n \n [Fs1,Cs1F]=element2patch(Es1,Cs1); %Patch data for plotting\n \n % Visualizing input mesh and lattice structures\n subplot(2,numel(hexSplitSet),c);\n hold on; title(['hexSplit=',num2str(hexSplitSet(q))]);\n gpatch(Fs1,Vs1,Cs1F,'k',0.8,2);\n colormap(gjet(250));\n axisGeom(gca,fontSize);\n camlight headlight; lighting flat;\n c=c+1;\n end\nend\ndrawnow;\n\n%%\n% \n\n[V,F]=platonic_solid(1,1);\nE=[1 2 4 3];\n\n% \n% boxDim=[1 1 1];\n% boxEl=[1 1 1];\n% [meshStruct]=hexMeshBox(boxDim,boxEl);\n% E=meshStruct.E;\n% V=meshStruct.V;\n% F=meshStruct.F;\n[indBoundary]=tesBoundary(F);\n\nclear controlParameter\n\n% Create lattice structure\ncontrolParameter.latticeSide=2;\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\ncontrolParameter.shrinkFactor=0.25;\ncontrolParameter.meshType='hex';\n\nhexSplitSet=[0 1 2];\ncFigure;\ngtitle('Lattice structure hex element output and element mesh refinement',fontSize);\n\nc=1; %counter for plotting\nfor latticeSide=1:2\n controlParameter.latticeSide=latticeSide;\n for q=1:numel(hexSplitSet)\n controlParameter.hexSplit=hexSplitSet(q); %The current mesh type\n \n [Es1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n \n [Fs1,Cs1F]=element2patch(Es1,Cs1); %Patch data for plotting\n \n % Visualizing input mesh and lattice structures\n subplot(2,numel(hexSplitSet),c);\n hold on; title(['hexSplit=',num2str(hexSplitSet(q))]);\n gpatch(Fs1,Vs1,Cs1F,'k',0.8,2);\n colormap(gjet(250));\n axisGeom(gca,fontSize);\n camlight headlight; lighting flat;\n c=c+1;\n end\nend\ndrawnow;\n\n%% Example: Creating lattice structure variations through input mesh conversion/subdevission\n\ncPar.shrinkFactor=0.25;\ncPar.numDigitKeep=5;\ncPar.meshType='quad';\n\ncParSmooth.Method='HC';\ncParSmooth.n=10;\n\ncFigure;\nc=1;\nfor latticeSide=1:2\n for testCase=1:3\n \n switch testCase\n case 1\n boxEl=[1 1 1];\n [meshStruct]=hexMeshBox(boxDim,boxEl);\n E=meshStruct.E;\n V=meshStruct.V;\n F=meshStruct.F;\n Ft=F;\n Vt=V;\n [E,V]=subHex(E,V,1,1);\n case 2\n boxEl=[1 1 1];\n [meshStruct]=hexMeshBox(boxDim,boxEl);\n E=meshStruct.E;\n V=meshStruct.V;\n F=meshStruct.F;\n Ft=F;\n Vt=V;\n [E,V]=subHex(E,V,1,1);\n [E,V,~]=hex2tet(E,V,[],1);\n case 3\n boxEl=[1 1 1];\n [meshStruct]=hexMeshBox(boxDim,boxEl);\n E=meshStruct.E;\n V=meshStruct.V;\n F=meshStruct.F;\n Ft=F;\n Vt=V;\n [E,V,~]=hex2tet(E,V,[],1);\n [E,V]=tet2hex(E,V);\n end\n \n %Get boundary indices\n [F]=element2patch(E); %Patch data for plotting\n [indBoundary]=tesBoundary(F); %Boundary indices\n \n %Compute lattice\n cPar.latticeSide=latticeSide;\n cPar.indBoundary=indBoundary;\n [Fn,Vn,Cn]=element2lattice(E,V,cPar);\n \n% %Refine mesh\n% [Fn,Vn]=subQuad(Fn,Vn,1);\n% Cn=repmat(Cn,[4 1]); %Replicate color info\n% \n% %Smoothen\n% indRigid=Fn(Cn==1,:);\n% indRigid=unique(indRigid(:)); %Indices for boundary elements to hold on to\n% cParSmooth.RigidConstraints=indRigid;\n% if cParSmooth.n>0\n% [Vn]=tesSmooth(Fn,Vn,[],cParSmooth); %Smoothen mesh\n% end\n \n %Visualize\n subplot(2,3,c); hold on;\n gpatch(Ft,Vt,0.5*ones(1,3),'k',0.25);\n gpatch(Fn,Vn,Cn,'k',1);\n colormap(cMap);\n axisGeom(gca,fontSize);\n camlight headlight;\n lighting flat;\n \n c=c+1;\n end\nend\ndrawnow;\n\n%% Example: Create lattice structures on arbitry input meshes\n% Below is an example of a general tetrahedral mesh\n\n%%\n\ntestCase=2;\nswitch testCase\n case 1\n [F,V,~]=geoSphere(2,1); % Building a geodesic dome surface model\n case 2\n [F,V]=stanford_bunny('g'); %Bunny\n V_mean=mean(V,1);\n V=V-V_mean(ones(size(V,1),1),:);\nend\n\n%% \n% Using tetgen to create a tetrahedral mesh (see |HELP_runTetGen|)\n\nstringOpt='-pq1.2AaY';\n\ninputStruct.stringOpt=stringOpt;\ninputStruct.Faces=fliplr(F);\ninputStruct.Nodes=V;\ninputStruct.holePoints=[];\ninputStruct.faceBoundaryMarker=ones(size(F,1),1); %Face boundary markers\ninputStruct.regionPoints=getInnerPoint(F,V); %region points\ninputStruct.regionA=tetVolMeanEst(F,V);\ninputStruct.minRegionMarker=2; %Minimum region marker\n\n[meshOutput]=runTetGen(inputStruct); %Run tetGen \n\nFb=meshOutput.facesBoundary;\nCb=meshOutput.boundaryMarker;\nV=meshOutput.nodes;\nCE=meshOutput.elementMaterialID;\nE=meshOutput.elements;\nF=meshOutput.faces;\n[indBoundary]=tesBoundary(F); %Boundary indices\n\n%%\n% Create lattice structure\n\n% Define spatially varying (on nodes) shrink factor\ns=V(:,1);\ns=s-min(s(:));\ns=s./max(s(:)); \ns=(s*0.6)+0.05;\n\nclear controlParameter\ncontrolParameter.shrinkFactor=s; %Strut sides are formed by shrinking the input mesh faces by this factor\ncontrolParameter.numDigitKeep=5; %used for merging nodes\ncontrolParameter.meshType='quad'; %desired output mesh type\ncontrolParameter.indBoundary=indBoundary; %indices of the boundary faces\ncontrolParameter.latticeSide=1; %1=side 1 the edge lattice, 2=side 2 the dual lattice to the edge lattice\n\n[Fs1,Vs1,Cs1]=element2lattice(E,V,controlParameter); %Get lattice structure\n\n%% \n% PLOTTING MODEL \n\n%Selecting half of the model to see interior\nY=V(:,2); YE=mean(Y(E),2);\nlogicCutView=YE>mean(Y);\n[Fs,Cs]=element2patch(E(logicCutView,:),CE(logicCutView),'tet4');\n\ncFigure;\nhold on; \ntitle('Cut view of tetrahedral mesh model','FontSize',fontSize);\ngpatch(Fb,V,0.5*ones(1,3),'none',0.5);\ngpatch(Fs,V,Cs,'k',1);\ncamlight headlight;\naxisGeom(gca,fontSize); \naxis off; \ncolormap(cMap); \ndrawnow;\n\n%%\n% Visualize lattice structure\ncFigure;\nhold on; \ntitle('Lattice structure on arbitrary input mesh','FontSize',fontSize);\n% gpatch(Fb,V,0.5*ones(1,3),'none',0.5);\ngpatch(Fs1,Vs1,Cs1,'none',1);\ncamlight headlight; lighting flat;\naxisGeom(gca,fontSize); \naxis off; \ncolormap(cMap); \ndrawnow;\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_element2lattice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6074720340245688}} {"text": "%Corrects the navigation states using the Kalman generated error values\n%if size(att)=[4,1], it assumes att=qbn else it assumes att=Cbn\n%vel=Vn\n%dx=corrections where position errors are defined as dr^n (order:[pos, vel, att])\n%delta_x(k)=K(delta_y(k)-h(delta_x(k|k-1)))=K*delta_y(k)\n\nfunction [att_new, Ve_new, ecef_new]=correctnav_eframe_v000(att, Ve, ecef, dx)\n\n%Correct the position\necef_new=ecef-dx(1:3);\n\n%velocity correction\nVe_new=Ve-dx(4:6);\n\n%attitude correction\nif (size(att,1)==3) %attitude is represented as DCM\n Cet=rot2dcm_v000(dx(7:9)); %Erroneous to true navigation frame:DCM=(I+S(ang))\n att_new=Cet*att;\nelse %attitude is quaternion\n %Method I\n qet=rvec2quat_v000(dx(7:9));\n att_new=quatmult_v000(qet, att);\n \n% %Method II:\n% %Method I involves some trigonometric functions. Here is a\n% %algebraic correction method (See: Chung 1996-Eq:16) (Special thanks to Kaygisiz)\n% R=[-q(2) -q(3) -q(4);q(1) q(4) -q(3);q(-4) q(1) q(2);q(3) q(-2) q(1)];\n% dq=-0.5*R*dx(7:9);\n% att_new=att_new-dq;\n% att_new=att_new/norm(att_new); %optional\nend\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/correction/correctnav_eframe_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6073133264220648}} {"text": "function [k,a]=invkini(x,y,phi)\nglobal l1 l2 l3\n l1=1;l2=1;l3=0.5;\nxx=x-l3*cos(phi);\nyy=y-l3*sin(phi);\nk=(xx^2+yy^2-l1^2-l2^2)/(2*l1*l2);\nif k > 1\n a=[];\n return\nend\nt2=acos(k);\nd=l1^2+l2^2+2*l1*l2*cos(t2);\ncc=(xx*(l1+l2*cos(t2))+yy*l2*sin(t2))/d;\nss=(-xx*l2*sin(t2)+yy*(l1+l2*cos(t2)))/d;\nt1=atan2(ss,cc);\nt3=phi-t1-t2;\na=[ t1 t2 t3];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23289-motion-planning-for-a-robot-arm-by-using-genetic-algorithm/robot motion planning/matlab code/invkini.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6071446521949427}} {"text": "function [rResult] = relm_HypothesisTest(vRatesH, vRatesN, nNumberSimulation, fMagThreshold)\n%RELMTEST\n%script to test two earthqauake rate hypotheses using earthquake data\n%\n% park1=vRatesH;\n% park2=vRatesN;\n% clear test null;\n% xmin(i)=park1(j,1);\n% xmax(i)=park1(j,2);\n% ymin(i)=park1(j,3);\n% ymax(i)=park1(j,4);\n% zmin(i)=park1(j,5);\n% zmax(i)=park1(j,6);\n% magmin(i)=park1(j,7);\n% magmax(i)=park1(j,8);\n% lamda1(i)=park1(j,9);\n% weight(i)=park1(j,10);\n% Get the numbers of observed earthquakes per bin\nvNumberQuake = vRatesH(:,11);\n% Get the lower magnitude-limits per bin\nvMagMin = vRatesH(:,7);\n% Get the forecasted numbers of events per bin\nvLambdaH = vRatesH(:,9);\nvLambdaN = vRatesN(:,9);\n% Get the weightings per bins\nvWeightH = vRatesH(:,10);\nvWeightN = vRatesN(:,10);\nvWeightCombined = vWeightH .* vWeightN .* (vMagMin > fMagThreshold);\n\n% Remove rows of matrix for which weight is zero\n[nRow, nColumn] = size(vRatesH);\nnNewIndex = 0;\nfor nCnt = 1:nRow\n if vWeightCombined(nCnt)>0\n nNewIndex = nNewIndex + 1;\n vWeight(nNewIndex) = vWeightCombined(nCnt);\n vNumberQuakeSel(nNewIndex) = vNumberQuake(nCnt);\n vLambdaHSel(nNewIndex) = vLambdaH(nCnt);\n vLambdaNSel(nNewIndex) = vLambdaN(nCnt);\n mmin(nNewIndex) = vMagMin(nCnt);\n end\nend\n\n% Get the number of events (weighted)\nvNumberQuake = vWeight .* vNumberQuakeSel;\nnNumberQuake = sum(vNumberQuake);\n\n% Weight the important columns\nvLambdaH = vWeight .* vLambdaHSel;\nvLambdaN = vWeight .* vLambdaNSel;\n% Garbage collection\nclear vRatesH vRatesN vLambdaHSel vLambdaNSel vNumberQuakeSel vMagMin vWeightCombined vWeightH vWeightN;\n\n%make a weighted magnitude-frequency plot\n%\n% mf=[mmin;vNumberQuake;vLambdaH;vLambdaN]';\n% mfsort=sortrows(mf);\n% mag=mfsort(:,1);\n%\n% Fobs=flip(cumsum(flip(mfsort(:,2))));\n% Fth1=flip(cumsum(flip(mfsort(:,3))));\n% Fth2=flip(cumsum(flip(mfsort(:,4))));\n% figure%(1)\n% semilogy(mag,Fobs,'r',mag,Fth1,'g',mag,Fth2,'b');\n% grid;\n% axis([3,8,.0001,100]);\n%\n% Evaluate whether total number of quakes is consistent with H1\n%\n%\nNhat=sum(vLambdaH);\npeq=poisspdf(nNumberQuake, Nhat); % probability of exactly Nquake\nPle=poisscdf(nNumberQuake, Nhat); % probability of less than or equal to Nquake\nPless=Ple-peq; % probability of less than Nquake\nPmore=1-Ple; % probability of more than Nquake\nrResult.P_H_Equal = peq;\nrResult.P_H_Less = Pless;\nrResult.P_H_More = Pmore;\nrResult.Nhat_H = Nhat;\nlamcum1=cumsum(vLambdaH)/rResult.Nhat_H;\n% Evaluate whether total number of quakes is consistent with H2\nNhat=sum(vLambdaN);\npeq=poisspdf(nNumberQuake, Nhat); % probability of exactly Nquake\nPle=poisscdf(nNumberQuake, Nhat); % probability of less than or equal to Nquake\nPless=Ple-peq; % probability of less than Nquake\nPmore=1-Ple; % probability of more than Nquake\nrResult.P_N_Equal = peq;\nrResult.P_N_Less = Pless;\nrResult.P_N_More = Pmore;\nrResult.Nhat_N = Nhat;\nlamcum2=cumsum(vLambdaN)/rResult.Nhat_N;\n%\n% simulate catalogs according to H1,\n% and evaluate likelihood scores of nsquake1 and real catalog using lamda1 and lamda2\n%\ntry\n nsquake=simulate(nNumberQuake, vLambdaH, nNumberSimulation);\n [rResult.LLR_H, rResult.fRank11, rResult.fRank12] = Rtest(vLambdaH, vLambdaN, vNumberQuake, nsquake, vWeight);\ncatch\n rResult.LLR_H = nan;\n rResult.fRank11 = nan;\n rResult.fRank12 = nan;\nend\n%\n% simulate catalogs according to H2,\n% and evaluate likelihood scores of nsquake1 and real catalog using lamda1 and lamda2\n%\ntry\n nsquake=simulate(nNumberQuake, vLambdaN, nNumberSimulation);\n [rResult.LLR_N, rResult.fRank21, rResult.fRank22] = Rtest(vLambdaH, vLambdaN, vNumberQuake, nsquake, vWeight);\ncatch\n rResult.LLR_N = nan;\n rResult.fRank21 = nan;\n rResult.fRank22 = nan;\nend\n%\n%Plot cumulative likelihood scores for two hypotheses\n%\nrResult.fAlpha = sum(rResult.LLR_N > 0)/nNumberSimulation;\nrResult.fBeta = sum(rResult.LLR_H < 0)/nNumberSimulation;\n%index=[1:nNumberSimulation]/nNumberSimulation;\n%x=[0,0];y=[0,1];\n%figure_w_normalized_uicontrolunits(2);\n%plot(rResult.LLR_H,index,'g',rResult.LLR_N,index,'r',x,y,'b')';\n%xlabel('Likelihood ratio (Variable b/Constant b)')';\n%ylabel('Fraction of cases');\n%title('Green assumes variable-b hypothesis; Red assumes constant=b hypothesis');\n% nNumberQuake, Nhat1,Nhat2,P1_less,P1_more,P2_less,P2_more, alpha, beta, rank11,rank12, rank21, rank22\nrResult.nNumberQuake = nNumberQuake;\nrResult.nNumberSimulation = nNumberSimulation;\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/danijel/dave/relm_HypothesisTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6071383765632348}} {"text": "function left = r8vec_bracket4 ( nt, t, ns, s )\n\n%*****************************************************************************80\n%\n%% R8VEC_BRACKET4 finds the interval to each of a vector of values.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8's.\n%\n% The routine always returns the index LEFT of the sorted array\n% T with the property that either\n% * T is contained in the interval [ T(LEFT), T(LEFT+1) ], or\n% * T < T(LEFT) = T(1), or\n% * T > T(LEFT+1) = T(N).\n%\n% The routine is useful for interpolation problems, where\n% the abscissa must be located within an interval of data\n% abscissas for interpolation, or the \"nearest\" interval\n% to the (extreme) abscissa must be found so that extrapolation\n% can be carried out.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NT, length of the input array.\n%\n% Input, real T(NT), an array that has been sorted\n% into ascending order.\n%\n% Input, integer NS, the number of points to be bracketed.\n%\n% Input, real S(NS), values to be bracketed by entries of T.\n%\n% Output, integer LEFT(NS).\n% LEFT(I) is set so that the interval [ T(LEFT(I)), T(LEFT(I)+1) ]\n% is the closest to S(I); it either contains S(I), or else S(I)\n% lies outside the interval [ T(1), T(NT) ].\n%\n\n%\n% Check the input data.\n%\n if ( nt < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_BRACKET4 - Fatal error!\\n' );\n fprintf ( 1, ' NT must be at least 2.\\n' );\n error ( 'R8VEC_BRACKET4 - Fatal error!' );\n end\n\n for i = 1 : ns\n\n left(i) = floor ( ( nt + 1 ) / 2 );\n%\n% CASE 1: S < T(LEFT):\n% Search for S in [T(I), T(I+1)] for intervals I = 1 to LEFT-1.\n%\n if ( s(i) < t(left(i)) )\n\n if ( left(i) == 1 )\n continue\n elseif ( left(i) == 2 )\n left(i) = 1;\n continue\n elseif ( t(left(i)-1) <= s(i) )\n left(i) = left(i) - 1;\n continue\n elseif ( s(i) <= t(2) )\n left(i) = 1;\n continue\n end\n%\n% ...Binary search for S in [T(I), T(I+1)] for intervals I = 2 to LEFT-2.\n%\n low = 2;\n high = left(i) - 2;\n\n while ( 1 )\n \n if ( low == high )\n left(i) = low;\n break\n end\n\n mid = floor ( ( low + high + 1 ) / 2 );\n\n if ( t(mid) <= s(i) )\n low = mid;\n else\n high = mid - 1;\n end\n\n end\n%\n% CASE2: T(LEFT+1) < S:\n% Search for S in [T(I),T(I+1)] for intervals I = LEFT+1 to N-1.\n%\n elseif ( t(left(i)+1) < s(i) )\n\n if ( left(i) == nt - 1 )\n continue\n elseif ( left(i) == nt - 2 )\n left(i) = left(i) + 1;\n continue\n elseif ( s(i) <= t(left(i)+2) )\n left(i) = left(i) + 1;\n continue\n elseif ( t(nt-1) <= s(i) )\n left(i) = nt - 1;\n continue\n end\n%\n% ...Binary search for S in [T(I), T(I+1)] for intervals I = LEFT+2 to NT-2.\n%\n low = left(i) + 2;\n high = nt - 2;\n\n while ( 1 )\n\n if ( low == high )\n left(i) = low;\n break\n end\n\n mid = floor ( ( low + high + 1 ) / 2 );\n\n if ( t(mid) <= s(i) )\n low = mid;\n else\n high = mid - 1;\n end\n\n end\n%\n% CASE3: T(LEFT) <= S <= T(LEFT+1):\n% S is in [T(LEFT), T(LEFT+1)].\n%\n else\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8vec_bracket4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.6071193869841175}} {"text": "function [B0, beta0, phi0, S0, alpha0]=nwprior(ar,arvar,lambda1,lambda3,lambda4,n,m,p,k,q,prior,priorexo)\n\n\n\n% function [B0 beta0 phi0 S0 alpha0]=nwprior(ar,arvar,lambda1,lambda3,lambda4,n,m,p,k,q,prior,bex)\n% returns prior values from hyperparameters, for the normal-Wishart prior\n% inputs: - scalar 'ar': prior value of the autoregressive coefficient on own first lag (defined p 15 of technical guide)\n% - vector 'arvar': residual variance of individual AR models estimated for each endogenous variable\n% - scalar 'lambda1': overall tightness hyperparameter (defined p 16 of technical guide)\n% - scalar 'lambda2': cross-variable weighting hyperparameter(defined p 16 of technical guide)\n% - scalar 'lambda3': lag decay hyperparameter (defined p 16 of technical guide)\n% - scalar 'lambda4': exogenous variable tightness hyperparameter (defined p 17 of technical guide)\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'm': number of exogenous variables in the BVAR model (defined p 7 of technical guide)\n% - integer 'p': number of lags included in the model (defined p 7 of technical guide)\n% - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)\n% - integer 'q': total number of coefficients to estimate for the BVAR model (defined p 7 of technical guide)\n% - integer 'prior': value to determine which prior applies to the model\n% outputs: - matrix 'B0': the non-vectorised form of beta0\n% - vector 'beta0': vector of prior values for beta (defined in 1.3.4)\n% - matrix 'phi0': prior covariance matrix for the VAR coefficients in the case of a normal-Wishart prior (defined in 1.4.7)\n% - matrix 'S0': prior scale matrix for sigma (defined in 1.4.11)\n% - integer 'alpha0': prior degrees of freedom for sigma (defined in 1.4.11)\n\n\n% start with beta0, defined in (1.3.4)\nbeta0=zeros(q,1);\n\nidx = 1:n;\nif isscalar(ar)\n beta0((idx-1)*k+idx,1) = ar;\nelse\n beta0((idx-1)*k+idx,1) = ar(idx,1);\nend\n\n% if a prior for the exogenous variables is selected put it in here:\nfor ii=1:n\n for jj=1:m\n beta0(k*ii-m+jj)=priorexo(ii,jj);\n end\nend\n% unvectorize (reshape) the vector to obtain the matrix B0\nB0=reshape(beta0,k,n);\n\n% next compute phi0, the variance-covariance matrix of beta, defined in (1.4.7)\n\n% set first phi0 as a k*k matrix of zeros\nphi0=zeros(k,k);\n\n% set the variance for coefficients on lagged values, using (1.4.5)\nfor ii=1:n\n for jj=1:p\n phi0((jj-1)*n+ii,(jj-1)*n+ii)=(1/arvar(ii,1))*(lambda1/jj^lambda3)^2;\n end\nend\n\n% set the variance for exogenous variables, using (1.4.6)\nfor ii=1:m\n phi0(k-m+ii,k-m+ii)=(lambda1*lambda4(1,ii))^2;\nend\n\n\n% now compute alpha0 from (1.4.12)\nalpha0=n+2;\n\n\n% and finally compute S0, depending on which choice has been made for the prior ((1.4.13) or identity)\nif prior==21\n S0=(alpha0-n-1)*diag(arvar);\nelseif prior==22\n S0=eye(n);\nelse\nend", "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/nwprior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6071174301586086}} {"text": "classdef RWMOP17 < PROBLEM\n% \n% Bulk carriers design problem \n\n%------------------------------- Reference --------------------------------\n% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,\n% A benchmark-suite of real-world constrained multi-objective optimization\n% problems and some baseline results, Swarm and Evolutionary Computation,\n% 2021, 67: 100961.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Initialization\n function Setting(obj)\n obj.M = 3;\n obj.D = 6;\n obj.lower = [150.0 20.0 13.0 10.0 14.0 0.63];\n obj.upper = [274.32 32.31 25.0 11.71 18.0 0.75];\n obj.encoding = ones(1,obj.D);\n end\n %% Evaluate multiple solutions\n function Population = Evaluation(obj,varargin)\n x = varargin{1};\n L = x(:,1);\n B = x(:,2);\n D = x(:,3);\n T = x(:,4);\n V_k = x(:,5);\n C_B = x(:,6);\n\n a = 4977.06.*C_B.^2 - 8105.61.*C_B + 4456.51;\n b = -10847.2.*C_B.^2 + 12817.*C_B - 6960.32;\n F_n = 0.5144./(9.8065 .* L).^0.5;\n P = ((1.025.*L.*B.*T.*C_B).^(2/3).*V_k.^3)./(a + b.*F_n);\n\n W_s = 0.034.*L.^1.7.*B.^0.6.*D.^0.4.*C_B.^0.5;\n W_o = L.^0.8.*B.^0.6.*D.^0.3.*C_B.^0.1;\n W_m = 0.17.*P.^0.9;\n ls = W_s+W_o+W_m;\n\n D_wt = 1.025.*L.*B.*T.*C_B-ls;\n F_c = 0.19.*24.*P./1000 + 0.2;\n D_cwt = D_wt - F_c.*((5000.*V_k)./24 + 5)-2.*D_wt.^0.5;\n R_trp = 350./((5000.*V_k)./24 + 2.*(D_cwt./8000 + 0.5));\n ac = D_cwt.*R_trp;\n S_d = 5000.*V_k./24;\n\n C_c = 0.2.*1.3 .* (2000.*W_s.^0.85 + 3500.*W_o + 2400.*P.^0.8);\n C_r = 40000.*D_wt.^0.3;\n C_v = (1.05.*100.*F_c.*S_d + 6.3.*D_wt.^0.8).*R_trp;\n \n % Objectives\n f(:,1) = (C_c + C_r + C_v)./ac;\n f(:,2) = ls;\n f(:,3) = -ac;\n \n % Constraints\n g(:,1) = L./B - 6;\n g(:,2) = 15 - L./D;\n g(:,3) = 19 - L./T;\n g(:,4) = 0.45.*D_wt.^0.31 - T;\n g(:,5) = 0.7.*D + 0.7 - T;\n g(:,6) = 0.32 - F_n;\n g(:,7) = 0.53.*T + ((0.085.*C_B - 0.002).*B.^2)./(T.*C_B)-(1 + 0.52.*D) - 0.07.*B;\n g(:,8) = D_wt - 3000;\n g(:,9) = 500000 - D_wt;\n g = -g;\n Population = SOLUTION(varargin{1},f,g,varargin{2:end});\n obj.FE = obj.FE + length(Population);\n end\n %% Generate a point for hypervolume calculation\n function R = GetOptimum(obj,~)\n R = [-3.1514157e+03 8.2606298e+03 8.1260004e+02];\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/RWMOPs/RWMOP17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6071174287307377}} {"text": "function [u,sigma,eqn,info] = PoissonRT0(node,elem,pde,bdFlag,option)\n%% POISSONRT0 Poisson equation: lowest order RT element.\n%\n% [u,sigma] = PoissonRT0(node,elem,pde,bdFlag) produces an approximation of\n% the Poisson equation \n%\n% -div(d*grad(u))=f in \\Omega, with \n% Dirichlet boundary condition u=g_D on \\Gamma_D, \n% Neumann boundary condition d*grad(u)*n=g_N on \\Gamma_N\n%\n% in the mixed formulation:\n%\n% ------------------------------------------------------------------------\n% Find (\\sigma , u) in H_{g_N,\\Gamma_N}(div,\\Omega)\\times L^2(\\Omega) s.t. \n%\n% (d^-1\\sigma,\\tau) - (div \\tau, u) = <\\tau*n,g_D>_{\\Gamma_D} \n% \\forall \\tau in H_{0,\\Gamma_N}(div,\\Omega) \n% - (div \\sigma, v) = -(f,v) \n% \\forall v in L^2(\\Omega) \n%\n% where \n% H_{g,\\Gamma}(div,\\Omega) = {\\sigma \\in H(div,\\Omega); \\sigma*n = g \n% on \\Gamma \\subset \\partial\\Omega }.\n% ------------------------------------------------------------------------\n%\n% The unknown sigma = d*grad(u) is approximated using the lowest order\n% Raviart-Thomas element and u by piecewise constant element (with basis 1).\n%\n% [u,sigma] = PoissonRT0(node,elem,pde,bdFlag,option) specifies options\n% - option.solver\n% 'direct': the built in direct solver \\ (mldivide)\n% 'dmg': multigrid-type solvers mg is used.\n% 'uzawapcg': PCG for the Schur complement equation\n% 'none': only assemble the matrix equation but not solve\n%\n% The default setting is to use the direct solver for small size problems\n% and transforming based multigrid solvers for large size problems. \n%\n% Example\n%\n% exampleRT0\n%\n% Created by Ming Wang. Reorganized by Long Chen. Change basis for u. \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\n\n%% Diffusion coefficient\nif ~isfield(pde,'d'), pde.d = []; end\nif isfield(pde,'d') && ~isempty(pde.d)\n if isnumeric(pde.d)\n K = pde.d; % d is an array\n else % d is a function\n center = (node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:))/3;\n K = pde.d(center); % take inverse sequencil. \n end\nelse\n K = [];\nend\n\n%% Data structure\nelemold = elem;\n[elem,bdFlag] = sortelem(elem,bdFlag); % ascend ordering\n[elem2edge,edge] = dofedge(elem);\nNT = size(elem,1); NE = size(edge,1);\n[Dlambda,area,elemSign] = gradbasis(node,elem);\n\n%% Assemble matrix \nNsigma = NE; Nu = NT; Ndof = Nsigma + Nu;\n\n% M. Mass matrix for RT0 element\nM = getmassmatvec(elem2edge,area,Dlambda,'RT0',K);\n\n% B. negative divergence operator\nB = icdmat(double(elem2edge),elemSign*[1 -1 1]);\n\n% C. zero matrix.\nC = sparse(Nu,Nu);\n\nA = [M B';B C];\n\n%% Assemble right hand side.\nfu = zeros(Nu,1);\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isfield(option,'fquadorder')\n option.fquadorder = 2; % default order\nend\nif ~isempty(pde.f)\n\t[lambda,weight] = quadpts(option.fquadorder);\n\tnQuad = size(lambda,1);\n for p = 1:nQuad\n\t\t% quadrature points in the x-y coordinate\n\t\tpxy = lambda(p,1)*node(elem(:,1),:) ...\n\t\t\t+ lambda(p,2)*node(elem(:,2),:) ...\n\t\t\t+ lambda(p,3)*node(elem(:,3),:);\n\t\tfp = pde.f(pxy);\n\t\tfu = fu - fp*weight(p);\n end\n fu = fu.*area;\nend\nclear fp area\nF((Nsigma+1):(Ndof),1) = fu;\n\n%% Boundary Conditions\nif ~exist('bdFlag','var'), bdFlag = []; end\n[AD,F,bigu,freeDof,isPureNeumannBC] = getbdRT0(F);\neqn = struct('M',AD(1:NE,1:NE),'B',AD(NE+1:end,1:NE),'C',AD(NE+1:end,NE+1:end),...\n 'f',F(1:NE),'g',F(NE+1:end),'freeDof',freeDof);\n\n%% Solve the linear system.\n% Set up solver type\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 2e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % MGCG solver for large size systems\n option.solver = 'dmg';\n end\nelseif strcmp(option.solver,'mg')\n option.solver = 'dmg'; \nend\nsolver = option.solver;\n% solve\nswitch lower(solver);\n case 'direct'\n bigu(freeDof) = AD(freeDof,freeDof)\\F(freeDof);\n sigma = bigu(1:NE);\n u = bigu(NE+1:end); info =[];\n case 'none'\n sigma = []; u = []; info =[]; \n case 'dmg'\n [sigma,u] = dmg(eqn.M,eqn.B,eqn.C,eqn.f,eqn.g,elemold); \n case 'uzawapcg'\n [sigma,u] = uzawapcg(eqn.M,eqn.B,eqn.C,eqn.f,eqn.g,elemold);\nend\ninfo.solverTime = 0; info.assembleTime = 0; info.itStep = 0;\ninfo.stopErr = 0; info.flag = 0;\nif isPureNeumannBC == true % post process for u.\n ubar = sum(u.*area)/sum(area);\n u = u - ubar;\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,F,bigu,freeDof,isPureNeumannBC] = getbdRT0(F)\n %% GETBDRT0 Boundary conditions for Poisson equation: RT0 element.\n %\n % Created by Ming Wang. Improved the check of edgeSign by Long Chen.\n\n %%\n bigu = zeros(Ndof,1);\n \n %% Boundary conditions\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n\n %% Set up bdFlag\n if isempty(bdFlag) % no bdFlag information\n if ~isempty(pde.g_N) % case: Neumann\n bdFlag = setboundary(node,elem,'Neumann');\n elseif ~isempty(pde.g_D) % case: Dirichlet\n bdFlag = setboundary(node,elem,'Dirichlet');\n end\n end\n\n %% Find Dirichlet and Neumann dofs \n if ~isempty(bdFlag)\n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n isNeumann(elem2edge(bdFlag(:)==2)) = true;\n % Direction of boundary edges may not be the outwards normal\n % direction of the domain. edgeSign is introduced to record this\n % inconsistency.\n edgeSign = ones(NE,1);\n idx = (bdFlag(:,1) ~= 0) & (elemSign == -1);% first edge is on boundary\n edgeSign(elem2edge(idx,1)) = -1;\n idx = (bdFlag(:,2) ~= 0) & (elemSign == 1); % second edge is on boundary\n edgeSign(elem2edge(idx,2)) = -1;\n idx = (bdFlag(:,3) ~= 0) & (elemSign == -1);% first edge is on boundary\n edgeSign(elem2edge(idx,3)) = -1;\n end\n Dirichlet = edge(isDirichlet,:);\n Neumann = edge(isNeumann,:); \n isBdDof = false(Ndof,1); \n isBdDof(isNeumann) = true; % for mixed method, Neumann edges are fixed\n freeDof = find(~isBdDof);\n\n %% Dirichlet boundary condition (Neumann BC in mixed form)\n % We need only modify the rhs on dof associated with Dirichlet\n % boundary. Compute the int_e \\Phi\\cdot n g_D on the boundary using\n % quadrature rules.\n if ~isempty(pde.g_D) && isnumeric(pde.g_D) && (pde.g_D==0)\n pde.g_D = [];\n end\n if ~isempty(pde.g_D) && any(isDirichlet) \n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 2; % default order exact for linear gN\n end\n [lambda,weight] = quadpts1(option.gNquadorder);\n nQuad = size(lambda,1);\n for ip = 1:nQuad\n \tpxy = lambda(ip,1)*node(Dirichlet(:,1),:)+...\n lambda(ip,2)*node(Dirichlet(:,2),:); \n F(isDirichlet) = F(isDirichlet) + weight(ip)*pde.g_D(pxy);\n end\n F(isDirichlet) = F(isDirichlet).*edgeSign(isDirichlet);\n % no edge length since the basis of sigma contains it.\n end\n\n %% Neumann boundary condition (Dirichlet BC in mixed form)\n if ~isempty(pde.g_N) && any(isNeumann)\n % modify the rhs to include Dirichlet boundary condition \n mid = 1/2*(node(Neumann(:,1),:)+node(Neumann(:,2),:));\n ve = node(Neumann(:,1),:)-node(Neumann(:,2),:);\n edgeLength = sqrt(sum(ve.^2,2)); \n if isnumeric(pde.g_N)\n evalg_N = pde.g_N;\n else\n evalg_N = pde.g_N(mid);\n end\n bigu(isNeumann) = edgeLength.*evalg_N;\n if ~isempty(pde.d)\n bigu(isNeumann) = pde.d(mid).*bigu(isNeumann);\n end\n bigu(isNeumann) = bigu(isNeumann).*edgeSign(isNeumann);\n F = F - A*bigu;\n F(isNeumann) = bigu(isNeumann);\n end\n \n %% Pure Neumann boundary condition\n isPureNeumannBC = false;\n if ~any(isDirichlet) && any(isNeumann)\n freeDof = freeDof(1:end-1); % eliminate the kernel by enforcing u(NT) = 0;\n isBdDof(end) = true;\n isPureNeumannBC = true;\n% F(end) = 0;\n end\n\n %% Modify the matrix\n % Build Neumann boundary condition(Dirichlet BC in mixed form) into the\n % matrix AD by enforcing |AD(bdNode,bdNode)=I, \n % AD(bdNode,FreeNode)=0, AD(FreeNode,bdNode)=0|.\n if any(isBdDof)\n bdidx = zeros(Ndof,1); \n bdidx(isBdDof) = 1;\n Tbd = spdiags(bdidx,0,Ndof,Ndof);\n T = spdiags(1-bdidx,0,Ndof,Ndof);\n AD = T*A*T + Tbd;\n else\n AD = A;\n end\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/PoissonRT0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.607117422347744}} {"text": "function L=ishappy(n)\n\nN=n;\nL=0;\nNHistory=n;\nwhile L==0\n N=sum(str2num(num2str(N).').^2); %Sum digits \n if N==1 %n is a happy number\n L=1;\n elseif ismember(N,NHistory); %Kill we are in a loop\n break\n end\n NHistory=[NHistory N]; \nend\nNHistory=[NHistory 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/ishappy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6069052711459644}} {"text": "function [coeff, score, latent, tsquare] = princomp_largedata(x,econFlag)\n% Principal Components Analysis\n%\n% This is a version created for large data sets by Matthew Davidson\n%\n% The default Matlab PRINCOMP is naive to large data sets. Out-of-memory\n% errors are easily obtained on imaging data. The solution is to replace\n% concise but inefficient calls to repmat with loops and to eliminate\n% large, unused variables.\n%\n% Tested on random data sets and produces identical output as original\n% PRINCOMP. Speed penalty is drastic for small data. 50% slower on\n% 50x1000 element data set, but on a 50x10000, only 2% slower.\n%\n% COEFF = PRINCOMP(X) performs principal components analysis on the N-by-P\n% data matrix X, and returns the principal component coefficients, also\n% known as loadings. Rows of X correspond to observations, columns to\n% variables. COEFF is a P-by-P matrix, each column containing coefficients\n% for one principal component. The columns are in order of decreasing\n% component variance.\n%\n% PRINCOMP centers X by subtracting off column means, but does not\n% rescale the columns of X. To perform PCA with standardized variables,\n% i.e., based on correlations, use PRINCOMP(ZSCORE(X)). To perform PCA\n% directly on a covariance or correlation matrix, use PCACOV.\n%\n% [COEFF, SCORE] = PRINCOMP(X) returns the principal component scores,\n% i.e., the representation of X in the principal component space. Rows\n% of SCORE correspond to observations, columns to components.\n%\n% [COEFF, SCORE, LATENT] = PRINCOMP(X) returns the principal component\n% variances, i.e., the eigenvalues of the covariance matrix of X, in\n% LATENT.\n%\n% [COEFF, SCORE, LATENT, TSQUARED] = PRINCOMP(X) returns Hotelling's\n% T-squared statistic for each observation in X.\n%\n% When N <= P, SCORE(:,N:P) and LATENT(N:P) are necessarily zero, and the\n% columns of COEFF(:,N:P) define directions that are orthogonal to X.\n%\n% [...] = PRINCOMP(X,'econ') returns only the elements of LATENT that are\n% not necessarily zero, i.e., when N <= P, only the first N-1, and the\n% corresponding columns of COEFF and SCORE. This can be significantly\n% faster when P >> N.\n%\n% :See Also: BARTTEST, BIPLOT, CANONCORR, FACTORAN, PCACOV, PCARES, ROTATEFACTORS.\n%\n% :References:\n% 1. Jackson, J.E., A User's Guide to Principal Components,\n% Wiley, 1988.\n% 2. Jolliffe, I.T. Principal Component Analysis, 2nd ed.,\n% Springer, 2002.\n% 3. Krzanowski, W.J., Principles of Multivariate Analysis,\n% Oxford University Press, 1988.\n% 4. Seber, G.A.F., Multivariate Observations, Wiley, 1984.\n%\n% ..\n% Copyright 1993-2005 The MathWorks, Inc.\n% $Revision: 2.9.2.9 $ $Date: 2006/10/02 16:35:01 $\n% ..\n\n% ..\n% When X has more variables than observations, the default behavior is to\n% return all the pc's, even those that have zero variance. When econFlag\n% is 'econ', those will not be returned.\n% ..\n\nif nargin < 2, econFlag = 0; end\n\n[n,p] = size(x);\nif isempty(x)\n pOrZero = ~isequal(econFlag, 'econ') * p;\n coeff = zeros(p,pOrZero); coeff(1:p+1:end) = 1;\n score = zeros(n,pOrZero);\n latent = zeros(pOrZero,1);\n tsquare = zeros(n,1);\n return\nend\n\n% Center X by subtracting off column means\n%x0 = x - repmat(mean(x,1),n,1);\nfor i=1:size(x, 2)\n x(:,i) = x(:,i) - mean(x(:,i));\nend\nr = min(n-1,p); % max possible rank of X0\n\n% The principal component coefficients are the eigenvectors of\n% S = X0'*X0./(n-1), but computed using SVD.\n[U,sigma,coeff] = svd(x,econFlag); % put in 1/sqrt(n-1) later\n\nif nargout < 2\n % When econFlag is 'econ', only (n-1) components should be returned.\n % See comment below.\n if (n <= p) && isequal(econFlag, 'econ')\n coeff(:,n) = [];\n end\n\nelse\n % Project X0 onto the principal component axes to get the scores.\n if n == 1 % sigma might have only 1 row\n sigma = sigma(1);\n else\n sigma = diag(sigma);\n end\n score = U .* repmat(sigma',n,1); % == x*coeff\n sigma = sigma ./ sqrt(n-1);\n\n % When X has at least as many variables as observations, eigenvalues\n % n:p of S are exactly zero.\n if n <= p\n % When econFlag is 'econ', nothing corresponding to the zero\n % eigenvalues should be returned. svd(,'econ') won't have\n % returned anything corresponding to components (n+1):p, so we\n % just have to cut off the n-th component.\n if isequal(econFlag, 'econ')\n sigma(n,:) = []; % make sure this shrinks as a column\n coeff(:,n) = [];\n score(:,n) = [];\n\n % Otherwise, set those eigenvalues and the corresponding scores to\n % exactly zero. svd(,0) won't have returned columns of U\n % corresponding to components (n+1):p, need to fill those out.\n else\n sigma(n:p,1) = 0; % make sure this extends as a column\n score(:,n:p) = 0;\n end\n end\n\n % The variances of the pc's are the eigenvalues of S = X0'*X0./(n-1).\n latent = sigma.^2;\n\n % Hotelling's T-squared statistic is the sum of squares of the\n % standardized scores, i.e., Mahalanobis distances. When X appears to\n % have column rank < r, ignore components that are orthogonal to the\n % data.\n if nargout == 4\n if n > 1\n q = sum(sigma > max(n,p).*eps(sigma(1)));\n if q < r\n warning('stats:princomp:colRankDefX', ...\n ['Columns of X are linearly dependent to within machine precision.\\n' ...\n 'Using only the first %d components to compute TSQUARED.'],q);\n end\n else\n q = 0;\n end\n tsquare = (n-1) .* sum(U(:,1:q).^2,2); % == sum((score*diag(1./sigma)).^2,2)\n end\nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/princomp_largedata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6069052711459644}} {"text": "function data = get_kernel_data(X,kernel, kernel_params, Xtrain, datatrain);\n% nargin >= 4, when computations of the testing data depends on the training data (i.e., with incomplete Cholesky)\n\nswitch kernel\n\tcase { 'polynomial','polynomial-mkl','polynomial-bimkl'}\n\t\t[n , p ] = size(X);\n\t\tq = kernel_params(1);\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = q;\n\t\tdata.qs = (q+1) * ones(1,p);\t\t % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\tdata.ind_Xs{i} = cell(1,data.qs(i));\n\t\t\tdata.d_Xs{i} = zeros(1,data.qs(i));\n\t\t\tjK = iK;\n\t\t\tfor j=1:data.qs(i)\n\t\t\t\tdata.ind_Xs{i}{j} = iK;\n\t\t\t\tdata.d_Xs{i}(j) = 1;\n\t\t\t\tif j==1\n\t\t\t\t\tdata.Xs(:,iK) = ones(n,1);\t\t% constant term\n\t\t\t\telse\n\t\t\t\t\tdata.Xs(:,iK) = X(:,i).^(j-1) * sqrt( 1 / factorial(j-1) * factorial(q) / factorial(q-j+1) );\n\t\t\t\tend\n\t\t\t\tiK = iK + 1 ;\n\t\t\tend\n\t\t\tjK = jK + data.qs(i);\n\t\tend\n\n\n\tcase {'hermite', 'hermite-mkl', 'hermite-bimkl'}\n\t\t[n , p ] = size(X);\n\t\tq = kernel_params(2);\n\t\talpha = kernel_params(1);\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = q;\n\t\tdata.qs = (q+1) * ones(1,p);\t\t % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\tdata.ind_Xs{i} = cell(1,data.qs(i));\n\t\t\tdata.d_Xs{i} = zeros(1,data.qs(i));\n\t\t\tjK = iK;\n\t\t\tfor j=1:data.qs(i)\n\t\t\t\tdata.ind_Xs{i}{j} = iK;\n\t\t\t\tdata.d_Xs{i}(j) = 1;\n\n\t\t\t\tif j==1\n\t\t\t\t\tdata.Xs(:,iK) = ones(n,1);\n\t\t\t\telse\n\t\t\t\t\tdata.Xs(:,iK) = hermite_polynomials(j,X(:,i)) * sqrt( (alpha/2)^(j-1) / factorial(j-1) );\n\t\t\t\tend\n\t\t\t\tiK = iK + 1 ;\n\t\t\tend\n\t\t\tjK = jK + data.qs(i);\n\t\tend\n\n\n\n\n\tcase {'gauss-hermite', 'gauss-hermite-mkl', 'gauss-hermite-bimkl'}\n\t\t[n , p ] = size(X);\n\t\tq = kernel_params(3);\n\t\tsigma = kernel_params(1);\n\t\tb = kernel_params(2);\n\t\ta = 1/4/sigma;\n\t\tc = sqrt(a*a+2*a*b);\n\t\tA = a + b + c;\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = q;\n\t\tdata.qs = (q+1) * ones(1,p);\t\t % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\tdata.ind_Xs{i} = cell(1,data.qs(i));\n\t\t\tdata.d_Xs{i} = zeros(1,data.qs(i));\n\t\t\tjK = iK;\n\t\t\tfor j=1:data.qs(i)\n\t\t\t\tdata.ind_Xs{i}{j} = iK;\n\t\t\t\tdata.d_Xs{i}(j) = 1;\n\n\t\t\t\tdata.Xs(:,iK) = ( 1 - (b/A)^2).^.25 * hermite_polynomials(j,X(:,i) * sqrt( 2 * c ) ) .* exp( - ( b/A*(a+c) * X(:,i).^ 2 ) ) ...\n\t\t\t\t\t* sqrt( (b/A)^(j-1) / ( 2^(j-1) * factorial(j-1) )) ;\n\t\t\t\tiK = iK + 1 ;\n\t\t\tend\n\t\t\tjK = jK + data.qs(i);\n\t\tend\n\n\tcase {'gauss-hermite-full', 'gauss-hermite-full-mkl', 'gauss-hermite-full-bimkl'}\n\t\t% simply the same as 'gauss-hermite', but with the full kernels at\n\t\t% the end\n\t\t[n , p ] = size(X);\n\t\tq = kernel_params(3);\n\t\tsigma = kernel_params(1);\n\t\tb = kernel_params(2);\n\t\ta = 1/4/sigma;\n\t\tc = sqrt(a*a+2*a*b);\n\t\tA = a + b + c;\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = q+1;\n\t\tdata.qs = (q+2) * ones(1,p); % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\tdata.ind_Xs{i} = cell(1,data.qs(i));\n\t\t\tdata.d_Xs{i} = zeros(1,data.qs(i));\n\t\t\tjK = iK;\n\t\t\tfulldataloc = [];\n\t\t\tfor j=1:data.qs(i)-1\n\t\t\t\t% first kernels as before\n\t\t\t\tdata.ind_Xs{i}{j} = iK;\n\t\t\t\tdata.d_Xs{i}(j) = 1;\n\n\t\t\t\tdata.Xs(:,iK) = ( 1 - (b/A)^2).^.25 * hermite_polynomials(j,X(:,i) * sqrt( 2 * c ) ) .* exp( - ( b/A*(a+c) * X(:,i).^ 2 ) ) ...\n\t\t\t\t\t* sqrt( (b/A)^(j-1) / ( 2^(j-1) * factorial(j-1) )) ;\n\t\t\t\tfulldataloc = [ fulldataloc; iK ];\n\n\t\t\t\tiK = iK + 1 ;\n\t\t\tend\n\n\n\t\t\tif nargin < 4\n\t\t\t\t% last kernel: first build the kernel matrix, then takes its\n\t\t\t\t% incomplete Cholesky decomposition\n\n\t\t\t\tK = exp( - b * sqdist(X(:,i)',X(:,i)' ) ) - data.Xs(:,fulldataloc) * data.Xs(:,fulldataloc)';\n\t\t\t\t[Gf,Pf,mf,residualf] = icd_general(K,1e-3,kernel_params(6));\n\t\t\t\tIf = Pf(1:mf);\n\t\t\t\tdata.Is{i} = If;\t\t\t\t\t% these two for test data\n\n\t\t\t\t[temp,Pif] = sort(Pf);\n\t\t\t\tGf = Gf(Pif,1:mf);\n\t\t\t\tdata.d_Xs{i}(end) = mf;\n\t\t\t\tdata.ind_Xs{i}{end} = iK:iK+mf-1;\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{end}) = Gf;\n\t\t\t\tiK = iK+mf;\n\t\t\telse\n\t\t\t\t% last kernel for test data! This compute testing data\n\t\t\t\tK = exp( - b * sqdist(X(:,i)',Xtrain(datatrain.Is{i},i)' ) ) - data.Xs(:,fulldataloc) * datatrain.Xs(datatrain.Is{i},fulldataloc)';\n\t\t\t\tdata.d_Xs{i}(end) = datatrain.d_Xs{i}(end);\n\t\t\t\tdata.ind_Xs{i}{end} = datatrain.ind_Xs{i}{end};\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{end}) = K * inv( datatrain.Xs(datatrain.Is{i},data.ind_Xs{i}{end})' ) ;\n\t\t\t\tiK = iK+data.d_Xs{i}(end);\n\n\t\t\tend\n\t\tend\n\n\n\n\n\n\n\tcase {'anova', 'anova-mkl', 'anova-bimkl'}\n\t\t% simply the same as 'gauss-hermite', but with the full kernels at\n\t\t% the end\n\t\t[n , p ] = size(X);\n\t\tb = kernel_params(1);\n\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = 1;\n\t\tdata.qs = 2 * ones(1,p); % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\t% constant term\n\t\t\tdata.ind_Xs{i} = cell(1,2);\n\t\t\tdata.d_Xs{i} = zeros(1,2);\n\t\t\tdata.ind_Xs{i}{1} = iK;\n\t\t\tdata.d_Xs{i}(1) = 1;\n\t\t\tdata.Xs(:,iK) = ones(size(X,1),1);\n\t\t\tiK = iK + 1 ;\n\n\t\t\tif nargin < 4\n\t\t\t\t% first build the kernel matrix, then takes it\n\t\t\t\t% incomplete Cholesky decomposition\n\n\t\t\t\tK = exp( - b * sqdist(X(:,i)',X(:,i)' ) );\n\t\t\t\t[Gf,Pf,mf,residualf] = icd_general(K,1e-3,kernel_params(4));\n\t\t\t\tIf = Pf(1:mf);\n\n\t\t\t\tdata.Is{i} = If;\t\t\t\t\t% these two for test data\n\t\t\t\t[temp,Pif] = sort(Pf);\n\t\t\t\tGf = Gf(Pif,1:mf);\n\t\t\t\tdata.d_Xs{i}(2) = mf;\n\t\t\t\tdata.ind_Xs{i}{2} = iK:iK+mf-1;\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{2}) = Gf;\n\t\t\t\tiK = iK+mf;\n\t\t\telse\n\t\t\t\t% last kernel for test!\n\t\t\t\tK = exp( - b * sqdist(X(:,i)',Xtrain(datatrain.Is{i},i)' ) );\n\t\t\t\tdata.d_Xs{i}(2) = datatrain.d_Xs{i}(2);\n\t\t\t\tdata.ind_Xs{i}{2} = datatrain.ind_Xs{i}{2};\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{2}) = K * inv( datatrain.Xs(datatrain.Is{i},data.ind_Xs{i}{2})' ) ;\n\t\t\t\tiK = iK+data.d_Xs{i}(2);\n\n\t\t\tend\n\t\tend\n\n\n\n\n\n\tcase {'base kernels', 'base kernels-mkl', 'base kernels-bimkl'}\n\t\tp = kernel_params(1);\n\t\tif nargin<4\n\t\t\t% train\n\t\t\tn = size(X,1);\n\t\t\tn = floor( sqrt(2 * n) );\n\t\telse\n\t\t\t% test\n\t\t\tntrain = size(Xtrain,1);\n\t\t\tntrain = floor( sqrt(2 * ntrain) );\n\t\t\tn = size(X,1) / ntrain;\n\t\tend\n\t\tq = kernel_params(2);\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = kernel_params(2);\n\t\tdata.qs = (q+1) * ones(1,p);\t\t\t% number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs));\t\t% storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\t% constant term\n\t\t\tdata.ind_Xs{i} = cell(1,2);\n\t\t\tdata.d_Xs{i} = zeros(1,2);\n\t\t\tdata.ind_Xs{i}{1} = iK;\n\t\t\tdata.d_Xs{i}(1) = 1;\n\t\t\tdata.Xs(:,iK) = ones(n,1);\n\t\t\tiK = iK + 1 ;\n\n\t\t\tif nargin < 4\n\t\t\t\t% first build the kernel matrix, then takes it\n\t\t\t\t% incomplete Cholesky decomposition\n\t\t\t\tfor j=1:q\n\t\t\t\t\tK = double( devectorize_single(X(:,i,j)) );\n\n\t\t\t\t\t[Gf,Pf,mf,residualf] = icd_general(K,1e-3,kernel_params(5));\n\t\t\t\t\tIf = Pf(1:mf);\n\n\t\t\t\t\tdata.Is{i}{j+1} = If;\t\t\t\t\t% these two for test data\n\t\t\t\t\t[temp,Pif] = sort(Pf);\n\t\t\t\t\tGf = Gf(Pif,1:mf);\n\t\t\t\t\tdata.d_Xs{i}(j+1) = mf;\n\t\t\t\t\tdata.ind_Xs{i}{j+1} = iK:iK+mf-1;\n\n\t\t\t\t\tdata.Xs(:,data.ind_Xs{i}{j+1}) = Gf;\n\t\t\t\t\tiK = iK+mf;\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tfor j=1:q\n\n\t\t\t\t\tK = double( reshape(X(:,i,j) ,n,ntrain ) );\n\t\t\t\t\tK = K(:,datatrain.Is{i}{j+1});\n\t\t\t\t\tdata.d_Xs{i}(j+1) = datatrain.d_Xs{i}(j+1);\n\t\t\t\t\tdata.ind_Xs{i}{j+1} = datatrain.ind_Xs{i}{j+1};\n\t\t\t\t\tdata.Xs(:,data.ind_Xs{i}{j+1}) = K * inv( datatrain.Xs(datatrain.Is{i}{j+1},data.ind_Xs{i}{j+1})' ) ;\n\t\t\t\t\tiK = iK+data.d_Xs{i}(j+1);\n\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\tcase {'spline', 'spline-mkl', 'spline-bimkl'}\n\t\t% simply the same as 'gauss-hermite', but with the full kernels at\n\t\t% the end\n\t\t[n , p ] = size(X);\n\t\tdata.n = n ;\n\t\tdata.p = p;\n\t\tdata.q = 2;\n\t\tdata.qs = 3 * ones(1,p); % number of kernels per directions\n\t\tdata.Xs = zeros(n,sum(data.qs)*30); % storing all dimensions in the same vector\n\t\tdata.ind_Xs = cell(1,p);\n\t\tdata.d_Xs = cell(1,p);\n\t\tiK = 1;\n\t\tfor i=1:p\n\t\t\t% constant term\n\t\t\tdata.ind_Xs{i} = cell(1,2);\n\t\t\tdata.d_Xs{i} = zeros(1,2);\n\n\t\t\tdata.ind_Xs{i}{1} = iK;\n\t\t\tdata.d_Xs{i}(1) = 1;\n\t\t\tdata.Xs(:,iK) = ones(size(X,1),1);\n\t\t\tiK = iK + 1 ;\n\n\t\t\tdata.ind_Xs{i}{2} = iK;\n\t\t\tdata.d_Xs{i}(2) = 1;\n\t\t\tdata.Xs(:,iK) = X(:,i);\n\t\t\tiK = iK + 1 ;\n\n\n\t\t\tif nargin < 4\n\t\t\t\t% first build the kernel matrix, then takes it\n\t\t\t\t% incomplete Cholesky decomposition\n\t\t\t\tK = compute_cubic_spline_kernel(X(:,i),X(:,i));\n\t\t\t\t[Gf,Pf,mf,residualf] = icd_general(K,1e-3,kernel_params(3));\n\t\t\t\tIf = Pf(1:mf);\n\n\t\t\t\tdata.Is{i} = If;\t\t\t\t\t% these two for test data\n\t\t\t\t[temp,Pif] = sort(Pf);\n\t\t\t\tGf = Gf(Pif,1:mf);\n\t\t\t\tdata.d_Xs{i}(3) = mf;\n\t\t\t\tdata.ind_Xs{i}{3} = iK:iK+mf-1;\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{3}) = Gf;\n\t\t\t\tiK = iK+mf;\n\t\t\telse\n\t\t\t\t% last kernel for test!\n\t\t\t\tK = compute_cubic_spline_kernel(X(:,i),Xtrain(datatrain.Is{i},i));\n\t\t\t\tdata.d_Xs{i}(3) = datatrain.d_Xs{i}(3);\n\t\t\t\tdata.ind_Xs{i}{3} = datatrain.ind_Xs{i}{3};\n\t\t\t\tdata.Xs(:,data.ind_Xs{i}{3}) = K * inv( datatrain.Xs(datatrain.Is{i},data.ind_Xs{i}{3})' ) ;\n\t\t\t\tiK = iK+data.d_Xs{i}(3);\n\n\t\t\tend\n\t\tend\n\n\t\tdata.Xs(:,iK:end) = [];\n\nend\n\n\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/hkl-3.0/get_kernel_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6069052711459642}} {"text": " function [yik, scalefactor] = ir_mri_field_map_reg_scale(yik, etime, varargin)\n%function [yik, scalefactor] = ir_mri_field_map_reg_scale(yik, etime, varargin)\n%|\n%| Scale images to account for R2* effects and differences in absolute value\n%| using median(ri), where ri = sum_j sum_k |yik_j yik_k|^2 (t_k - t_j)^2\n%|\n%| in\n%|\tyik\t[N nset]\tscan images\n%|\tetime\t[1 nset]\techo times (units of sec if fieldmap is in Hz)\n%|\n%| option\n%|\tfmax\t\t\tthreshold for absolute yik value (default 0.1)\n%|\tdmax\t\t\tthreshold for absolute rj value (default 0.1)\n%|\tshow\t0|1\t\t1 to show result (default 0)\n%|\n%| out\n%|\tyik\t[N nset]\tscaled scan images\n%|\tscalefactor\t\tsqrt(median(rj)) * effect_of_fmax\n%|\n%| MJ Allison\n%| 2015-06-27 JF cosmetic changes\n\nif nargin < 4, ir_usage, end\n\narg.fmax = 0.1;\narg.dmax = 0.1;\narg.show = 0;\narg = vararg_pair(arg, varargin);\n\ndim_yik = size(yik);\nyik = reshapee(yik, [], dim_yik(end)); % [*N nset]\n\n[nn, nset] = size(yik);\n\n% Scale by median of first set of data to get rid of large mag_j\n% effects (not actually needed, but left in for consistency)\nif arg.fmax > 0\n\ty1 = abs(yik(:,1));\n\tscalefactor = median(y1(y1(:) > arg.fmax * max(y1(:))));\n\tif scalefactor == 0\n\t\tfail 'median is zero?'\n\tend\n\tyik = yik / scalefactor;\nelse\n\tscalefactor = 1;\nend\n\n\n% Try to compensate for R2 effects on effective regularization.\n\nd = zeros(nn,1);\nfor j = 1:nset\n\tfor k = 1:nset\n\t\ttmp = abs(yik(:,j) .* yik(:,k)).^2 * (etime(k)-etime(j)).^2;\n\t\td = d + tmp;\n\tend\nend\n\n% divide by numerator of wj^mn -> sum(abs(y)^2)\nd = div0(d, sum(abs(yik).^2,2));\n\nif arg.show\n\tim(reshape(d, [dim_yik(1:2)]))\nend\n\n% compute dtyp\ndtyp = median(d(d(:) > arg.dmax * max(d(:))));\n% pr dtyp\n\n% now uniformly scale by the square root of dtyp\nyik = yik / sqrt(dtyp);\n\nscalefactor = scalefactor * sqrt(dtyp); % 2022-11-27 fix\nyik = reshape(yik, dim_yik); % [(N) nset]\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/mri/fieldmap/ir_mri_field_map_reg_scale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6068640301072439}} {"text": "function [m,v,w,g,f,pp,gg]=gaussmix(x,c,l,m0,v0,w0,wx)\n%GAUSSMIX fits a gaussian mixture pdf to a set of data observations [m,v,w,g,f]=(x,c,l,m0,v0,w0,wx)\n%\n% Usage:\n% (1) [m,v,w]=gaussmix(x,[],[],k); % create GMM with k mixtures and diagonal covariances\n% (2) [m,v,w]=gaussmix(x,[],[],k,'v); % create GMM with k mixtures and full covariances\n%\n% Inputs: n data values, k mixtures, p parameters, l loops\n%\n% X(n,p) Input data vectors, one per row.\n% c(1) Minimum variance of normalized data (Use [] to take default value of 1/n^2)\n% L The integer portion of l gives a maximum loop count. The fractional portion gives\n% an optional stopping threshold. Iteration will cease if the increase in\n% log likelihood density per data point is less than this value. Thus l=10.001 will\n% stop after 10 iterations or when the increase in log likelihood falls below\n% 0.001.\n% As a special case, if L=0, then the first three outputs are omitted.\n% Use [] to take default value of 100.0001\n% M0 Number of mixtures required (or initial mixture means - see below)\n% V0 Initialization mode:\n% 'f' Initialize with K randomly selected data points [default]\n% 'p' Initialize with centroids and variances of random partitions\n% 'k' k-means algorithm ('kf' and 'kp' determine initialization)\n% 'h' k-harmonic means algorithm ('hf' and 'hp' determine initialization) [default]\n% 's' do not scale data during initialization to have equal variances\n% 'm' M0 contains the initial centres\n% 'v' full covariance matrices\n% Mode 'hf' [the default] generally gives the best results but 'f' is faster and often OK\n% W0(n,1) Data point weights\n%\n% Alternatively, initial values for M0, V0 and W0 can be given explicitly:\n%\n% M0(k,p) Initial mixture means, one row per mixture.\n% V0(k,p) Initial mixture variances, one row per mixture.\n% or V0(p,p,k) one full-covariance matrix per mixture\n% W0(k,1) Initial mixture weights, one per mixture. The weights should sum to unity.\n% WX(n,1) Data point weights\n%\n% Outputs: (Note that M, V and W are omitted if L==0)\n%\n% M(k,p) Mixture means, one row per mixture. (omitted if L==0)\n% V(k,p) Mixture variances, one row per mixture. (omitted if L==0)\n% or V(p,p,k) if full covariance matrices in use (i.e. either 'v' option or V0(p,p,k) specified)\n% W(k,1) Mixture weights, one per mixture. The weights will sum to unity. (omitted if L==0)\n% G Average log probability of the input data points.\n% F Fisher's Discriminant measures how well the data divides into classes.\n% It is the ratio of the between-mixture variance to the average mixture variance: a\n% high value means the classes (mixtures) are well separated.\n% PP(n,1) Log probability of each data point\n% GG(l+1,1) Average log probabilities at the beginning of each iteration and at the end\n%\n% The fitting procedure uses one of several initialization methods to create an initial guess\n% for the mixture centres and then uses the EM (expectation-maximization) algorithm to refine\n% the guess. Although the EM algorithm is deterministic, the initialization procedures use \n% random numbers and so the routine will not give identical answers if you call it multiple\n% times with the same input data.\n\n% Bugs/Suggestions\n% (1) Allow processing in chunks by outputting/reinputting an array of sufficient statistics\n% (2) Other initialization options:\n% 'l' LBG algorithm\n% 'm' Move-means (dog-rabbit) algorithm\n% (3) Allow updating of weights-only, not means/variances\n\n% Copyright (C) Mike Brookes 2000-2009\n% Version: $Id: gaussmix.m 7784 2016-04-15 11:09:50Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[n,p]=size(x);\nwn=ones(n,1);\nmx0=sum(x,1)/n; % calculate mean and variance of input data in each dimension\nvx0=sum(x.^2,1)/n-mx0.^2;\nsx0=sqrt(vx0);\nsx0(sx0==0)=1; % do not divide by zero when scaling\nscaled=0; % data is not yet scaled\nmemsize=voicebox('memsize'); % set memory size to use\nif isempty(c)\n c=1/n^2;\nelse\n c=c(1); % just to prevent legacy code failing\nend\nfulliv=0; % initial variance is not full\nif isempty(l)\n l=100+1e-4; % max loop count + stopping threshold\nend\nif nargin<5 || isempty(v0) || ischar(v0) % no initial values specified for m0, v0, w0\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % No initialvalues given, so we must use k-means or equivalent\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if nargin<6\n if nargin<5 || isempty(v0)\n v0='hf'; % default initialization mode: hf\n end\n wx=wn; % no data point weights\n else\n wx=w0(:); % data point weights\n end\n if any(v0=='m')\n k=size(m0,1);\n else\n k=m0;\n end\n fv=any(v0=='v'); % full covariance matrices requested\n if n<=k % each data point can have its own mixture\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale the data\n m=xs(mod((1:k)-1,n)+1,:); % just include all points several times\n v=zeros(k,p); % will be set to floor later\n w=zeros(k,1);\n w(1:n)=1/n;\n if l>0\n l=0.1; % no point in iterating\n end\n else % more points than mixtures\n if any(v0=='s')\n xs=x; % do not scale data during initialization\n else\n xs=(x-mx0(wn,:))./sx0(wn,:); % else scale now\n if any(v0=='m')\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % scale specified means as well\n end\n end\n w=repmat(1/k,k,1); % all mixtures equally likely\n if any(v0=='k') % k-means initialization\n if any(v0=='m')\n [m,e,j]=v_kmeans(xs,k,m);\n elseif any(v0=='p')\n [m,e,j]=v_kmeans(xs,k,'p');\n else\n [m,e,j]=v_kmeans(xs,k,'f');\n end\n elseif any(v0=='h') % k-harmonic means initialization\n if any(v0=='m')\n [m,e,j]=kmeanhar(xs,k,[],4,m);\n else\n if any(v0=='p')\n [m,e,j]=kmeanhar(xs,k,[],4,'p');\n else\n [m,e,j]=kmeanhar(xs,k,[],4,'f');\n end\n end\n elseif any(v0=='p') % Initialize using a random partition\n j=ceil(rand(n,1)*k); % allocate to random clusters\n j(rnsubset(k,n))=1:k; % but force at least one point per cluster\n for i=1:k\n m(i,:)=mean(xs(j==i,:),1);\n end\n else\n if any(v0=='m')\n m=m0; % use specified centres\n else\n m=xs(rnsubset(k,n),:); % Forgy initialization: sample k centres without replacement [default]\n end\n [e,j]=v_kmeans(xs,k,m,0); % find out the cluster allocation\n end\n if any(v0=='s')\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale data now if not done previously\n end\n v=zeros(k,p); % diagonal covariances\n w=zeros(k,1);\n for i=1:k\n ni=sum(j==i); % number assigned to this centre\n w(i)=(ni+1)/(n+k); % weight of this mixture\n if ni\n v(i,:)=sum((xs(j==i,:)-repmat(m(i,:),ni,1)).^2,1)/ni;\n else\n v(i,:)=zeros(1,p);\n end\n end\n end\nelse\n %%%%%%%%%%%%%%%%%%%%%%%%\n % use initial values given as input parameters\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n [k,p]=size(m0);\n xs=(x-mx0(wn,:))./sx0(wn,:); % scale the data\n m=(m0-mx0(ones(k,1),:))./sx0(ones(k,1),:); % and the means\n v=v0;\n w=w0;\n fv=ndims(v)>2 || size(v,1)>k; % full covariance matrix is supplied\n if fv\n mk=eye(p)==0; % off-diagonal elements\n fulliv=any(v(repmat(mk,[1 1 k]))~=0); % check if any are non-zero\n if ~fulliv\n v=reshape(v(repmat(~mk,[1 1 k])),p,k)'./repmat(sx0.^2,k,1); % just pick out and scale the diagonal elements for now\n else\n v=v./repmat(sx0'*sx0,[1 1 k]); % scale the full covariance matrix\n end\n end\n if nargin<7\n wx=wn; % no data point weights\n end\nend\nif length(wx)~=n\n error('%d datapoints but %d weights',n,length(wx));\nend\nlsx=sum(log(sx0));\nxsw=xs.*repmat(wx,1,p); % weighted data points\nnwt=sum(wx); % number of data points counting duplicates\nif ~fulliv % initializing with diagonal covariance\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Diagonal Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n v=max(v,c); % apply the lower bound\n xs2=xs.^2.*repmat(wx,1,p); % square and weight the data for variance calculations\n\n % If data size is large then do calculations in chunks\n\n nb=min(n,max(1,floor(memsize/(8*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n\n im=repmat(1:k,1,nb); im=im(:);\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n\n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n\n % EM loop\n\n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n for j=1:lp\n g1=g; % save previous log likelihood (2*pi factor omitted)\n m1=m; % save previous means, variances and weights\n v1=v;\n w1=w;\n vi=-0.5*v.^(-1); % data-independent scale factor in exponent\n lvm=log(w)-0.5*sum(log(v),2); % log of external scale factor (excluding -0.5*p*log(2pi) term)\n\n % first do partial chunk (of length jx0)\n\n jx=jx0;\n ii=1:jx; % indices of data points in this chunk\n kk=repmat(ii,k,1); % kk(jx,k): one row per data point, one column per mixture\n km=repmat(1:k,1,jx); % km(jx,k): one row per data point, one column per mixture\n py=reshape(sum((xs(kk(:),:)-m(km(:),:)).^2.*vi(km(:),:),2),k,jx)+lvm(:,wnj); % py(k,jx) pdf of each point with each mixture\n mx=max(py,[],1); % mx(1,jx) find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=px*wx(ii); % pk(k,1) effective number of data points for each mixture (could be zero due to underflow)\n sx=px*xsw(ii,:);\n sx2=px*xs2(ii,:);\n for il=2:nl % process the data points in chunks\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx; % indices of data points in this chunk\n kk=repmat(ii,k,1);\n py=reshape(sum((xs(kk(:),:)-m(im,:)).^2.*vi(im,:),2),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+px*wx(ii); % pk(k,1) effective number of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xsw(ii,:);\n sx2=sx2+px*xs2(ii,:);\n end\n g=lpx*wx; % total log probability summed over all data points\n gg(j)=g; % save log prob at each iteration\n w=pk/nwt; % normalize to get the weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp); % calculate mixture means\n v=sx2./pk(:,wp); % and variances\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); \t% number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=m;\n m(wm,:)=xs(mk(1:nz),:); \t% set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; \t% set these weights non-zero\n w=w*n/(n+nz); \t% normalize so the weights sum to unity\n wm=~wm; \t% mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wp);\n end\n v=max(v-m.^2,c); % apply floor to variances\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n\n end\n if sd && ~fv % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)/n-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n % gg' % *** DEBUG ***\n m=m1; % back up to previous iteration\n v=v1;\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/sum(v(:));\n end\n if ~fv\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:);\t% unscale means\n v=v.*repmat(sx0.^2,k,1); % and variances\n else\n v1=v;\n v=zeros(p,p,k);\n mk=eye(p)==1; % mask for diagonal elements\n v(repmat(mk,[1 1 k]))=v1'; % set from v1\n end\nend\nif fv % check if full covariance matrices were requested\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Full Covariance matrices %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n pl=p*(p+1)/2;\n lix=1:p^2;\n cix=repmat(1:p,p,1);\n rix=cix';\n lix(cix>rix)=[]; % index of lower triangular elements\n cix=cix(lix); % index of lower triangular columns\n rix=rix(lix); % index of lower triangular rows\n dix=find(rix==cix);\n lixi=zeros(p,p);\n lixi(lix)=1:pl;\n lixi=lixi';\n lixi(lix)=1:pl; % reverse index to build full matrices\n v=reshape(v,p^2,k);\n v=v(lix,:)'; % lower triangular in rows\n\n % If data size is large then do calculations in chunks\n\n nb=min(n,max(1,floor(memsize/(24*p*k)))); % chunk size for testing data points\n nl=ceil(n/nb); % number of chunks\n jx0=n-(nl-1)*nb; % size of first chunk\n %\n th=(l-floor(l))*n;\n sd=(nargout > 3*(l~=0)); % = 1 if we are outputting log likelihood values\n lp=floor(l)+sd; % extra loop needed to calculate final G value\n %\n lpx=zeros(1,n); % log probability of each data point\n wk=ones(k,1);\n wp=ones(1,p);\n wpl=ones(1,pl); % 1 index for lower triangular matrix\n wnb=ones(1,nb);\n wnj=ones(1,jx0);\n\n % EM loop\n\n g=0; % dummy initial value for comparison\n gg=zeros(lp+1,1);\n ss=sd; % initialize stopping count (0 or 1)\n vi=zeros(p*k,p); % stack of k inverse cov matrices each size p*p\n vim=zeros(p*k,1); \t% stack of k vectors of the form inv(v)*m\n mtk=vim; \t% stack of k vectors of the form m\n lvm=zeros(k,1);\n wpk=repmat((1:p)',k,1);\n for j=1:lp\n g1=g; \t% save previous log likelihood (2*pi factor omitted)\n m1=m; \t% save previous means, variances and weights\n v1=v;\n w1=w;\n for ik=1:k\n\n % these lines added for debugging only\n % vk=reshape(v(k,lixi),p,p);\n % condk(ik)=cond(vk);\n %%%%%%%%%%%%%%%%%%%%\n [uvk,dvk]=eig(reshape(v(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvalues\n dvk=max(diag(dvk),c); \t% apply variance floor to eigenvalues\n vik=-0.5*uvk*diag(dvk.^(-1))*uvk'; % calculate inverse\n vi((ik-1)*p+(1:p),:)=vik; % vi contains all mixture inverses stacked on top of each other\n vim((ik-1)*p+(1:p))=vik*m(ik,:)'; % vim contains vi*m for all mixtures stacked on top of each other\n mtk((ik-1)*p+(1:p))=m(ik,:)'; % mtk contains all mixture means stacked on top of each other\n lvm(ik)=log(w(ik))-0.5*sum(log(dvk)); % vm contains the weighted sqrt of det(vi) for each mixture\n end\n %\n % % first do partial chunk\n %\n jx=jx0;\n ii=1:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnj)).*(xii(wpk,:)-mtk(:,wnj)),p,jx*k),1),k,jx)+lvm(:,wnj);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=px*wx(ii); % effective number of data points for each mixture (could be zero due to underflow)\n sx=px*xsw(ii,:);\n sx2=px*(xsw(ii,rix).*xs(ii,cix));\t% accumulator for variance calculation (lower tri cov matrix as a row)\n for il=2:nl\n ix=jx+1;\n jx=jx+nb; % increment upper limit\n ii=ix:jx;\n xii=xs(ii,:).';\n py=reshape(sum(reshape((vi*xii-vim(:,wnb)).*(xii(wpk,:)-mtk(:,wnb)),p,nb*k),1),k,nb)+lvm(:,wnb);\n mx=max(py,[],1); % find normalizing factor for each data point to prevent underflow when using exp()\n px=exp(py-mx(wk,:)); % find normalized probability of each mixture for each datapoint\n ps=sum(px,1); % total normalized likelihood of each data point\n px=px./ps(wk,:); % relative mixture probabilities for each data point (columns sum to 1)\n lpx(ii)=log(ps)+mx;\n pk=pk+px*wx(ii); % effective number of data points for each mixture (could be zero due to underflow)\n sx=sx+px*xsw(ii,:); % accumulator for mean calculation\n sx2=sx2+px*(xsw(ii,rix).*xs(ii,cix));\t% accumulator for variance calculation\n end\n g=lpx*wx; % total log probability summed over all data points\n gg(j)=g; % save convergence history\n w=pk/nwt; \t% w(k,1) normalize to get the column of weights\n if pk % if all elements of pk are non-zero\n m=sx./pk(:,wp); % find mean and mean square\n v=sx2./pk(:,wpl);\n else\n wm=pk==0; % mask indicating mixtures with zero weights\n nz=sum(wm); % number of zero-weight mixtures\n [vv,mk]=sort(lpx); % find the lowest probability data points\n m=zeros(k,p); % initialize means and variances to zero (variances are floored later)\n v=zeros(k,pl);\n m(wm,:)=xs(mk(1:nz),:); % set zero-weight mixture means to worst-fitted data points\n w(wm)=1/n; % set these weights non-zero\n w=w*n/(n+nz); % normalize so the weights sum to unity\n wm=~wm; % mask for non-zero weights\n m(wm,:)=sx(wm,:)./pk(wm,wp); % recalculate means and variances for mixtures with a non-zero weight\n v(wm,:)=sx2(wm,:)./pk(wm,wpl);\n end\n v=v-m(:,cix).*m(:,rix); % subtract off mean squared\n if g-g1<=th && j>1\n if ~ss, break; end % stop\n ss=ss-1; % stop next time\n end\n end\n if sd % we need to calculate the final probabilities\n pp=lpx'-0.5*p*log(2*pi)-lsx; % log of total probability of each data point\n gg=gg(1:j)/nwt-0.5*p*log(2*pi)-lsx; % average log prob at each iteration\n g=gg(end);\n % gg' % *** DEBUG ONLY ***\n m=m1; % back up to previous iteration\n v=zeros(p,p,k); % reserve spave for k full covariance matrices\n trv=0; % sum of variance matrix traces\n for ik=1:k % loop for each mixture to apply variance floor\n [uvk,dvk]=eig(reshape(v1(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor to eigenvalues\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n trv=trv+sum(dvk); % add trace to the sum\n end\n w=w1;\n mm=sum(m,1)/k;\n f=(m(:)'*m(:)-k*mm(:)'*mm(:))/trv;\n else\n v1=v; % lower triangular form\n v=zeros(p,p,k); % reserve spave for k full covariance matrices\n for ik=1:k % loop for each mixture to apply variance floor\n [uvk,dvk,]=eig(reshape(v1(ik,lixi),p,p));\t% convert lower triangular to full and find eigenvectors\n dvk=max(diag(dvk),c); % apply variance floor\n v(:,:,ik)=uvk*diag(dvk)*uvk'; % reconstitute full matrix\n end\n end\n m=m.*sx0(ones(k,1),:)+mx0(ones(k,1),:); % unscale means\n v=v.*repmat(sx0'*sx0,[1 1 k]);\nend\nif l==0 % suppress the first three output arguments if l==0\n m=g;\n v=f;\n w=pp;\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/gaussmix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6068148466922807}} {"text": "function Xcq = cqt(x, B, fs, fmin, fmax, varargin)\n%CQT Constant-Q/Variable-Q transform\n% Usage: Xcq = cqt(x, B, fs, fmin, fmax, varargin)\n%\n% Input parameters:\n% x : input signal\n% B : number of bins per octave\n% fs : sampling frequency\n% fmin : lowest frequency to be analyzed\n% fmax : highest frequency to be analyzed\n% varargin : Optional input pairs (see table below)\n%\n% Output parameters: \n% Xcq : Struct consisting of \n% .c : CQT coefficients\n% .cDC : transform coefficients for f = 0\n% .cNyq : transform coefficients for fs/2\n% .g : cell array of analysis filters\n% .shift : center frequencies of analysis filters\n% .M : bandwidth of analysis filters\n% .xlen : length of input signal\n% .phasemode : 'local' -> zero-centered filtered used\n% : 'global' -> mapping function used\n% .rast : time-frequency plane sampling scheme (full,\n% piecewise, none)\n% .fmin\n% .fmax\n% .B \n% .format : eighter 'cell' or 'matrix' (only applies for\n% piecewise rasterization)\n% \n% Optional input arguments arguments can be supplied like this:\n%\n% Xcq = cqt(x, B, fs, fmin, fmax, 'rasterize', 'piecewise')\n%\n% The arguments must be character strings followed by an\n% argument:\n%\n% 'rasterize': can be set to (default is 'full');\n% - 'none': Hop sizes are distinct for each frequency\n% channel. Transform coefficients will be\n% presented in a cell array.\n% - 'full': The hop sizes for all freqency channels are \n% set to the smallest hop size in the representa-\n% tion. Transform coefficients will be presented \n% in matrix format.\n% - 'piecewise': Hop sizes will be rounded down to be a power-of-\n% two integer multiple of the smallest hop size in\n% the representation. Coefficients will be \n% presented either in a sparse matrix or as cell \n% arrays (see 'format' option)\n%\n% 'phasemode': can be set to (default is 'global')\n% - 'local': Zero-centered filtered used\n% - 'global': Mapping function used (see reference)\n%\n% 'format': applies only for piecewise rasterization \n% - 'sparse': Coefficients will be presented in a sparse matrix \n% - 'cell': Coefficients will be presented in a cell array\n%\n% 'gamma': the bandwidth of each filter is given by\n% Bk = 1/Q * fk + gamma,\n% where fk is the filters center frequency, Q is fully\n% determined by the number of bins per octave and gamma\n% is a bandwidth offset. If gamma = 0 the obtained\n% filterbank is constant-Q. Setting gamma > 0 time\n% resolution towards lower frequencies can be improved\n% compared to the constant-Q case (e.g. ERB proportional\n% bandwidths). See reference for more information.\n% 'normalize': coefficient normalization\n% - 'sine': Filters are scaled such that a sinusoid with\n% amplitude A in time domain will exhibit the same\n% amplitude in the time-frequency representation.\n% - 'impulse': Filters are scaled such that an impulse in time\n% domain will exhibit a flat response in the\n% time-frequency representation (in the frame that \n% centers the impulse)\n% - 'none': ...\n% 'winfun': defines the window function that is used for filter\n% design. See winfuns for more information.\n%\n% See also: nsgtf_real, winfuns\n%\n% References:\n% C. Sch�rkhuber, A. Klapuri, N. Holighaus, and M. D�rfler. A Matlab \n% Toolbox for Efficient Perfect Reconstruction log-f Time-Frequecy \n% Transforms.\n%\n% G. A. Velasco, N. Holighaus, M. D�rfler, and T. Grill. Constructing an\n% invertible constant-Q transform with non-stationary Gabor frames.\n% Proceedings of DAFX11, Paris, 2011.\n% \n% N. Holighaus, M. D�rfler, G. Velasco, and T. Grill. A framework for\n% invertible, real-time constant-q transforms. Audio, Speech, and\n% Language Processing, IEEE Transactions on, 21(4):775-785, April 2013.\n% \n%\n%\n% Copyright (C) 2013 Christian Sch�rkhuber.\n% \n% This work is licensed under the Creative Commons \n% Attribution-NonCommercial-ShareAlike 3.0 Unported \n% License. To view a copy of this license, visit \n% http://creativecommons.org/licenses/by-nc-sa/3.0/ \n% or send a letter to \n% Creative Commons, 444 Castro Street, Suite 900, \n% Mountain View, California, 94041, USA.\n\n% Authors: Christian Sch�rkhuber\n% Date: 20.09.13\n\n\n%% check input arguments\n\n%defaults\nrasterize = 'full'; %fully rasterized\nphasemode = 'global';\noutputFormat = 'sparse'; %only applies if rasterize == 'octave'\nnormalize = 'sine';\nwindowFct = 'hann';\ngamma = 0;\n\n\nif nargin >= 6\n Larg = length(varargin);\n for ii=1:2:Larg\n switch varargin{ii}\n case {'rasterize'}\n rasterize = varargin{ii+1};\n case {'phasemode'}\n phasemode = varargin{ii+1};\n case {'format'}\n outputFormat = varargin{ii+1};\n case {'gamma'}\n gamma = varargin{ii+1};\n case {'normalize'}\n normalize = varargin{ii+1};\n case {'win'}\n windowFct = varargin{ii+1};\n end\n end\nend\n \n\n%% window design\n[g,shift,M] = nsgcqwin(fmin,fmax,B,fs, length(x), ...\n 'winfun', windowFct, 'gamma', gamma, 'fractional', 0);\n fbas = fs*cumsum(shift(2:end))./ length(x);\n fbas = fbas(1:size(M,1)/2-1);\n \n\n%% compute coefficients\nbins = size(M,1)/2 - 1;\nswitch rasterize\n case 'full'\n M(2:bins+1) = M(bins+1);\n M(bins+3:end) = M(bins+1:-1:2);\n \n \n case 'piecewise'\n temp = M(bins+1);\n octs = ceil(log2(fmax/fmin));\n %make sure that the number of coefficients in the highest octave is\n %dividable by 2 at least octs-times\n temp = ceil(temp/2^octs)*2^octs; \n mtemp = temp./ M;\n mtemp = 2.^( ceil(log2(mtemp)) -1);\n mtemp = temp./ mtemp;\n mtemp(bins+2) = M(bins+2); %don't rasterize Nyquist bin\n mtemp(1) = M(1); %don't rasterize DC bin\n M = mtemp;\n \n otherwise\nend\n\nswitch normalize\n case {'sine','Sine','SINE','sin'}\n normFacVec = 2*M(1:bins+2)./length(x);\n case {'impulse','Impulse', 'IMPULSE','imp'}\n normFacVec = 2*M(1:bins+2)/cellfun(@length,g);\n case {'none','None','NONE','no'}\n normFacVec = ones(bins+2,1);\n otherwise\n error('Unkown normalization method!');\nend\n\nnormFacVec = [normFacVec; normFacVec(end-1:-1:2)];\ng = arrayfun(@(k) (g{k}*normFacVec(k)),1:(2*bins+2),'UniformOutput',0).'; \n\nc = nsgtf_real(x,g,shift,M,phasemode);\n\nswitch rasterize\n case 'full'\n cDC = cell2mat(c(1)).'; \n cNyq = cell2mat(c(bins+2)).';\n c = cell2mat(c(2:bins+1).');\n case 'piecewise'\n cDC = cell2mat(c(1)); \n cNyq = cell2mat(c(bins+2));\n if strcmp(outputFormat,'sparse')\n c = cqtCell2Sparse(c,M).';\n else\n c = c(2:end-1);\n end\n \n otherwise\n cDC = cell2mat(c(1)); \n cNyq = cell2mat(c(end));\n c = c(2:end-1);\nend\n\n\n%% output\nXcq = struct('c', {c.'}, 'g', {g}, 'shift', shift, 'M', {M}, ...\n 'xlen', length(x), 'phasemode', phasemode, 'rast', rasterize, ...\n 'fmin', fmin, 'fmax', fmax, 'B', B, 'cDC', cDC, 'cNyq', cNyq, ...\n 'format', outputFormat, 'fbas', fbas);\n\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/CQCC_v1.0/CQT_toolbox_2013/cqt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6068148388717048}} {"text": "function [Jul1,Jul2]=UTC2TT(Jul1,Jul2)\n%%UTC2TT Convert from universal coordinated time (UTC) given as a two-part\n% pseudo-Julian date to terrestrial time (TT), represented as a two-\n% part Julian date.\n%\n%INPUTS: Jul1, Jul2 Matrices of two parts of a pseudo-Julian date given in\n% UTC. The units of the date are days. The full date is\n% the sum of both terms. The date is broken into two\n% parts to provide more bits of precision. It does not\n% matter how the date is split. Corresponding elements in\n% each matrix are times that are converted.\n%\n%OUTPUTS: Jul1, Jul2 The time as a Julian date in TT with the same\n% dimensionalities as the input sets of dates.\n%\n%The UTC date is only pseudo-Julian, because there is not a fixed number\n%of seconds in a Julian day. The convention used in the IAU standard is\n%that the Julian day matches the UTC day regardless of whether the UTC day\n%is 86399, 86400 or 86401 SI seconds (depending on the presence of leap\n%seconds).\n%\n%UTC began at 1960 January 1.0 (JD 2436934.5) and this function should not\n%be called with an earlier date.\n%\n%This just calls a number of intermediate conversion functions out of the\n%International Astronomical Union's (IAU) Standard's of Fundamental\n%Astronomy library.\n%\n%Many temporal coordinate systems standards are compared in [1].\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"An Overview of Major Terrestrial, Celestial, and\n% Temporal Coordinate Systems for Target Tracking,\" Formal Report, Naval\n% Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173\n% pages.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n[Jul1,Jul2]=UTC2TAI(Jul1,Jul2);\n[Jul1,Jul2]=TAI2TT(Jul1,Jul2);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Coordinate_Systems/Time/UTC2TT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6067882209272497}} {"text": "function [H,Hnorm,inv_Hnorm] = compute_homography(m,M);\n\n%compute_homography\n%\n%[H,Hnorm,inv_Hnorm] = compute_homography(m,M)\n%\n%Computes the planar homography between the point coordinates on the plane (M) and the image\n%point coordinates (m).\n%\n%INPUT: m: homogeneous coordinates in the image plane (3xN matrix)\n% M: homogeneous coordinates in the plane in 3D (3xN matrix)\n%\n%OUTPUT: H: Homography matrix (3x3 homogeneous matrix)\n% Hnorm: Normalization matrix used on the points before homography computation\n% (useful for numerical stability is points in pixel coordinates)\n% inv_Hnorm: The inverse of Hnorm\n%\n%Definition: m ~ H*M where \"~\" means equal up to a non zero scalar factor.\n%\n%Method: First computes an initial guess for the homography through quasi-linear method.\n% Then, if the total number of points is larger than 4, optimize the solution by minimizing\n% the reprojection error (in the least squares sense).\n%\n%\n%Important functions called within that program:\n%\n%comp_distortion_oulu: Undistorts pixel coordinates.\n%\n%compute_homography.m: Computes the planar homography between points on the grid in 3D, and the image plane.\n%\n%project_points.m: Computes the 2D image projections of a set of 3D points, and also returns te Jacobian\n% matrix (derivative with respect to the intrinsic and extrinsic parameters).\n% This function is called within the minimization loop.\n\n\n\n\nNp = size(m,2);\n\nif size(m,1)<3,\n m = [m;ones(1,Np)];\nend;\n\nif size(M,1)<3,\n M = [M;ones(1,Np)];\nend;\n\n\nm = m ./ (ones(3,1)*m(3,:));\nM = M ./ (ones(3,1)*M(3,:));\n\n% Prenormalization of point coordinates (very important):\n% (Affine normalization)\n\nax = m(1,:);\nay = m(2,:);\n\nmxx = mean(ax);\nmyy = mean(ay);\nax = ax - mxx;\nay = ay - myy;\n\nscxx = mean(abs(ax));\nscyy = mean(abs(ay));\n\n\nHnorm = [1/scxx 0 -mxx/scxx;0 1/scyy -myy/scyy;0 0 1];\ninv_Hnorm = [scxx 0 mxx ; 0 scyy myy; 0 0 1];\n\nmn = Hnorm*m;\n\n% Compute the homography between m and mn:\n\n% Build the matrix:\n\nL = zeros(2*Np,9);\n\nL(1:2:2*Np,1:3) = M';\nL(2:2:2*Np,4:6) = M';\nL(1:2:2*Np,7:9) = -((ones(3,1)*mn(1,:)).* M)';\nL(2:2:2*Np,7:9) = -((ones(3,1)*mn(2,:)).* M)';\n\nif Np > 4,\n\tL = L'*L;\nend;\n\n[U,S,V] = svd(L);\n\nhh = V(:,9);\nhh = hh/hh(9);\n\nHrem = reshape(hh,3,3)';\n%Hrem = Hrem / Hrem(3,3);\n\n\n% Final homography:\n\nH = inv_Hnorm*Hrem;\n\nif 0,\n m2 = H*M;\n m2 = [m2(1,:)./m2(3,:) ; m2(2,:)./m2(3,:)];\n merr = m(1:2,:) - m2;\nend;\n\n%keyboard;\n \n%%% Homography refinement if there are more than 4 points:\n\nif Np > 4,\n \n % Final refinement:\n hhv = reshape(H',9,1);\n hhv = hhv(1:8);\n \n for iter=1:10,\n \n\n \n\t\tmrep = H * M;\n\n\t\tJ = zeros(2*Np,8);\n\n\t\tMMM = (M ./ (ones(3,1)*mrep(3,:)));\n\n\t\tJ(1:2:2*Np,1:3) = -MMM';\n\t\tJ(2:2:2*Np,4:6) = -MMM';\n\t\t\n\t\tmrep = mrep ./ (ones(3,1)*mrep(3,:));\n\n\t\tm_err = m(1:2,:) - mrep(1:2,:);\n\t\tm_err = m_err(:);\n\n\t\tMMM2 = (ones(3,1)*mrep(1,:)) .* MMM;\n\t\tMMM3 = (ones(3,1)*mrep(2,:)) .* MMM;\n\n\t\tJ(1:2:2*Np,7:8) = MMM2(1:2,:)';\n\t\tJ(2:2:2*Np,7:8) = MMM3(1:2,:)';\n\n\t\tMMM = (M ./ (ones(3,1)*mrep(3,:)))';\n\n\t\thh_innov = inv(J'*J)*J'*m_err;\n\n\t\thhv_up = hhv - hh_innov;\n\n\t\tH_up = reshape([hhv_up;1],3,3)';\n\n\t\t%norm(m_err)\n\t\t%norm(hh_innov)\n\n\t\thhv = hhv_up;\n H = H_up;\n \n end;\n \n\nend;\n\nif 0,\n m2 = H*M;\n m2 = [m2(1,:)./m2(3,:) ; m2(2,:)./m2(3,:)];\n merr = m(1:2,:) - m2;\nend;\n\nreturn;\n\n%test of Jacobian\n\nmrep = H*M;\nmrep = mrep ./ (ones(3,1)*mrep(3,:));\n\nm_err = mrep(1:2,:) - m(1:2,:);\nfigure(8);\nplot(m_err(1,:),m_err(2,:),'r+');\nstd(m_err')\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/compute_homography.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6067882047132294}} {"text": "function gcm = fmri_scm2gcm(X,Nnnc,TR,tPreStim,delta,tau)\n%\n% gcm = fmri_scm2gcm(X,Nnnc,TR,tPreStim,delta,tau)\n%\n% Produces a Gamma Convolution Matrix from a stimulus\n% convolution matrix (X) and parameters of the gamma\n% function (delta, tau). The gamma functions\n% are interpreted as basis vectors.\n%\n% $Id: fmri_scm2gcm.m,v 1.3 2005/06/01 01:04:52 sayres Exp $\n\n\n[Ntp Nch Nr] = size(X);\nNh = Nch/Nnnc;\nNg = length(delta);\n\nt = TR*[0:Nh-1] - tPreStim;\nh = fmri_hemodyn(t,delta,tau);\nh = h./(repmat(max(h),[Nh 1]));\n\nh_all = zeros(Nch,Nnnc*Ng);\nh0 = zeros(Nh,Nnnc*Ng);\nh0(1:Nh,1:Ng) = h;\nfor c = 1:Nnnc,\n r1 = Nh*(c-1)+1;\n r2 = r1 + Nh - 1;\n h_all(r1:r2,:) = fmri_shiftcol(h0,Ng*(c-1));\nend\n\ngcm = zeros(Ntp,Nnnc*Ng,Nr);\n\nfor r = 1:Nr,\n gcm(:,:,r) = X(:,:,r)*h_all;\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/mrBOLD/EventRelated/fmri_scm2gcm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.606737803594355}} {"text": "function [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)\n% Return global Volterra kernels for a MIMO Bilinear system\n% FORMAT [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)\n% A - (n x n) df(x(0),0)/dx - n states\n% B - (n x n x m) d2f(x(0),0)/dxdu - m inputs\n% C - (n x m) df(x(0),0)/du - d2f(x(0),0)/dxdu*x(0)\n% D - (n x 1) f(x(0).0) - df(x(0),0)/dx*x(0)\n% x0 - (n x 1) x(0)\n% N - kernel depth {intervals}\n% dt - interval {seconds}\n%\n% Volterra kernels:\n%\n% H0 - (n) = h0(t) = y(t)\n% H1 - (N x n x m) = h1i(t,s1) = dy(t)/dui(t - s1)\n% H2 - (N x N x n x m x m) = h2ij(t,s1,s2) = d2y(t)/dui(t - s1)duj(t - s2)\n%\n% where n = p if modes are specified\n%\n%--------------------------------------------------------------------------\n% Returns Volterra kernels for bilinear systems of the form\n%\n% dx/dt = f(x,u) = A*x + B1*x*u1 + ... Bm*x*um + C1u1 + ... Cmum + D\n% y(t) = x(t)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston \n% $Id: spm_bilinear.m 5219 2013-01-29 17:07:07Z spm $\n\n\n% Volterra kernels for bilinear systems\n%==========================================================================\n\n% parameters\n%--------------------------------------------------------------------------\nn = size(A,1); % state variables\nm = size(C,2); % inputs\nA = full(A);\nB = full(B);\nC = full(C);\nD = full(D);\n\n% eignvector solution {to reduce M0 to leading diagonal form}\n%-------------------------------------------------------------------------\nM0 = [0 zeros(1,n); D A];\n[U,J] = eig(M0);\nV = pinv(U);\n\n% Lie operator {M0}\n%--------------------------------------------------------------------------\nM0 = sparse(J);\nX0 = V*[1; x0];\n\n% 0th order kernel\n%--------------------------------------------------------------------------\nH0 = ex(N*dt*M0)*X0;\n\n% 1st order kernel\n%--------------------------------------------------------------------------\nif nargout > 1\n\n % Lie operator {M1}\n %----------------------------------------------------------------------\n for i = 1:m\n M1(:,:,i) = V*[0 zeros(1,n); C(:,i) B(:,:,i)]*U;\n end\n\n % 1st order kernel\n %----------------------------------------------------------------------\n H1 = zeros(N,n + 1,m);\n for p = 1:m\n for i = 1:N\n u1 = N - i + 1;\n H1(u1,:,p) = ex(u1*dt*M0)*M1(:,:,p)*ex(-u1*dt*M0)*H0;\n end\n end\nend\n\n% 2nd order kernels\n%--------------------------------------------------------------------------\nif nargout > 2\n H2 = zeros(N,N,n + 1,m,m);\n for p = 1:m\n for q = 1:m\n for j = 1:N\n u2 = N - j + 1;\n u1 = N - [1:j] + 1;\n H = ex(u2*dt*M0)*M1(:,:,q)*ex(-u2*dt*M0)*H1(u1,:,p)';\n H2(u2,u1,:,q,p) = H';\n H2(u1,u2,:,p,q) = H';\n end\n end\n end\nend\n\n% project to state space and remove kernels associated with the constant \n%--------------------------------------------------------------------------\nif nargout > 0\n H0 = real(U*H0);\n H0 = H0([1:n] + 1);\nend\nif nargout > 1\n for p = 1:m\n H1(:,:,p) = real(H1(:,:,p)*U.');\n end\n H1 = H1(:,[1:n] + 1,:);\nend\nif nargout > 1\n for p = 1:m\n for q = 1:m\n for j = 1:N\n H2(j,:,:,p,q) = real(squeeze(H2(j,:,:,p,q))*U.');\n end\n end\n end\n H2 = H2(:,:,[1:n] + 1,:,:);\nend\n\nreturn\n\n\n% matrix exponential function (for diagonal matrices)\n%==========================================================================\nfunction y = ex(x)\nn = length(x);\ny = spdiags(exp(diag(x)),0,n,n);\nreturn\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_bilinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6067167242234017}} {"text": "function [M, RHS, Mx, My, Mz, RHSx, RHSy, RHSz] = convectionTvdTerm(u, phi, FL)\n% This function uses the TVD scheme to discretize a\n% convection term in the form $\\grad (u \\phi)$ where u is a face vactor\n% It also returns the x, y, x parts of the matrix of coefficient.\n%\n% SYNOPSIS:\n% [M, RHS, Mx, My, Mz, RHSx, RHSy, RHSz] = convectionTvdTerm(u, phi, FL)\n%\n% PARAMETERS:\n% u - velocity vector, FaceVariable\n% phi - value of phi from the previous time step or iteration, CellVariable\n% FL - Flux Limiter function\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\nMz=[];\nd = u.domain.dimension;\nswitch d\n case 1\n [M, RHS] = convectionTvdTerm1D(u, phi, FL);\n case 1.5\n [M, RHS] = convectionTvdTermCylindrical1D(u, phi, FL);\n case 1.8\n [M, RHS] = convectionTvdTermSpherical1D(u, phi, FL);\n case 2\n [M, RHS, Mx, My, RHSx, RHSy] = convectionTvdTerm2D(u, phi, FL);\n case 2.5\n [M, RHS, Mx, My, RHSx, RHSy] = convectionTvdTermCylindrical2D(u, phi, FL);\n case 2.8\n [M, RHS, Mx, My, RHSx, RHSy] = ...\n convectionTvdTermRadial2D(u, phi, FL);\n case 3\n [M, RHS, Mx, My, Mz, RHSx, RHSy, RHSz] = convectionTvdTerm3D(u, phi, FL);\n case 3.2\n [M, RHS, Mx, My, Mz, RHSx, RHSy, RHSz] = ...\n convectionTvdTermCylindrical3D(u, phi, FL);\nend\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Discretization/convectionTvdTerm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6066434120989896}} {"text": "function [solution, modelOut] = entropicFluxBalanceAnalysis(model, param)\n%% TBC\n% minimize g.*vf'*(log(vf) -1) + (cf + ci)'*vf \n% vf,vr,w,x,x0 + g.*vr'*(log(vr) -1) + (cr - ci)'*vr\n% + f.*x' *(log(x) -1) + u0'*x \n% + f.*x0'*(log(x0) -1) + u0'*x0\n% + ce'*w\n% + (1/2)v'*Q*v\n% + (1/2)(v-h)'*H*(v-h)\n%\n% subject to [N B]*[v w] <=> b : y_N\n% subject to N*(vf - vr) + B*w = x - x0 = dx/dt \n%\n% subject to N*(vf - vr) - x + x0 <=> b : y_N\n% C*(vf - vr) <=> d : y_C\n% lb <= [vf - vr; w] <= ub : y_v\n% dxl <= x - x0 <= dxu : z_dx\n% vfl <= vf <= vfu : z_vf\n% vrl <= vr <= vru : z_vr\n% xl <= x <= xu : z_x\n% x0l <= x0 <= x0u : z_x0\n%\n% with Biochemical optimality conditions\n% || N*(vf - vr) - x + x0 - b ||_inf\n% || C*(vf - vr) - d ||_inf\n% || g*log(vf) + ci + cf + N'*y_N + C'*y_C + y_v + z_vf ||_inf\n% || g*log(vr) - ci + cr - N'*y_N - C'*y_C - y_vi + z_vr ||_inf\n% || f.*log(x) + u0 - y_N + z_dx - z_x ||_inf\n% || f.*log(x0) + u0 + y_N - z_dx + z_x0 ||_inf\n%\n% with Derived biochemical optimality conditions (fluxes)\n% || g*log(vr/vf) + cr - cf - 2*(ci + N'*y_N + C'*y_C + y_vi) + z_vr - z_vf ||_inf\n%\n% with Derived biochemical optimality conditions (concentrations)\n% || f.*log(x/x0) - 2*y_N + 2*z_dx + z_x - z_x0 ||_inf\n% || f.*log(x.*x0) + 2*u0 + z_x + z_x0 ||_inf\n%\n% Derived biochemical optimality conditions (fluxes and concentrations)\n% || g*log(vf) + cf + ci + N'*(u0 + log(x) + z_dx + z_x) + C'*y_C + y_vi + z_vf ||_inf\n% || g*log(vr) + cr - ci - N'*(u0 + log(x) + z_dx + z_x) - C'*y_C - y_vi + z_vr ||_inf\n%\n% Derived biochemical optimality conditions (fluxes and concentrations, combining forward and reverse)\n% || g*log(vr/vf) + cr - cf - 2*(ci + N'*(u0 + f*log(x) + z_dx + z_x) + C'*y_C + y_vi) - z_vf + z_vr ||_inf\n% || g*log(vr/vf) + cr - cf - 2*(ci - N'*(u0 + f*log(x0) - z_dx + z_x0) + C'*y_C + y_vi) - z_vf + z_vr ||_inf\n%\n% If (but not only if) the input data is as follows:\n% g = 2, f = 1, cr = cf, ci = 0,\n% C = 0, d = 0, <=> y_C = 0\n% vl = -inf, vu = inf <=> y_v = 0\n% dxl = -inf, dxu = inf, <=> z_dx = 0\n% ub = inf, <=> z_vf = 0\n% lb = - inf, <=> z_vr = 0\n% x0l = -inf, x0u = inf, <=> z_x0 = 0\n% then the above reduces to\n% || log(vr/vf) = N'*(u0 + log(x) + z_x) ||_inf\n% where z_x is the dual variable to the bounds on concentration x.\n%\n% USAGE:\n%\n% [solution, modelOut] = entropicFluxBalanceAnalysis(model,param)\n%\n% INPUT:\n% model: (the following fields are required - others can be supplied)\n%\n% * S - `m x (n + k)` Stoichiometric matrix\n% * c - `(n + k) x 1` Linear objective coefficients\n% * lb - `(n + k) x 1` Lower bounds on net flux\n% * ub - `(n + k) x 1` Upper bounds on net flux\n%\n% OPTIONAL INPUTS:\n% model.osenseStr: Maximize ('max')/minimize ('min') (opt, default = 'max') linear part of the objective. \n% Nonlinear parts of the objective are always assumed to be minimised.\n%\n% model.b `m x 1` change in concentration with time\n% model.csense `m x 1` character array with entries in {L,E,G}\n%\n% model.C: `c x (n + k)` Left hand side of C*v <= d\n% model.d: `c x (n + k)` Right hand side of C*v <= d\n% model.dsense `c x 1` character array with entries in {L,E,G}\n%\n% model.g n x 1 strictly positive weight on internal flux entropy maximisation (default 2)\n% model.cf: n x 1 real valued linear objective coefficients on internal forward flux (default 0)\n% model.cr: n x 1 real valued linear objective coefficients on internal reverse flux (default 0)\n% model.vfl: n x 1 non-negative lower bound on internal forward flux (default 0) \n% model.vfu: n x 1 non-negative upper bound on internal forward flux (default inf) \n% model.vrl: n x 1 non-negative lower bound on internal reverse flux (default 0) \n% model.vru: n x 1 non-negative upper bound on internal reverse flux (default 0) \n%\n% model.f: m x 1 strictly positive weight on concentration entropy maximisation (default 1)\n% model.u0: m x 1 real valued linear objective coefficients on concentrations (default 0) \n% model.x0l: m x 1 non-negative lower bound on initial molecular concentrations \n% model.x0u: m x 1 non-negative upper bound on initial molecular concentrations\n% model.xl: m x 1 non-negative lower bound on final molecular concentrations \n% model.xu: m x 1 non-negative lower bound on final molecular concentrations\n% model.dxl: m x 1 real valued lower bound on difference between final and initial molecular concentrations \n% model.dxu: m x 1 real valued upper bound on difference between final and initial initial molecular concentrations \n% \n% model.Q (n + k) x (n + k) positive semi-definite matrix to minimise (1/2)v'*Q*v\n%\n% model.SConsistentMetBool: m x 1 boolean indicating stoichiometrically consistent metabolites\n% model.SConsistentRxnBool: n x 1 boolean indicating stoichiometrically consistent metabolites\n%\n% param.solver: {('pdco'),'mosek'}\n% param.method: {('fluxes'),'fluxesConcentrations','fluxTracer')} maximise entropy of fluxes or also concentrations\n% param.printLevel: {(0),1}\n%\n%\n% Parameters related with flux optimisation\n% param.maxUnidirectionalFlux: scalar real valued maximum expected value of unidirectional flux\n% param.internalNetFluxBounds: 'original' (default) maintains direction and magnitude of net flux from model.lb & model.ub\n% 'directional' maintains direction of net flux from model.lb & model.ub but not magnitude\n% 'random' random net flux direction, replacing constraints from model.lb & model.ub\n%\n% Parameters related with concentration optimisation:\n% param.maxConc: scalar maximum permitted metabolite concentration\n% param.externalNetFluxBounds:\n%\n% model.gasConstant: scalar gas constant (default 8.31446261815324 J K^-1 mol^-1)\n% model.T: scalar temperature (default 310.15 Kelvin)\n%\n%\n% OUTPUTS:\n% solution: solution structure with the following fields\n%\n% *.v: n x 1 double net flux\n% *.vf: n x 1 double unidirectional forward internal reaction flux\n% *.vr: n x 1 double unidirectional reverse internal reaction flux\n% *.vt: scalar total internal reaction flux sum(vf + vr)\n% *.y_N: m × 1 double dual variable to steady state constraints\n% *.y_C: z × 1 double dual variable to coupling constraints\n% *.y_vi: n x 1 double dual variable to box constraints on internal net flux\n% *.z_v: (n + k) x 1 double dual variable to box constraints on net flux\n% *.z_vf: n x 1 double dual variable to box constraints on forward flux\n% *.z_vr: n x 1 double dual variable to box constraints on reverse flux\n% *.time: solve time\n% *.stat: COBRA toolbox standard solution status\n% *.origStat: solution status as provided by the solver\n%\n% modelOut: solved model with optional input fields populated by defaults, if they were not provided \n% \n% EXAMPLE:\n%\n% NOTE:\n%\n% Author(s): Ronan M.T. Fleming 2021\n \n%%\nif ~exist('param','var')\n param = struct();\nend\nif ~isfield(param,'printLevel')\n param.printLevel=1;\nend\nif ~isfield(param,'debug')\n param.debug=false;\nend\nif ~isfield(param,'solver')\n param.solver='mosek';\nend\nif ~isfield(param,'method')\n param.method='fluxes';\nend\n\nif ~isfield(model,'osenseStr') || isempty(model.osenseStr)\n %default linear objective sense is maximisation\n model.osenseStr = 'max';\nend\n[~,osense] = getObjectiveSense(model);\n\nif ~isfield(model, 'csense')\n % if csense is not declared in the model, assume that all\n % constraints are equalities.\n model.csense(1:size(model.S, 1), 1)='E';\nend\n\nif ~isfield(model, 'b')\n model.b = zeros(size(model.S, 1), 1);\nend\n\nif isfield(model,'C') && ~isfield(model,'d')\n error('model.C present but model.d missing in C*v <=> d')\nend\n\n%find the maximal set of metabolites and reactions that are stoichiometrically consistent\nif ~isfield(model,'SConsistentMetBool') || ~isfield(model,'SConsistentRxnBool')\n massBalanceCheck=0;\n [~, ~, ~, ~, ~, ~, model, ~] = findStoichConsistentSubset(model, massBalanceCheck, param.printLevel-1);\nend\nif 0\n %find the maximal set of metabolites and reactions that are flux consistent\n if ~isfield(model,'fluxConsistentMetBool') || ~isfield(model,'fluxConsistentRxnBool')\n findFluxConsistentSubset.z_x0= 1e-6;\n [fluxConsistentMetBool, fluxConsistentRxnBool, fluxInConsistentMetBool, fluxInConsistentRxnBool, model, fluxConsistModel] = findFluxConsistentSubset(model, param, param.printLevel)\n end\n %only use that part of model.S which is stoichiometrically and flux\n %consistent\n N=model.S(model.SConsistentMetBool & fluxConsistentMetBool,model.SConsistentRxnBool & fluxConsistentRxnBool);\nend\n\nif any(~model.SConsistentMetBool) || 0\n error(['model.S is incorrectly specified as it contains ' int2str(nnz(~model.SConsistentMetBool)) ' stoichiometrically inconsistent metabolites'])\nend\n\nN = model.S(:,model.SConsistentRxnBool);\nB = model.S(:,~model.SConsistentRxnBool);\n\n[m,n] = size(N); % number of metabolities & internal reactions\n[~,k] = size(B); % number of external reactions\n\n%% processing for fluxes\nprocessFluxConstraints\n\n%% optionally processing for concentrations\nprocessConcConstraints\n\n%matrices for padding\nOmn = sparse(m,n);\nOnm = sparse(n,m);\nOnk=sparse(n,k);\nOm=sparse(m,m);\nOmk=sparse(m,k);\nOn1 = sparse(n,1);\nO1n = sparse(1,n);\nO1k=sparse(1,k);\nOm1 = sparse(m,1);\n\nIm = speye(m);\nIn = speye(n);\nI1n = ones(1,n);\ne = ones(n,1);\n\nif isfield(model,'C')\n C = model.C(:,model.SConsistentRxnBool);\n nConstr = size(model.C,1);\n Ocn = sparse(nConstr,n);\n Ocm = sparse(nConstr,m);\n D = model.C(:,~model.SConsistentRxnBool);\nelse\n C = [];\nend\n\n\nif isfield(model,'H')\n Hi = model.H(:,model.SConsistentRxnBool);\n if any(any(Hi))\n error('model.H corresponding to internal reactions is ignored')\n end\n bool = ~model.SConsistentRxnBool & ~isnan(model.h);\n h = model.h(bool);\n H = model.H(bool,bool);\n nH=nnz(bool);\n Och = sparse(nConstr,nH);\n Ohn = sparse(nH,n);\n Ih = speye(nH);\n Ihk = speye(n+k);\n Ihk = Ihk(bool,~model.SConsistentRxnBool);\n Omh = sparse(m,nH);\n Onh = sparse(n,nH);\nend\n\nswitch param.method\n case {'fluxConc','fluxConcNorm'}\n switch param.solver\n case 'pdco'\n %constraint matrix\n if isfield(model,'C')\n EPproblem.A =...\n [ N, -N, Omn, -Im, Im, Om;\n In, -In, -In, Onm, Onm, Onm;\n Omn, Omn, Omn, Im, -Im, -Im;\n C, -C, Ocn, Ocm, Ocm, Ocm];\n % vf vr v x x0 dx\n EPproblem.b = [model.b;zeros(n+m,1);model.d];\n \n EPproblem.csense(1:m,1)=model.csense;\n EPproblem.csense(m+1:m+n,1)='E';\n EPproblem.csense(m+n+1:2*m+n,1)='E';\n EPproblem.csense(2*m+n+1:2*m+n+nConstr,1) = model.dsense;\n else\n EPproblem.A = ... \n [ N, -N, Omn, -Im, Im, Om;\n In, -In, -In, Onm, Onm, Onm;\n Omn, Omn, Omn, Im, -Im, -Im];\n % vf vr v x x0 dx\n EPproblem.b = [model.b;zeros(n+m,1)];\n EPproblem.csense(1:m,1)=model.csense;\n EPproblem.csense(m+1:m+n,1)='E';\n EPproblem.csense(m+n+1:2*m+n,1)='E';\n end\n \n \n EPproblem.c =...\n [ci + cf;\n -ci + cr;\n zeros(n,1);\n u0;\n u0;\n zeros(m,1)];\n EPproblem.osense = 1; %minimise\n \n %bounds\n EPproblem.lb = [vfl;vrl;vl;model.xl;model.x0l;model.dxl];\n EPproblem.ub = [vfu;vru;vu;model.xu;model.x0u;model.dxu];\n \n if any(EPproblem.lb > EPproblem.ub)\n if any(vfl>vfu)\n error('vfl>vfu, i.e. lower bound on dx cannot be greater than upper bound')\n end\n if any(vrl>vru)\n error('vrl>vru, i.e. lower bound on dx cannot be greater than upper bound')\n end\n if any(vl>vu)\n error('vl>vu, i.e. lower bound on dx cannot be greater than upper bound')\n end\n if any(model.xl>model.xu)\n error('model.xl>model.xu i.e. lower bound on dx cannot be greater than upper bound')\n end\n if any(model.x0l>model.x0u)\n error('model.x0l>model.x0u i.e. lower bound on dx cannot be greater than upper bound')\n end\n if any(model.dxl>model.dxu)\n bool = (model.dxl~=0 | model.dxu~=0) & model.dxl>model.dxu;\n T=table(model.dxl(bool),model.dxu(bool));\n disp(T)\n error('model.dxl>model.dxu i.e. lower bound on dx cannot be greater than upper bound')\n end\n end\n %variables for entropy maximisation\n EPproblem.d=[g;g;zeros(n,1);f;f;zeros(m,1)];\n \n \n solution = solveCobraEP(EPproblem,param);\n \n if param.printLevel>1\n fprintf('%8.2g %s\\n',norm(EPproblem.A*solution.full + solution.slack - EPproblem.b,inf),'|| A*x + s - b ||_inf')\n end\n \n y_N = solution.dual(1:m);%Already Rockafellar signs\n y_vi = solution.dual(m+1:m+n);\n z_dx = solution.dual(m+n+1:2*m+n);\n if isfield(model,'C')\n y_C = solution.dual(2*m+n+1:2*m+n+nConstr);\n end\n %fluxes\n vf = solution.full(1:n);\n vr = solution.full(n+1:2*n);\n v = solution.full(2*n+1:3*n);\n x = solution.full(3*n+1:3*n+m);\n x0 = solution.full(3*n+m+1:3*n+2*m);\n dx = solution.full(3*n+2*m+1:3*n+3*m);\n \n ve = -B'*(x - x0);\n \n % duals to bounds on unidirectional fluxes\n z_vf = solution.rcost(1:n,1);\n z_vr = solution.rcost(n+1:2*n,1);\n % duals to bounds on net fluxes\n z_vi = solution.rcost(2*n+1:3*n,1);\n %dual to bounds on concentration\n z_x = solution.rcost(3*n+1:3*n+m,1);\n z_x0 = solution.rcost(3*n+m+1:3*n+2*m,1);\n %dual to bounds on change in concentration\n eta2 = solution.rcost(3*n+2*m+1:3*n+3*m,1);\n \n %extra checks\n if param.printLevel>0\n fprintf('%s\\n','Primal optimality conditions')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) - x + x0 - model.b,inf),'|| N*(vf - vr) - x + x0 - b ||_inf');\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - model.b,inf),'|| N*(vf - vr) + B*ve - b ||_inf');\n fprintf('%8.2g %s\\n',norm(vf - vr - v,inf),'|| vf - vr - v ||_inf');\n fprintf('%8.2g %s\\n',norm(x - x0 - dx,inf),'|| x - x0 - dx ||_inf');\n if isfield(model,'C')\n \n end\n fprintf('%s\\n','Dual optimality conditions (fluxes)')\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + ci + cf + N'*y_N + C'*y_C + y_vi + z_vf,inf), '|| g.*log(vf) + ci + cf + N''*y_N + C''*y_C + y_vi + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) - ci + cr - N'*y_N - C'*y_C - y_vi + z_vr,inf),'|| g.*log(vr) - ci + cr - N''*y_N - C''*y_C - y_vi + z_vr ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + ci + cf + N'*y_N + y_vi + z_vf,inf), '|| g.*log(vf) + ci + cf + N''*y_N + y_vi + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) - ci + cr - N'*y_N - y_vi + z_vr,inf),'|| g.*log(vr) - ci + cr - N''*y_N - y_vi + z_vr ||_inf');\n end\n fprintf('%8.2g %s\\n',norm(-y_vi + z_vi,inf),'|| - y_vi + zeta2 ||_inf');\n fprintf('%s\\n','Dual optimality conditions (concentrations)')\n fprintf('%8.2g %s\\n',norm(f.*reallog(x) + u0 - y_N + z_dx + z_x,inf), '|| f.*log(x) + u0 - y_N + z_dx + z_x ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x0) + u0 + y_N - z_dx + z_x0,inf),'|| f.*log(x0) + u0 + y_N - z_dx + z_x0 ||_inf');\n fprintf('%8.2g %s\\n',norm(-z_dx + eta2,inf),'|| - z_dx + eta2 ||_inf');\n \n \n fprintf('\\n%s\\n','Thermo conditions (fluxes)')\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) - N'*y_N - C'*y_C,inf),'|| log(vr./vf) - N''*y_N - C''*y_C ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N - 2*C'*y_C,inf),'|| d.*log(vr./vf) - 2*N''*y_N - 2*C''*y_C ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vf + z_vr,inf),'|| g.*log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi - z_vf + z_vr ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) - N'*y_N,inf),'|| log(vr./vf) - N''*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N,inf),'|| d.*log(vr./vf) - 2*N''*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi,inf),'|| g.*log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi + z_vf - z_vr,inf),'|| g.*log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi + z_vf - z_vr ||_inf');\n end\n \n fprintf('%s\\n','Effects of internal bounds on fluxes')\n fprintf('%8.2g %s\\n',norm(y_vi,inf),'|| y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(z_vf,inf),'|| z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(z_vr,inf),'|| z_vr ||_inf');\n\n \n fprintf('\\n%s\\n','Thermo conditions (concentrations)')\n fprintf('%8.2g %s\\n',norm(f.*reallog(x./x0) - 2*y_N + 2*z_dx + z_x - z_x0,inf),'|| f.*log(x/x0) - 2*y_N + 2*z_dx + z_x - z_x0 ||_inf');\n \n fprintf('%s\\n','Effects of internal bounds on concentrations')\n fprintf('%8.2g %s\\n',norm(z_dx,inf),'|| z_dx ||_inf');\n fprintf('%8.2g %s\\n',norm(z_x,inf),'|| z_x ||_inf');\n fprintf('%8.2g %s\\n',norm(z_x0,inf),'|| z_x0 ||_inf'); \n pause(0.001)\n \n if isfield(model,'C')\n fprintf('\\n%s\\n','Effects of coupling constraints on fluxes')\n fprintf('%8.2g %s\\n',norm(y_C,inf),'|| y_C ||_inf');\n end\n d1=solution.d1;\n d2=solution.d2;\n fprintf('\\n%s\\n','Optimality conditions (regularised)')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) - x + x0 - model.b - (d2^2)*y_N,inf),'|| N*(vf - vr) + B*ve - b - (d2^2)*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(vf - vr - v - (d2^2)*y_vi,inf),'|| vf - vr - v - (d2^2)*y_vi ||_inf');\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + N'*y_N + C'*y_C + y_vi + z_vf - (d1^2)*vf,inf), '|| g.*log(vf) + cf + N''*y_N + C''*y_C + y_vi - z_vf - (d1^2)*vf||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - N'*y_N - C'*y_C - y_vi + z_vr - (d1^2)*vr,inf), '|| g.*log(vr) + cr - N''*y_N - C''*y_C - y_vi - z_vr - (d1^2)*vr||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + N'*y_N + y_vi + z_vf - (d1^2)*vf,inf), '|| g.*log(vf) + cf + N''*y_N + y_vi - z_vf - (d1^2)*vf||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - N'*y_N - y_vi + z_vr - (d1^2)*vr,inf), '|| g.*log(vr) + cr - N''*y_N - y_vi - z_vr - (d1^2)*vr||_inf');\n end\n fprintf('%8.2g %s\\n',norm(f.*reallog(x) + u0 - y_N + z_dx + z_x - (d1^2)*x,inf), '|| f.*log(x) + u0 - y_N + z_dx - z_x - (d1^2)*x ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x0) + u0 + y_N - z_dx + z_x0 - (d1^2)*x0,inf),'|| f.*log(x0) + u0 + y_N + z_dx + z_x0 - (d1^2)*x0 ||_inf');\n \n fprintf('\\n%s\\n','Thermo conditions (regularised)')\n fprintf('%8.2g %s\\n',norm((d1^2)*(vr - vf),inf),'|| (d1^2)*(vr - vf) ||_inf');\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vf + z_vr - (d1^2)*(vr -vf),inf),'|| g.*log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi - z_vf + z_vr - (d1^2)*(vr -vf) ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi + z_vf - z_vr + (d1^2)*(vr -vf),inf),'|| g.*log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi + z_vf - z_vr + (d1^2)*(vr -vf) ||_inf');\n end\n fprintf('%8.2g %s\\n',norm((d1^2)*(x - x0),inf),'|| (d1^2)*(x - x0) ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x./x0) - 2*y_N + 2*z_dx + z_x - z_x0 + (d1^2)*(x - x0),inf),'|| f.*log(x/x0) - 2*y_N + 2*z_dx + z_x - z_x0 + (d1^2)*(x - x0) ||_inf');\n \n end\n \n case 'mosek'\n %%\n % https://docs.mosek.com/modeling-cookbook/expo.html\n % min (d.*x)'*(log(x./y) + c)\n % s.t. l <= A[x;y] <= u\n %\n % where d,c,A,l,u are data and x,y are variables, is equivalent to\n %\n % min d*t + d*c*x\n % s.t. t >= x*log(x/y)\n % l <= A[x;y] <= u\n %\n % which is equivalent to:\n %\n % min d*t + d*c*x\n % s.t. (y, x, -t) \\in K_{exp}\n % l <= A[x;y] <= u\n %\n % Such a problem could be formulated using the Affine conic constraints, as shown in the following code:\n \n %B=B*0;\n \n %constraint matrix\n if isfield(model,'C') \n EPproblem.A = [ ...\n N, -N, B, -Im, Im;\n In, -In, Onk, Onm, Onm;\n Omn, Omn, Omk, Im, -Im;\n C, -C, D, Ocm, Ocm];\n % vf, vr, w, x, x0\n EPproblem.blc = [model.b;vl;model.dxl;model.d];\n EPproblem.buc = [model.b;vu;model.dxu;model.d];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n csense(2*m+n+1:2*m+n+nConstr,1) = model.dsense;\n else\n EPproblem.A =...\n [N, -N, B, -Im, Im;\n In, -In, Onk, Onm, Onm;\n Omn, Omn, Omk, Im, -Im];\n % vf, vr, w, x, x0\n EPproblem.blc = [model.b;vl;model.dxl];\n EPproblem.buc = [model.b;vu;model.dxu];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n end\n \n EPproblem.buc(csense == 'G') = inf;\n EPproblem.blc(csense == 'L') = -inf;\n \n if strcmp(param.method,'fluxConcNorm')\n EPproblem.c =...\n [ci + cf;\n -ci + cr;\n ce;\n u0;\n u0];\n else\n EPproblem.c =...\n [ci + cf - g;\n -ci + cr - g;\n ce;\n u0 - f;\n u0 - f];\n end\n EPproblem.osense = 1; %minimise\n \n %bounds\n EPproblem.lb = [vfl;vrl;vel;model.xl;model.x0l];\n EPproblem.ub = [vfu;vru;veu;model.xu;model.x0u];\n \n %variables for entropy maximisation\n % vf, vr, w, x, x0\n EPproblem.d=[g; g; zeros(k,1); f; f];\n \n if strcmp(param.method,'fluxConcNorm')\n P = sparse(3,size(EPproblem.A,2));\n P(1,1:2*n)=1; % normalisation of forward + reverse fluxes\n P(2,2*n+k+1:2*n+k+m)=1; % normalisation of concentration\n P(3,2*n+k+m+1:2*n+k+2*m)=1; %normalisation of initial concentration\n EPproblem.P = P;\n pBool=(sum(EPproblem.P,1)~=0)'; %identify normalised variables\n [p,~] = size(EPproblem.P);\n EPproblem.sumFluxes = 2*(sum(model.x0u)+1e-6);\n EPproblem.sumConc = sum(model.x0u)+1e-6;\n EPproblem.sumConc0 = sum(model.x0u)+1e-6;\n else\n P = zeros(3,size(EPproblem.A,2));\n pBool = false(size(EPproblem.A,2),1);\n p = 0;\n EPproblem.sumFluxes = [];\n EPproblem.sumConc = [];\n EPproblem.sumConc0 = [];\n end\n q = any(EPproblem.d & ~pBool)+0;\n \n solution = solveCobraEP(EPproblem,param);\n \n if solution.stat~=1\n nInfLB = nnz(~isfinite(EPproblem.lb));\n nInfUB = nnz(~isfinite(EPproblem.ub));\n disp([int2str(nInfLB) ' non-finite lower bounds'])\n disp([int2str(nInfUB) ' non-finite upper bounds'])\n disp(['solution.stat = ' num2str(solution.stat)])\n disp(['solution.origStat = ' solution.origStat])\n error('solveCobraEP did not solve')\n end\n \n % Primal variables\n % vf, vr, ve, x , x0\n vf = solution.full(1:n);\n vr = solution.full(n+1:2*n);\n ve = solution.full(2*n+1:2*n+k);\n x = solution.full(2*n+k+1:2*n+k+m);\n x0 = solution.full(2*n+k+m+1:2*n+k+2*m);\n \n % Primal normalisation variables\n if q\n t_1 = 0;\n else\n t_1 = solution.auxPrimal(1);\n end\n if strcmp(param.method,'fluxConcNorm')\n t_vfvr = solution.auxPrimal(q+1);\n t_x = solution.auxPrimal(q+2);\n t_x0 = solution.auxPrimal(q+3);\n else\n t_vfvr = 1;\n t_x = 1;\n t_x0 = 1;\n end\n \n %slack variable\n slack = solution.slack;\n \n %% Dual variables corresponding to constraints\n % dual to steady state constraints\n y_N = solution.dual(1:m); \n %dual to bounds on net flux\n y_vi = solution.dual(m+1:m+n); \n %dual to bounds on change in concentration\n z_dx = solution.dual(m+n+1:2*m+n); \n %dual to coupling constraints\n if isfield(model,'C')\n y_C = solution.dual(2*m+n+1:2*m+n+nConstr);\n end\n %dual to normalisation constraints\n if strcmp(param.method,'fluxConcNorm')\n y_vt = solution.dualNorm(1);\n y_xt = solution.dualNorm(2);\n y_x0t = solution.dualNorm(3);\n else\n y_vt = -g; %cancel out \n y_xt = -f;\n y_x0t = -f;\n end\n \n % Primal auxiliary variables of affine conic constraints\n e_vf = solution.auxPrimal(q+p+1:q+p+n);\n e_vr = solution.auxPrimal(q+p+n+1:q+p+2*n);\n e_x = solution.auxPrimal(q+p+2*n+1:q+p+2*n+m);\n e_x0 = solution.auxPrimal(q+p+2*n+m+1:q+p+2*n+2*m);\n \n % Dual variables to affine conic constraints\n y_K = solution.coneDual;\n \n % Dual to affine conic constraints reordered by F matrix\n Fty_K = solution.coneF'*y_K; %Rockafeller signs\n k_vf = Fty_K(1:n);\n k_vr = Fty_K(n+1:2*n);\n k_ve = Fty_K(2*n+1:2*n+k);\n k_x = Fty_K(2*n+k+1:2*n+k+m);\n k_x0 = Fty_K(2*n+k+m+1:2*n+k+2*m);\n if q\n k_e_1 = Fty_K(2*n+k+2*m+1);\n else\n k_e_1 = 0; \n end\n if strcmp(param.method,'fluxConcNorm')\n k_vt = Fty_K(q+2*n+k+2*m+1);\n k_xt = Fty_K(q+2*n+k+2*m+2);\n k_x0t = Fty_K(q+2*n+k+2*m+3);\n end\n k_e_vf = Fty_K(q+2*n+k+2*m+p+1:q+3*n+k+2*m+p);\n k_e_vr = Fty_K(q+3*n+k+2*m+p+1:q+4*n+k+2*m+p);\n k_tx = Fty_K(q+4*n+k+2*m+p+1:q+4*n+k+3*m+p);\n k_tx0 = Fty_K(q+4*n+k+3*m+p+1:q+4*n+k+4*m+p);\n \n \n % duals to bounds on forward unidirectional fluxes\n z_vf = solution.rcost(1:n,1);\n % duals to bounds on reverse unidirectional fluxes\n z_vr = solution.rcost(n+1:2*n,1);\n %duals to bounds on final concentration\n z_x = solution.rcost(2*n+k+1:2*n+k+m,1);\n %duals to bounds on initial concentration\n z_x0 = solution.rcost(2*n+k+m+1:2*n+k+2*m,1);\n \n if strcmp(param.method,'fluxConcNorm')\n %dual to bounds on total forward and reverse flux\n z_vt = solution.rcost(2*n+k+2*m+1);\n %dual to bounds on total concentration\n z_xt = solution.rcost(2*n+k+2*m+2);\n %dual to bounds on total initial concentration\n z_x0t = solution.rcost(2*n+k+2*m+3);\n % else\n % z_vt = 0;\n % z_xt = 0;\n % z_x0t =0;\n end\n % Dual variables corresponding to bounds on auxiliary variables.\n if q\n z_t = solution.auxRcost(1); % 1\n else\n z_t = 0; \n end\n z_t_f = solution.auxRcost(q+1:q+n); % tf\n z_t_r = solution.auxRcost(q+n+1:q+2*n); % tr\n z_t_x = solution.auxRcost(q+2*n+1:q+2*n+m); % tx\n z_t_x0 = solution.auxRcost(q+2*n+m+1:q+2*n+2*m); % tx0\n \n % Tf = table(reallog(vf/vt), 1,cf,N'*y_N,e*z_dx,z_vf,wvf)\n % Tf = table(reallog(vr/vt), 1,cr,N'*y_N,e*z_dx,z_vr,wvr)\n % T = table(reallog(vf/vt),cf,N'*y_N)\n \n %extra checks\n if param.printLevel>0\n fprintf('\\n%s\\n','Optimality conditions (biochemistry)')\n %primal\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - x + x0 - model.b,inf),'|| N*(vf - vr) + B*ve - x + x0 - b ||_inf');\n %dual\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(k_vf + cf + ci + N'*y_N + C'*y_C + y_vi - z_vf + y_vt,inf), '|| k_vf - g + cf + ci + N''*y_N + C''*y_C + y_vi - z_vf + y_vt ||_inf');\n fprintf('%8.2g %s\\n',norm(k_vr + cr - ci - N'*y_N - C'*y_C - y_vi - z_vr + y_vt,inf), '|| k_vr - g + cr - ci - N''*y_N - C''*y_C - y_vi - z_vr + y_vt ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(k_vf + cf + ci + N'*y_N + y_vi - z_vf + y_vt,inf), '|| k_vf - g + cf + ci + N''*y_N + y_vi - z_vf + y_vt ||_inf');\n fprintf('%8.2g %s\\n',norm(k_vr + cr - ci - N'*y_N - y_vi - z_vr + y_vt,inf), '|| k_vr - g + cr - ci - N''*y_N - y_vi - z_vr + y_vt ||_inf');\n end\n fprintf('%8.2g %s\\n',norm(k_x + u0 - y_N + z_dx + z_x + y_xt,inf), '|| k_x + u0 - y_N + z_dx + z_x + y_xt ||_inf');\n fprintf('%8.2g %s\\n',norm(k_x0 + u0 + y_N - z_dx + z_x0 + y_x0t,inf),'|| k_x0 + u0 + y_N - z_dx + z_x0 + y_x0t ||_inf');\n \n if strcmp(param.method,'fluxConcNorm')\n fprintf('%8.2g %s\\n',norm(k_vt - y_vt + z_vt,inf),'|| k_vt - y_vt + z_vt ||_inf');\n fprintf('%8.2g %s\\n',norm(k_xt - y_xt + z_xt,inf),'|| k_xt - y_xt + z_xt ||_inf');\n fprintf('%8.2g %s\\n',norm(k_x0t - y_x0t + z_x0t,inf),'|| k_x0t - y_x0t + z_x0t ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(k_e_1 + z_t,inf),'|| k_1 + z_t ||_inf');\n end\n \n fprintf('%8.2g %s\\n',norm(k_e_vf - g - z_t_f,inf),'|| k_e_vf - g - z_t_f ||_inf');\n fprintf('%8.2g %s\\n',norm(k_e_vr - g - z_t_r,inf),'|| k_e_vr - g - z_t_r ||_inf');\n fprintf('%8.2g %s\\n',norm(k_tx - f - z_t_x,inf),'|| k_tx - f - z_t_x ||_inf');\n fprintf('%8.2g %s\\n',norm(k_tx0 - f - z_t_x0,inf),'|| k_tx0 - f - z_t_x0 ||_inf');\n \n fprintf('%8.2g %s\\n',norm(e_vf + vf.*reallog(vf./t_vfvr),inf), '|| t_f + vf*log(vf/(1''*(vf + vr))) ||_inf');\n fprintf('%8.2g %s\\n',norm(e_vr + vr.*reallog(vr./t_vfvr),inf), '|| t_r + vr*log(vr/(1''*(vf + vr))) ||_inf');\n fprintf('%8.2g %s\\n',norm(e_x + x.*reallog( x./t_x),inf), '|| t_x + x*log(x/(1''*x)) ||_inf');\n fprintf('%8.2g %s\\n',norm(e_x0 + x0.*reallog(x0./t_x0),inf), '|| t_x0 + x0*log(x0/(1''*x0)) ||_inf');\n \n fprintf('\\n%s\\n','Derived optimality conditions (fluxes)')\n if param.printLevel>1\n fprintf('%8.2g %s\\n',norm(k_vf - g.*reallog(vf./t_vfvr) - g,inf), '|| k_vf - g.*log(vf) - g ||_inf');\n fprintf('%8.2g %s\\n',norm(k_vr - g.*reallog(vr./t_vfvr) - g,inf), '|| k_vr - g.*log(vr) - g ||_inf');\n end\n \n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf./t_vfvr) + cf + ci + N'*y_N + C'*y_C + y_vi - z_vf,inf), '|| g.*log(vf) + cf + ci + N''*y_N + C''*y_C + y_vi - z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./t_vfvr) + cr - ci - N'*y_N - C'*y_C - y_vi - z_vr,inf),'|| g.*log(vr) + cr - ci - N''*y_N - C''*y_C - y_vi - z_vr ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf./t_vfvr) + cf + ci + N'*y_N + y_vi + - z_vf,inf), '|| g.*log(vf) + cf + ci + N''*y_N - z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./t_vfvr) + cr - ci - N'*y_N - y_vi + - z_vr,inf),'|| g.*log(vr) + cr - ci - N''*y_N + - z_vr ||_inf');\n end\n \n fprintf('\\n%s\\n','Effects of internal bounds on net fluxes')\n fprintf('%8.2g %s\\n',norm(y_vi,inf),'|| y_vi ||_inf');\n fprintf('\\n%s\\n','Effects of internal bounds on forward fluxes')\n fprintf('%8.2g %s\\n',norm(z_vf,inf),'|| z_vf ||_inf');\n fprintf('\\n%s\\n','Effects of internal bounds on reverse fluxes')\n fprintf('%8.2g %s\\n',norm(z_vr,inf),'|| z_vr ||_inf');\n \n \n fprintf('\\n%s\\n','Derived optimality conditions (concentrations)')\n if param.printLevel>1\n fprintf('%8.2g %s\\n',norm(k_x - f.*reallog(x./t_x) - f,inf), '|| sx - f.*log( x/ (1''*x)) - f ||_inf');\n fprintf('%8.2g %s\\n',norm(k_x0 - f.*reallog(x0./t_x0) - f,inf), '|| sx0 - f.*log(x0/(1''*x0)) - f ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x./t_x) + f + u0 - y_N + z_dx + z_x + y_xt,inf), '|| f.*log(x/(1''*x)) + f + u0 - y_N + z_dx + z_x + y_vt ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x0./t_x0) + f + u0 + y_N - z_dx + z_x0 + y_x0t,inf),'|| f.*log(x0/(1''*x0)) + f + u0 + y_N - z_dx + z_x0 + y_xt ||_inf');\n \n end\n fprintf('%8.2g %s\\n',norm(f.*reallog(x./t_x) + u0 - y_N + z_dx + z_x,inf), '|| f.*log(x/(1''*x)) + u0 - y_N + z_dx + z_x ||_inf');\n fprintf('%8.2g %s\\n',norm(f.*reallog(x0./t_x0) + u0 + y_N - z_dx + z_x0,inf),'|| f.*log(x0/(1''*x0)) + u0 + y_N - z_dx + z_x0 ||_inf');\n \n fprintf('\\n%s\\n','Thermo conditions (fluxes)')\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N - 2*C'*y_C,inf),'|| g.*log(vr/vf) - 2*N''*y_N - 2*C''*y_C ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*C''*y_C - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vr + z_vf,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*C''*y_C - 2*y_vi - z_vr + z_vf ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N,inf),'|| g.*log(vr/vf) - 2*N''*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*y_vi,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*y_vi - z_vr + z_vf,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*y_vi - z_vr + z_vf ||_inf');\n end\n \n fprintf('\\n%s\\n','Thermo conditions (concentrations)')\n if strcmp(param.method,'fluxConcNorm')\n fprintf('%8.2g %s\\n',norm(f.*reallog(x./t_x) - f.*reallog(x0./t_x0) - 2*y_N + 2*z_dx + z_x - z_x0 + y_xt - y_x0t,inf),'|| f.*(log(x/(1''*x)) - log(x0/(1''*x0))) - 2*y_N + 2*z_dx + z_x - z_x0 + y_xt - y_x0t ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(f.*reallog(x) - f.*reallog(x0) - 2*y_N + 2*z_dx + z_x - z_x0,inf),'|| f.*(log(x/x0)) - 2*y_N + 2*z_dx + z_x - z_x0 ||_inf');\n end\n \n fprintf('\\n%s\\n','Effects of internal bounds on change in concentrations')\n fprintf('%8.2g %s\\n',norm(z_dx,inf),'|| z_dx ||_inf');\n fprintf('\\n%s\\n','Effects of internal bounds on concentrations')\n fprintf('%8.2g %s\\n',norm(z_x,inf),'|| z_x ||_inf');\n fprintf('\\n%s\\n','Effects of internal bounds on initial concentrations')\n fprintf('%8.2g %s\\n',norm(z_x0,inf),'|| z_x0 ||_inf');\n \n if isfield(model,'C')\n fprintf('\\n%s\\n','Effects of coupling constraints on fluxes')\n fprintf('%8.2g %s\\n',norm(y_C,inf),'|| y_C ||_inf');\n end\n \n fprintf('%8.2g %s\\n',min(slack(slack~=0)), 'min(slack)');\n fprintf('%8.2g %s\\n',max(slack(slack~=0)), 'max(slack)');\n end\n \n \n switch param.externalNetFluxBounds\n case 'dxReplacement'\n ve = model.S(:,~model.SConsistentRxnBool)\\(x-x0);\n pause(0.1)\n end\n end\n case 'fluxes'\n switch param.solver\n case 'pdco'\n %constraint matrix\n if isfield(model,'C')\n EPproblem.A =[...\n N, -N, Omn, B;\n In, -In, -In, Onk;\n C, -C, Ocn, D];\n % vf vr v w\n EPproblem.b = [model.b;zeros(n,1);model.d];\n EPproblem.csense(1:length(EPproblem.b),1)='E';\n EPproblem.csense(1:m,1)=model.csense;\n EPproblem.csense(m+n+1:m+n+nConstr,1) = model.dsense;\n else\n EPproblem.A = ...\n [N, -N, Omn, B;\n In, -In, -In, Onk];\n % vf vr v w\n EPproblem.b = [model.b;zeros(n,1)];\n EPproblem.csense(1:length(EPproblem.b),1)='E';\n EPproblem.csense(1:m,1)=model.csense;\n end\n \n if isfield(model,'Q')\n EPproblem.Q = sparse(size(EPproblem.A,2),size(EPproblem.A,2));\n Qv = model.Q(model.SConsistentRxnBool,model.SConsistentRxnBool);\n EPproblem.Q(2*n+1:3*n,2*n+1:3*n) = Qv;\n Qve = model.Q(~model.SConsistentRxnBool,~model.SConsistentRxnBool);\n EPproblem.Q(3*n+1:3*n+k,3*n+1:3*n+k) = Qve;\n else\n Qv = sparse(n,n);\n Qve = sparse(k,k);\n end\n \n EPproblem.c =...\n [ci + cf; %ci already includes sign for minimisation or maximisation\n -ci + cr;\n zeros(n,1);\n ce];\n EPproblem.osense = 1; %minimise\n \n %bounds\n EPproblem.lb = [vfl;vrl;vl;vel];\n EPproblem.ub = [vfu;vru;vu;veu];\n \n %variables for entropy maximisation\n EPproblem.d=zeros(size(EPproblem.A,2),1);\n EPproblem.d(1:2*n)=[g;g];\n \n solution = solveCobraEP(EPproblem,param);\n if 0\n save('infeasibleEPproblem.mat','EPproblem','model')\n return\n end\n \n switch solution.stat\n case 1\n y_N = solution.dual(1:m);%Already Rockafellar signs\n y_vi = solution.dual(m+1:m+n);\n \n if isfield(model,'C')\n y_C = solution.dual(m+n+1:m+n+nConstr);\n CtYC = ' + C''y_C';\n mCtYC = ' - C''y_C';\n CtYC2 = ' + 2*C''y_C';\n mCtYC2 = ' - 2*C''y_C';\n else\n C = sparse(0,n);\n y_C = sparse(0);\n CtYC = '';\n mCtYC = '';\n CtYC2 = '';\n mCtYC2 = '';\n end\n \n if isfield(model,'Q')\n Qdotv = ' + Q*v ';\n %mQdotv = ' - Q*v ';\n Qdotve = ' + Q*ve ';\n else\n Qdotv = '';\n Qdotve = ''; \n end\n \n %fluxes\n vf = solution.full(1:n);\n vr = solution.full(n+1:2*n);\n v = solution.full(2*n+1:3*n);\n ve = solution.full(3*n+1:3*n+k);\n \n %slacks\n s = solution.slack;\n s_N = s(1:m,1);\n if any(s_N)\n sN = '+ s_N';\n else\n sN = '';\n end\n s_c = s(m+1:m+n,1);\n if any(s_c)\n sc = '+ s_c';\n else\n sc = '';\n end\n if isfield(model,'C')\n s_C = s(m+n+1:m+n+nConstr,1);\n else\n s_C = sparse(1,0);\n end\n \n % duals to bounds on unidirectional fluxes\n z_vf = solution.rcost(1:n,1);\n z_vr = solution.rcost(n+1:2*n,1);\n % duals to bounds on internal net fluxes\n z_vi = solution.rcost(2*n+1:3*n,1);\n % duals to bounds on external net fluxes\n z_ve = solution.rcost(3*n+1:3*n+k,1);\n\n %extra checks\n if param.printLevel>1 || param.debug\n fprintf('%s\\n','Optimality conditions (unregularised)')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve + s_N - model.b,inf),['|| N*(vf - vr) + B*ve ' sN ' - b ||_inf']);\n fprintf('%8.2g %s\\n',norm(vf - vr - v + s_c,inf),['|| vf - vr - v ' sc '||_inf']);\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(C*(vf - vr) + s_C - model.d,inf),'|| C*(vf - vr) + s_C - d ||_inf, sC = slack variable');\n end\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + ci + N'*y_N + C'*y_C + Qv*v + y_vi + z_vf,inf), ['|| g.*log(vf) + g + cf + ci + N''*y_N' CtYC Qdotv ' + y_vi + z_vf ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - ci - N'*y_N - C'*y_C + Qv*v - y_vi + z_vr,inf),['|| g.*log(vr) + g + cr - ci - N''*y_N' mCtYC Qdotv ' - y_vi + z_vr ||_inf']);\n fprintf('%8.2g %s\\n',norm(ce + B'*y_N + Qve*ve + z_ve,inf),['|| ce + B''*y_N ' Qdotve ' + z_ve ||_inf']);\n\n d1=solution.d1;\n d2=solution.d2;\n fprintf('\\n%s\\n','Optimality conditions (regularised)')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - model.b + (d2^2)*y_N,inf),'|| N*(vf - vr) + B*ve - b + (d2^2)*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(vf - vr - v + (d2^2)*y_vi,inf),'|| vf - vr - v + (d2^2)*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + ci + N'*y_N + C'*y_C + Qv*v + y_vi + z_vf + (d1^2)*vf,inf), ['|| g.*log(vf) + g + cf + ci + N''*y_N' CtYC2 Qdotv ' + y_vi + z_vf + (d1^2)*vf ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - ci - N'*y_N - C'*y_C + Qv*v - y_vi + z_vr + (d1^2)*vr,inf), ['|| g.*log(vr) + g + cr - ci - N''*y_N' mCtYC2 Qdotv ' - y_vi + z_vr + (d1^2)*vr ||_inf']);\n fprintf('%8.2g %s\\n',norm(ce + B'*y_N + Qve*ve + z_ve + (d1^2)*ve,inf),['|| ce + B''*y_N ' Qdotve ' + z_ve + (d1^2)*ve ||_inf']);\n\n fprintf('\\n%s\\n','Thermo conditions (unregularised)')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vf + z_vr,inf),['|| g.*log(vr./vf) + cr - cf - 2*ci - 2*N''*y_N' mCtYC2 ' - 2*y_vi + z_vf - z_vr ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi,inf),['|| g.*log(vr./vf) + cr - cf - 2*ci - 2*N''*y_N' mCtYC2 ' - 2*y_vi ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*ci - 2*N'*y_N,inf),'|| g.*log(vr./vf) - 2*ci - 2*N''*y_N ||_inf');\n \n fprintf('\\n%s\\n','Thermo conditions (regularised)')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vf + z_vr + (d1^2)*(vr -vf),inf),['|| g.*log(vr./vf) + cr - cf -2*ci - 2*N''*y_N' mCtYC2 ' - 2*y_vi - z_vf + z_vr + (d1^2)*(vr -vf) ||_inf']);\n fprintf('%8.2g %s\\n',norm(z_vf - z_vr + (d1^2)*(vr -vf),inf),'|| z_vf - z_vr + (d1^2)*(vr -vf) ||_inf');\n\n fprintf('\\n%s\\n','Effects of internal bounds')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + ci + N'*y_N + C'*y_C + Qv*v + y_vi + z_vf,inf), ['|| g.*log(vf) + g + cf + ci + N''*y_N' CtYC Qdotv ' + y_vi + z_vf ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - ci - N'*y_N - C'*y_C + Qv*v - y_vi + z_vr,inf),['|| g.*log(vr) + g + cr - ci - N''*y_N' mCtYC Qdotv ' - y_vi + z_vr ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vf) + cf + ci + N'*y_N + C'*y_C + Qv*v + y_vi ,inf), ['|| g.*log(vf) + g + cf + ci + N''*y_N' CtYC Qdotv ' + y_vi ||_inf']);\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr) + cr - ci - N'*y_N - C'*y_C + Qv*v - y_vi ,inf),['|| g.*log(vr) + g + cr - ci - N''*y_N' mCtYC Qdotv ' - y_vi ||_inf']);\n fprintf('%8.2g %s\\n',norm(z_vf,inf),'|| z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(z_vr,inf),'|| z_vr ||_inf');\n fprintf('%8.2g %s\\n',norm(z_vi,inf),'|| z_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(y_vi,inf),'|| y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(- y_vi + z_vi,inf),'|| -y_vi + z_vi||_inf');\n \n fprintf('\\n%s\\n','Effects of external bounds')\n fprintf('%8.2g %s\\n',norm(ce + B'*y_N + Qve*ve + z_ve,inf),['|| ce + B''*y_N ' Qdotve ' + z_ve ||_inf']);\n fprintf('%8.2g %s\\n',norm(z_ve,inf),'|| z_ve ||_inf');\n\n end\n end\n case 'mosek'\n %%\n % https://docs.mosek.com/modeling-cookbook/expo.html\n % min (d.*x)'*(log(x./y) + c)\n % s.t. l <= A[x;y] <= u\n %\n % where d,c,A,l,u are data and x,y are variables, is equivalent to\n %\n % min d*t + d*c*x\n % s.t. t >= x*log(x/y)\n % l <= A[x;y] <= u\n %\n % which is equivalent to:\n %\n % min d*t + d*c*x\n % s.t. (y, x, -t) \\in K_{exp}\n % l <= A[x;y] <= u\n %\n % Such a problem could be formulated using the Affine conic constraints, as shown in the following code:\n \n if isfield(model,'H') && isfield(model,'h')\n if isfield(model,'C') && isfield(model,'d')\n EPproblem.A =...\n [N, -N, B, Omh;\n In, -In, Onk, Onh;\n C, -C, D, Och;\n Ohn, Ohn, Ihk, -Ih];\n % vf vr w dw\n EPproblem.blc = [model.b;vl;model.d;h];\n EPproblem.buc = [model.b;vu;model.d;h];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n csense(m+n+1:m+n+nConstr,1) = model.dsense;\n else\n EPproblem.A = ...\n [N, -N, B, Omk;\n In, -In, Onk, Onk;\n Ohn, Ohn, Ik, -Ik];\n % vf vr w dw\n EPproblem.blc = [model.b;vl;h];\n EPproblem.buc = [model.b;vu;h];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n end\n else\n %constraint matrix\n if isfield(model,'C') && isfield(model,'d')\n EPproblem.A =...\n [N, -N, B;\n In, -In, Onk;\n C, -C, D];\n % vf vr w\n EPproblem.blc = [model.b;vl;model.d];\n EPproblem.buc = [model.b;vu;model.d];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n csense(m+n+1:m+n+nConstr,1) = model.dsense;\n else\n EPproblem.A = ...\n [N, -N, B;\n In, -In, Onk];\n % vf vr w\n EPproblem.blc = [model.b;vl];\n EPproblem.buc = [model.b;vu];\n csense(1:size(EPproblem.A,1),1)='E';\n csense(1:m,1)=model.csense;\n end\n end\n \n if isfield(model,'H') && isfield(model,'h')\n EPproblem.Q = sparse(size(EPproblem.A,2),size(EPproblem.A,2));\n %minimise Euclidean deviation from h\n EPproblem.Q(2*n+k+1:2*n+k+nH,2*n+k+1:2*n+k+nH) = H;\n if isfield(model,'Q')\n Qv = model.Q(model.SConsistentRxnBool,model.SConsistentRxnBool);\n EPproblem.Q(1:n,1:n)=Qv; %TODO - this minimises sum of vf + vr rather than difference\n EPproblem.Q(n+1:2*n,n+1:2*n)=Qv;\n Qve = model.Q(~model.SConsistentRxnBool,~model.SConsistentRxnBool);\n EPproblem.Q(2*n+1:2*n+k,2*n+1:2*n+k)=Qve;\n end\n quadRows = any(EPproblem.Q,2);\n quadCols = any(EPproblem.Q,1)';\n quadBool = quadRows | quadCols;\n nQuadCone = nnz(quadBool);\n else\n if isfield(model,'Q')\n EPproblem.Q = sparse(size(EPproblem.A,2),size(EPproblem.A,2));\n Qv = model.Q(model.SConsistentRxnBool,model.SConsistentRxnBool);\n EPproblem.Q(1:n,1:n)=Qv;\n EPproblem.Q(n+1:2*n,n+1:2*n)=Qv;\n Qve = model.Q(~model.SConsistentRxnBool,~model.SConsistentRxnBool);\n EPproblem.Q(2*n+1:2*n+k,2*n+1:2*n+k)=Qve;\n \n quadRows = any(EPproblem.Q,2);\n quadCols = any(EPproblem.Q,1)';\n quadBool = quadRows | quadCols;\n nQuadCone = nnz(quadBool);\n else\n Qv = sparse(n,n);\n Qve = sparse(k,k);\n nQuadCone = 0;\n end\n end\n %%\n EPproblem.sumFluxes = [];\n EPproblem.sumConc = [];\n EPproblem.sumConc0 = [];\n \n EPproblem.buc(csense == 'G') = inf;\n EPproblem.blc(csense == 'L') = -inf;\n \n if isfield(model,'H') && isfield(model,'h')\n EPproblem.c =...\n [ci + cf;\n -ci + cr;\n ce;\n zeros(nH,1)];\n %bounds\n EPproblem.lb = [vfl;vrl;vel;-inf*ones(nH,1)];\n EPproblem.ub = [vfu;vru;veu; inf*ones(nH,1)];\n else\n EPproblem.c =...\n [ci + cf;\n -ci + cr;\n ce];\n %bounds\n EPproblem.lb = [vfl;vrl;vel];\n EPproblem.ub = [vfu;vru;veu];\n end\n \n EPproblem.osense = 1; %minimise\n \n %variables for entropy maximisation\n EPproblem.d=zeros(size(EPproblem.A,2),1);\n EPproblem.d(1:2*n)=[g;g];\n expConeBool = EPproblem.d~=0;\n nExpCone = nnz(expConeBool);\n \n %\n if 1\n solution = solveCobraEP(EPproblem,param);\n else\n [verify,method,printLevel,debug,feasTol,optTol,solver,param] =...\n getCobraSolverParams('EP',getCobraSolverParamsOptionsForType('EP'),param);\n \n solution = solveCobraEP(EPproblem,...\n 'verify',verify,...\n 'method',method,...\n 'printLevel',printLevel,...\n 'debug',debug,...\n 'feasTol',feasTol,...\n 'optTol',optTol,...\n 'solver',solver,...\n param);\n end\n \n switch solution.stat\n case 1\n % Primal variables\n % vf, vr, ve\n vf = solution.full(1:n);\n vr = solution.full(n+1:2*n);\n \n zeroVfBool = vf==0;\n zeroVrBool = vr==0;\n bool = zeroVfBool | zeroVrBool;\n if any(zeroVfBool | zeroVrBool)\n ind = find(bool);\n fprintf('%8s %8s %8s %8s %8s %8s\\n','vfl','vf','vfu','vrl','vr','vru')\n for i=1:length(ind)\n fprintf('%8.4g %8.4g %8.4g %8.4g %8.4g %8.4g\\n',vfl(ind(i)),vf(ind(i)),vfu(ind(i)),vrl(ind(i)),vr(ind(i)),vru(ind(i)));\n end \n end\n \n ve = solution.full(2*n+1:2*n+k);\n \n \n if isfield(model,'H') && isfield(model,'h')\n dv = solution.full(2*n+k+1:2*n+k+nH);\n %disp(norm(dv))\n else\n dv=[];\n end\n \n \n \n expCone1 = (nExpCone>0)+0;\n quadCone1 = (nQuadCone>0)+0;\n \n % Primal auxiliary variables\n % x, 1, p, e, 1, q;\n e_vf_vr = 0*ones(2*n,1);\n e_1 = 0;\n if nExpCone>0\n e_1 = solution.auxPrimal(1);\n e_vf_vr(expConeBool) = solution.auxPrimal(2:nExpCone+1);\n end\n e_vf = e_vf_vr(1:n,1);\n e_vr = e_vf_vr(n+1:2*n,1);\n \n \n q_vf_vr_ve = 0*ones(2*n+k,1);\n q_1 = 0;\n if nQuadCone>0\n q_1 = solution.auxPrimal(nExpCone + double(nExpCone>0) + 1);\n q_vf_vr_ve(quadBool) = solution.auxPrimal(nExpCone + double(nExpCone>0) + 2:nExpCone + double(nExpCone>0) + nQuadCone + 1);\n end\n q_vf = q_vf_vr_ve(1:n,1);\n q_vr = q_vf_vr_ve(n+1:2*n,1);\n q_ve = q_vf_vr_ve(2*n+1:2*n+k,1);\n \n \n %slack variable\n slack = solution.slack;\n s_N = solution.slack(1:m);\n s_v = solution.slack(m+1:m+n);\n if isfield(model,'C')\n s_C = solution.slack(m+n+1:m+n+nConstr);\n end\n \n % Dual variables corresponding to constraints\n y_N = solution.dual(1:m); %dual to steady state constraints\n y_vi = solution.dual(m+1:m+n); %dual to bounds on net flux\n if isfield(model,'C')\n y_C = solution.dual(m+n+1:m+n+nConstr);\n else\n y_C = zeros(0,0);\n end\n \n % Dual variables to affine conic constraints\n y_K = solution.coneDual;\n \n % Dual variables corresponding to bounds on variables.\n z_vf = solution.rcost(1:n,1);\n z_vr = solution.rcost(n+1:2*n,1);\n z_ve = solution.rcost(2*n+1:2*n+k,1);\n \n % Dual variables corresponding to bounds on auxiliary variables.\n z_e_vf_vr = 0*ones(2*n+k,1);\n z_e_1 = 0;\n if nExpCone>0\n z_e_1 = solution.auxRcost(1); % 1\n z_e_vf_vr(expConeBool) = solution.auxRcost(2:nExpCone+1);\n end\n z_e_vf = z_e_vf_vr(1:n,1); % e_vf\n z_e_vr = z_e_vf_vr(n+1:2*n,1); % e_vr\n \n z_q_vf_vr_ve = 0*ones(2*n+k,1);\n z_q_1 = 0;\n if nQuadCone>0\n z_q_1 = solution.auxRcost(nExpCone + expCone1 + 1);\n z_q_vf_vr_ve(quadBool) = solution.auxRcost(nExpCone + expCone1 + 2:nExpCone + expCone1 + nQuadCone + 1);\n end\n z_q_vf = z_q_vf_vr_ve(1:n,1);\n z_q_vr = z_q_vf_vr_ve(n+1:2*n,1);\n z_q_ve = z_q_vf_vr_ve(2*n+1:2*n+k,1);\n \n \n% F = [...\n% % x, 1, p, e, 1, q;\n% Odn, Id1, Idp, Od, Oz1, Odq; % exp cone x1 = 1 or y (if normalisation)\n% Oqn, Ox1, Oqp, Oqd, Oq1, Iq; % quad cone x1 = q \n% Idn, Od1, Odp, Od, Oz1, Odq; % exp cone x2 = x\n% Oqn, Ox1, Oqp, Oqd, Iq1, Oq; % quad cone x2 = 1\n% Odn, Od1, Odp, Id, Oz1, Odq; % exp cone x3 = e\n% R, Ox1, Oqp, Oqd, Oq1, Oq]; % quad cone R*x3 = F3*x\n \n %DUAL to conic constraints ordered by original F matrix\n Fty_K = solution.coneF'*y_K; %Rockafeller signs\n \n % x, 1, p, e, 1, q;\n % x = vf, vr\n k_vf = Fty_K(1:n);\n k_vr = Fty_K(n+1:2*n);\n %note that the rows of the F matrix include exchange reactions even though they are not involved in exponential cone\n k_ve = Fty_K(2*n+1:2*n+k);\n if isfield(model,'Q')\n if max(max(Qve))==0 && norm(k_ve)~=0 %TODO - check if norm(Qve)~=0 >> norm(k_ve)~=0\n error('k_ve should be zero')\n end\n end\n \n %dual to exponential cone variables\n k_e_vf_vr = zeros(2*n,1);\n k_e_1 = 0;\n if nExpCone>0\n k_e_1 = Fty_K(2*n+k+1);\n k_e_vf_vr(expConeBool) = Fty_K(2*n+k+2:2*n+k+1+nExpCone);\n end\n k_e_vf = k_e_vf_vr(1:n,1); % e_vf\n k_e_vr = k_e_vf_vr(n+1:2*n,1); % e_vr\n \n %dual to quadratic cone variable\n kq_vf_vr_ve = zeros(2*n,1);\n k_q_1 = 0;\n if nQuadCone>0\n k_q_1 = Fty_K(2*n+k+1+nExpCone+1);\n kq_vf_vr_ve(quadBool) = Fty_K(2*n+k+3+nExpCone:2*n+k+2+nExpCone+nQuadCone);\n end\n kq_vf = kq_vf_vr_ve(1:n,1);\n kq_vr = kq_vf_vr_ve(n+1:2*n,1);\n \n %TODO fix this piece of code (Index in position 1 exceeds array bounds )\n if 0 && k>0\n kq_ve = kq_vf_vr_ve(2*n+1:2*n+k,1);\n else\n kq_ve = [];\n end\n \n % Tf = table(reallog(vf/vt), 1,cf,N'*y_N,e*z_dx,z_vf,wvf)\n % Tf = table(reallog(vr/vt), 1,cr,N'*y_N,e*z_dx,z_vr,wvr)\n % T = table(reallog(vf/vt),cf,N'*y_N)\n \n %extra checks\n if param.printLevel>0 || param.debug\n fprintf('\\n%s\\n','Optimality conditions (biochemistry)')\n %primal\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - model.b,inf),'|| N*(vf - vr) + B*ve - b ||_inf');\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(C*(vf - vr) + s_C - model.d,inf),'|| C*(vf - vr) + s_C - d ||_inf, s_C = slack variable');\n end\n %dual\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(cf + ci + N'*y_N + C'*y_C + Qv*vf + y_vi + k_vf + z_vf,inf), '|| cf + ci + N''*y_N + C''*y_C + y_vi + Qv*vf + k_vf + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(cr - ci - N'*y_N - C'*y_C + Qv*vr - y_vi + k_vr + z_vr,inf), '|| cr - ci - N''*y_N - C''*y_C - y_vi + Qv*vf + k_vr + z_vr ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(cf + ci + N'*y_N + Qv*vf + y_vi + k_vf + z_vf,inf), '|| cf + ci + N''*y_N + y_vi + Qv*vf + k_vf + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(cr - ci - N'*y_N + Qv*vr - y_vi + k_vr + z_vr,inf), '|| cr - ci - N''*y_N - y_vi + Qv*vf + k_vr + z_vr ||_inf');\n end\n fprintf('%8.2g %s\\n',norm(ce + B'*y_N + z_ve,inf),'|| ce + B''*y_N + z_ve ||_inf');\n \n fprintf('%8.2g %s\\n',norm(k_e_1 + z_e_1,inf),'|| k_e_1 + z_e_1 ||_inf');\n \n fprintf('%8.2g %s\\n',norm(-g + k_e_vf + z_e_vf,inf),'|| -g + k_e_vf + z_e_vf||_inf');\n fprintf('%8.2g %s\\n',norm(-g + k_e_vr + z_e_vr,inf),'|| -g + k_e_vr + z_e_vr||_inf');\n \n if nExpCone>0\n if any(expConeBool(1:n))\n fprintf('%8.2g %s\\n',norm(e_vf(expConeBool(1:n)) + vf(expConeBool(1:n)).*reallog(vf(expConeBool(1:n))),inf), '|| e_vf + vf*log(vf) ||_inf');\n %TODO dual cone\n %fprintf('%7.2g\\t%s\\n',min(y1_K(1:nExpCone) + y3_K(1:nExpCone).*exp(y2_K(1:nExpCone)./y3_K(1:nExpCone))/exp(1)), 'min(y1_k + y3_k.*exp(y2_K./y3_K)/exp(1)) >= 0');\n %fprintf('%7.2g\\t%s\\n',min(-k_e_1 + -k_e_vf.*exp(-k_vf./-k_e_vf)/exp(1)), 'min(k_e_1 + k_e_vf.*exp(k_vf./k_e_vf)/exp(1)) >= 0 (Dual exponential cone)');\n\n end\n if any(expConeBool(n+1:2*n))\n fprintf('%8.2g %s\\n',norm(e_vr(expConeBool(n+1:2*n)) + vr(expConeBool(n+1:2*n)).*reallog(vr(expConeBool(n+1:2*n))),inf), '|| e_vr + vr*log(vr) ||_inf');\n end\n \n\n end\n \n if nQuadCone>0\n fprintf('%8.2g %s\\n',norm(k_q_1 + z_q_1,inf),'|| k_q_1 + z_q_1 ||_inf');\n \n if any(quadBool(1:n))\n fprintf('%8.2g %s\\n',norm(double(kq_vf~=0) + kq_vf + z_q_vf,inf),'|| 1 + k_q_vf + z_q_vf ||_inf');\n bool = false(size(model.Q,1),1);\n bool(1:n,1)=1;\n fprintf('%8.2g %s\\n',norm(q_vf(quadBool(1:n)) + (1/2)*vf'*model.Q(quadBool(n+1:2*n+k) & bool,quadBool(n+1:2*n+k) & bool)*vf,inf), '|| q_vf + 1/2*vf''*Q*vf ||_inf');\n end\n if any(quadBool(n+1:2*n))\n fprintf('%8.2g %s\\n',norm(double(kq_vr~=0) + kq_vr + z_q_vr,inf),'|| 1 + k_q_vr + z_q_vr ||_inf');\n bool = false(size(model.Q,1),1);\n bool(1:n,1)=1;\n fprintf('%8.2g %s\\n',norm(q_vr(quadBool(n+1:2*n)) + (1/2)*vr'*model.Q(quadBool(n+1:2*n+k) & bool,quadBool(n+1:2*n+k) & bool)*vr,inf), '|| q_vr + 1/2*vr''*Q*vr ||_inf');\n end\n \n if any(quadBool(2*n+1:2*n+k)) && 0\n fprintf('%8.2g %s\\n',norm(double(kq_ve~=0) + kq_ve + z_q_ve,inf),'|| 1 + k_q_ve + z_q_ve ||_inf');\n bool = false(size(model.Q,1),1);\n bool(n+1:n+k,1)=1;\n if 0\n %primal - Not sure how to interpret this\n fprintf('%8.2g %s\\n',norm(q_ve(quadBool(2*n+1:2*n+k)) + (1/2)*ve'*model.Q(quadBool(n+1:2*n+k) & bool,quadBool(n+1:2*n+k) & bool)*ve,inf), '|| q_ve + 1/2*ve''*Q*ve ||_inf');\n end\n \n %dual\n fprintf('%8.2g %s\\n',norm(ce + B'*y_N + k_ve + z_ve,inf), '|| ce + B''*y + k_ve + z_ve ||_inf');\n end\n end\n \n fprintf('\\n%s\\n','Derived optimality conditions (biochemistry)')\n valf = k_vf - g.*reallog(vf) - g;\n fprintf('%8.2g %s\\n',norm(valf,inf), '|| g.*log(vf) + g - k_vf ||_inf');\n bool = abs(valf) > 1e-4;\n if any(bool) && param.printLevel>1\n T = table(k_vf(bool),g(bool).*reallog(vf(bool)) + g(bool),vfl(bool),vfu(bool),z_vf(bool),vl(bool),vu(bool),y_vi(bool),'VariableNames',{'k_vf','glog(vf)+g','vfl','vfu','z_vf','vl','vu','z_vi'});\n disp(T)\n end\n valr = k_vr - g.*reallog(vr) - g;\n fprintf('%8.2g %s\\n',norm(valr,inf), '|| g.*log(vr) + g - k_vr ||_inf');\n \n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(cf + ci + N'*y_N + C'*y_C + Qv*vf + y_vi + g.*reallog(vf) + g + z_vf,inf), '|| cf + ci + N''*y_N + C''*y_C + y_vi + Qv*vf + g.*log(vf) + g + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(cr - ci - N'*y_N - C'*y_C + Qv*vr - y_vi + g.*reallog(vr) + g + z_vr,inf), '|| cr - ci - N''*y_N - C''*y_C - y_vi + Qv*vf + g.*log(vr) + g + z_vr ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(cf + ci + N'*y_N + Qv*vf + y_vi + g.*reallog(vf) + g + z_vf,inf), '|| cf + ci + N''*y_N + y_vi + Qv*vf + g.*log(vf) + g + z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(cr - ci - N'*y_N + Qv*vr - y_vi + g.*reallog(vr) + g + z_vr,inf), '|| cr - ci - N''*y_N - y_vi + Qv*vf + g.*log(vr) + g + z_vr ||_inf');\n end\n \n fprintf('\\n%s\\n','Thermo conditions')\n if isfield(model,'C')\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N - 2*C'*y_C,inf),'|| g.*log(vr/vf) - 2*N''*y_N - 2*C''*y_C ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*C''*y_C - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*C'*y_C - 2*y_vi - z_vr + z_vf,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*C''*y_C - 2*y_vi - z_vr + z_vf ||_inf');\n else\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) - 2*N'*y_N,inf),'|| g.*log(vr/vf) - 2*N''*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*y_vi,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(g.*reallog(vr./vf) + cr - cf - 2*ci - 2*N'*y_N - 2*y_vi - z_vr + z_vf,inf),'|| g.*log(vr/vf) + cr - cf - 2*ci - 2*N''*y_N - 2*y_vi - z_vr + z_vf ||_inf');\n end\n \n fprintf('%8.2g %s\\n',min(slack(slack~=0)), 'min(slack)');\n fprintf('%8.2g %s\\n',max(slack(slack~=0)), 'max(slack)');\n end\n otherwise\n end\n \n otherwise\n error('Incorrect solver choice');\n end\n case 'normalisedEntropy'\n switch param.solver\n case 'pdcoPrimal'\n %set the objective\n entropyhandle = @(x) normEntropyObj(x);\n \n %constraint matrix\n % vf vr v vt w\n A = [ N -N Omn Om1 B;\n In -In -In On1 Onk;\n -I1n -I1n O1n 1 O1k];\n \n b2 = [model.b; zeros(n+1,1)];\n \n %bounds\n vl = [vfl;vrl;vl;1;vel];\n vu = [vfu;vru;vu;inf;veu];\n \n %starting vector\n %x0 = (vl+vu)/2; %initial primal variables\n %x0(~isfinite(x0))=1;\n x0 = ones(3*n+1+k,1);\n y0 = sparse(m+n+1,1); %initial dual variables for constraints\n z0 = ones(3*n+1+k,1); %initial reduced gradients\n xsize=1e6;\n zsize=1e2;\n \n %TODO - still have no idea what the best parameters for pdco are\n options = pdcoSet;\n %options.mu0 = 1; %very small only for entropy function\n options.mu0 = 0; %pdco chooses its own\n options.FeaTol = 1e-6;\n options.OptTol = 1e-6;\n % If getting linesearch failures, slacken tolerances\n % i.e. Linesearch failed (nf too big)\n %options.FeaTol = 1e-6; %%Ecoli core working at 1e-7\n %options.OptTol = 1e-6;\n % options.StepSame = 0; %(allow different primal and dual steps)\n d1 = 1e-4;\n d2 = 1e-4; %(regularizations)\n %%%%%%\n %Additional parameter specifications by Ronan\n %increasing to 0.99 reduced the number of iterations required\n %options.StepTol = 0.9;\n % needed more than 30 iterations when xsize & zsize not tuned set\n options.MaxIter = 200;\n options.Method = 2;\n \n % %options from Michael's pdcotestENTROPY\n % xsize = 5/n; % A few elements of x are much bigger than 1/n.\n % xsize = min(xsize,1); % Safeguard for tiny problems.\n % zsize = 1; % This makes y (sic) about the right size.\n % % 10 makes ||y|| even closer to 1,\n % % but for some reason doesn't help.\n %\n % x0min = xsize; % Applies to scaled x1, x2\n % z0min = zsize; % Applies to scaled z1, z2\n %\n % en = ones(n,1);\n % x0 = en*xsize; %\n % y0 = zeros(m,1);\n % z0 = en*z0min; % z is nominally zero (but converges to mu/x)\n %\n % d1 = 0; % 1e-3 is normal. 0 seems fine for entropy\n % d2 = 1e-3; %\n %\n % options = pdcoSet;\n % options.MaxIter = 50;\n % options.FeaTol = 1e-6;\n % options.OptTol = 1e-6;\n % options.x0min = x0min; % This applies to scaled x1, x2.\n % options.z0min = z0min; % This applies to scaled z1, z2.\n % options.mu0 = 1e-5; % 09 Dec 2005: BEWARE: mu0 = 1e-5 happens\n % % to be ok for the entropy problem,\n % % but mu0 = 1e-0 is SAFER IN GENERAL.\n %\n % options.Method = 3; % 1=Chol 2=QR 3=LSQR\n % options.LSMRatol1 = 1e-3;\n % options.LSMRatol2 = 1e-6;\n % options.wait = 1;\n \n options.Print = param.printLevel-1;\n [x,t_vfvr,z,inform,~,~,~] = ...\n pdco(entropyhandle,A,b2,vl,vu,d1,d2,options,x0,y0,z0,xsize,zsize);\n \n if (inform == 0)\n stat = 1;\n if ~any(model.csense == 'L' | model.csense == 'G')\n slack = zeros(m,1);\n else\n slack = zeros(m,1);\n slack(model.csense == 'L' | model.csense == 'G') = z(nRxn+1:end);\n slack(model.csense == 'G') = -slack(model.csense == 'G');\n end\n %x=z(1:size(A,2));\n %w=w(1:size(A,2));\n if 0\n norm(A*x + slack - b,inf)\n end\n elseif (inform == 1 || inform == 2 || inform == 3)\n stat = 0;\n else\n stat = -1;\n end\n origStat=inform;\n \n y_N =-t_vfvr(1:m);%Rockafellar signs\n y_vi = -t_vfvr(m+1:m+n);\n z_dx = -t_vfvr(m+n+1);\n \n %fluxes\n vf = x(1:n);\n vr = x(n+1:2*n);\n v = x(2*n+1:3*n);\n vt = x(3*n+1);\n ve = x(3*n+2:3*n+1+k);\n \n % duals to bounds on unidirectional fluxes\n z_vf = z(1:n,1);\n z_vr = z(n+1:2*n,1);\n % duals to bounds on net fluxes\n z_vi = z(2*n+1:3*n,1);\n %duals to the bounds on total flux\n y_C = z(3*n+1);\n \n %extra checks\n if param.debug\n fprintf('%s\\n','Optimality conditions (unregularised)')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - model.b,inf),'|| N*(vf - vr) + B*ve - b ||_inf');\n fprintf('%8.2g %s\\n',norm(vf - vr - v,inf),'|| vf - vr - v ||_inf');\n fprintf('%8.2g %s\\n',norm(-e'*(vf + vr) + vt,inf),'|| -1''*(vf + vr) + vt ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vf/vt) + 1 + cf + N'*y_N + y_vi - e*z_dx,inf), '|| log(vf/vt) + 1 + cf + N''*y_N - e*z_dx ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr/vt) + 1 + cr - N'*y_N - y_vi - e*z_dx,inf),'|| log(vr/vt) + 1 + cr - N''*y_N - e*z_dx ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vf/vt) + 1 + cf + N'*y_N + y_vi - e*z_dx - z_vf,inf), '|| log(vf/vt) + 1 + cf + N''*y_N - e*z_dx - z_vf ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr/vt) + 1 + cr - N'*y_N - y_vi - e*z_dx - z_vr,inf),'|| log(vr/vt) + 1 + cr - N''*y_N - e*z_dx - z_vr ||_inf');\n fprintf('%8.2g %s\\n',norm(- y_vi - z_vi,inf),'|| -y_vi - z_vi||_inf');\n fprintf('%8.2g %s\\n',norm( -(e'*(vf + vr)/vt) + z_dx - y_C,inf),'|| -(e''*(vf + vr)/vt) + z_dx - y_C||_inf');\n \n \n fprintf('\\n%s\\n','Optimality conditions (regularised)')\n fprintf('%8.2g %s\\n',norm(N*(vf - vr) + B*ve - model.b + (d2^2)*y_N,inf),'|| N*(vf - vr) + B*ve - b + (d2^2)*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(vf - vr - v + (d2^2)*y_vi,inf),'|| vf - vr - v + (d2^2)*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(-e'*(vf + vr) + vt + (d2^2)*z_dx,inf),'|| -1''*(vf + vr) + vt + (d2^2)*z_dx ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vf/vt) + 1 + cf + N'*y_N + y_vi - e*z_dx - z_vf + d1*vf,inf), '|| log(vf/vt) + 1 + cf + N''*y_N + y_vi - e*z_dx - z_vf + d1*vf||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr/vt) + 1 + cr - N'*y_N - y_vi - e*z_dx - z_vr + d1*vr,inf), '|| log(vr/vt) + 1 + cr - N''*y_N - y_vi - e*z_dx - z_vr + d1*vr||_inf');\n \n fprintf('%8.2g %s\\n',norm(- y_vi - z_vi + d1*v,inf),'|| -y_vi - z_vi + d1*v ||_inf');\n fprintf('%8.2g %s\\n',norm( -(e'*(vf + vr)/vt) + z_dx - y_C + d1*vt,inf),'|| -(e''*(vf + vr)/vt) + z_dx - y_C + d1*vt ||_inf');\n \n fprintf('\\n%s\\n','Thermo conditions (unregularised)')\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) - 2*N'*y_N,inf),'|| log(vr./vf) + cr - cf - 2*N''*y_N ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi,inf),'|| log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi + z_vf - z_vr,inf),'|| log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi + z_vf - z_vr ||_inf');\n \n fprintf('\\n%s\\n','Thermo conditions (regularised)')\n fprintf('%8.2g %s\\n',norm(z_vf - z_vr + d1*(vr -vf),inf),'|| z_vf - z_vr + d1*(vr -vf) ||_inf');\n fprintf('%8.2g %s\\n',norm(reallog(vr./vf) + cr - cf - 2*N'*y_N - 2*y_vi + z_vf - z_vr + d1*(vr -vf),inf),'|| log(vr./vf) + cr - cf - 2*N''*y_N - 2*y_vi + z_vf - z_vr + d1*(vr -vf) ||_inf');\n end\n %T = table(reallog(vf/vt)+1+cf,N'*y_N,y_vi,e*z_dx,z_vf,d1*vf);\n end\n case 'fluxTracing'\n otherwise\n error('Incorrect method choice');\nend\n\nif 0\n %get nullspace of N\n [Z,rankS]=getNullSpace(N,param.printLevel-1);\n fprintf('%8.2g %s\\n',norm(Z'*(z_vf - z_vr),inf),'|| Z''*(z_vf - z_vr) ||_inf');\nend\n\nswitch solution.stat\n case 1\n switch param.solver\n case 'pdco'\n solution = rmfield(solution,{'full','dual','rcost','slack'});\n \n case 'mosek'\n solution = rmfield(solution,{'full','dual','rcost','slack','coneF','auxPrimal','auxRcost','coneDual'});\n end\n\n\n v=zeros(n+k,1);\n v(model.SConsistentRxnBool)= vf - vr;\n v(~model.SConsistentRxnBool) = ve;\n \n if ~exist('vt','var')\n vt = sum(vf) + sum(vr);\n end\n if ~exist('z_dx','var')\n z_dx = 0;\n end\n \n if ~exist('z_vi','var')\n if exist('y_vi','var')\n %mosek uses blc <= A*x < buc to enforce l < vf - vr < u\n z_vi = y_vi;\n else\n z_vi = 0;\n end\n end\n \n y_v=zeros(n+k,1);\n y_v(model.SConsistentRxnBool)= z_vi;\n y_v(~model.SConsistentRxnBool) = z_ve;\n z_v = y_v;\n \n [solution.v,solution.vf,solution.vr,solution.vt,solution.y_N,solution.y_v,solution.z_dx,solution.z_vf,solution.z_vr,solution.z_vi,solution.z_v,solution.stat,solution.osense] =...\n deal(v,vf,vr,vt,y_N,y_v,z_dx,z_vf,z_vr,z_vi,z_v,solution.stat,osense);\n \n if exist('x0','var')\n [solution.x, solution.x0, solution.z_x, solution.z_x0, solution.z_dx] = deal(x, x0, z_x, z_x0, z_dx);\n end\n \n if isfield(model,'C')\n solution.y_C=y_C;\n end\n if exist('messages','var')\n if isfield(solution,'messages')\n solution.messages = [solution.messages;messages];\n else\n solution.messages = messages;\n end\n else\n solution.messages = [];\n end\n otherwise\n solution_optimizeCbModel = optimizeCbModel(model);\n switch solution_optimizeCbModel.stat\n case 0\n message = 'entropicFluxBalanceAnalysis: EPproblem is not feasible, because LP part of model is not feasible according to optimizeCbModel.';\n warning(message)\n case 1\n message ='entropicFluxBalanceAnalysis: EPproblem is not feasible, but LP part of model is feasible according to optimizeCbModel.';\n warning(message)\n end\n if isfield(solution,'messages')\n solution.messages = [solution.messages;message];\n else\n solution.messages = cellstr(message);\n end\nend\n\nmodelOut=model;\nmodelOut.lb(model.SConsistentRxnBool) = vl;\nmodelOut.ub(model.SConsistentRxnBool) = vu;\nmodelOut.lb(~model.SConsistentRxnBool) = vel;\nmodelOut.ub(~model.SConsistentRxnBool) = veu;\nmodelOut.cf = cf;\nmodelOut.cr = cr;\nmodelOut.g = g;\n\nif contains(lower(param.method),'conc')\n modelOut.u0 = u0;\n modelOut.f = f;\nend\n\nend\n\n% helper functions for pdco\nfunction [obj,grad,hess] = normEntropyObj(x)\n%NB PDCO SIGNS HERE\nvf = x(1:n);\nvr = x(n+1:2*n);\nvi = x(2*n+1:3*n);\nvt = x(3*n+1);\nve = x(3*n+2:3*n+1+k);\n\nlogvf = reallog(vf/vt); % error if negative\nlogvr = reallog(vr/vt);\ne = ones(n,1);\nobj = vf'*logvf + vr'*logvr + cf'*vf + cr'*vr + [ci;ce]'*[vi;ve];\ngrad = [ logvf + e + cf; % grad f(vf)\n logvr + e + cr; % grad f(vr)\n ci; % grad f(vnet)\n -(e'*(vf + vr))/vt; % grad f(vt)\n ce]; % grad f(ve)\n\nhess = [1./vf; 1./vr; zeros(n,1); (e'*vf + e'*vr)/(vt^2);zeros(k,1)];\nhess = diag(hess);\nend\n\nfunction [obj,grad,hess] = entropyObj(x,c,cr,cf,ci,ce,SConsistentRxnBool)\n\n%NB PDCO SIGNS HERE\nn=nnz(SConsistentRxnBool);\nk=nnz(~SConsistentRxnBool);\nvf = x(1:n);\nvr = x(n+1:2*n);\nvi = x(2*n+1:3*n);\nve = x(3*n+1:3*n+k);\n\nlogvf = reallog(vf); % error if negative\nlogvr = reallog(vr);\ne = ones(n,1);\nobj = vf'*logvf + vr'*logvr + cf'*vf + cr'*vr + [ci;ce]'*[vi;ve];\ngrad = [ logvf + e + cf; % grad f(vf)\n logvr + e + cr; % grad f(vr)\n ci; % grad f(vnet)\n ce]; % grad f(ve)\n\nhess = [1./vf; 1./vr; zeros(n,1); zeros(k,1)];\nhess = diag(hess);\nend\n\nfunction [obj,grad,hess] = dualEntropyObj(x,m,n,b,vfl,vfu,vrl,vru)\n% objective for dual convex flux balance analysis problem\n\ny = x(1:m);\n%dual to inequality constraints on fluxes\nalphal=x(m+1:m+n);\nalphau=x(m+n+1:m+2*n);\nbetal=x(m+2*n+1:m+3*n);\nbetau=x(m+3*n+1:m+4*n);\nwf=x(m+4*n+1:m+4*n+n);\nwr=x(m+4*n+n+1:m+4*n+2*n);\n\n%take exponentials\nwfexp = exp(wf);\nwrexp = exp(wr);\n\nif ~any(isfinite(wfexp))\n % Uncomment this to check if exp(-w) is getting to large\n fprintf('\\n%s%g\\n','Max exp(wf): ',max(wfexp));\nend\nif ~any(isfinite(wfexp))\n fprintf('%s%g\\n','Max exp(wr): ',max(wrexp));\nend\n\n%NB PDCO SIGNS HERE\nobj = - b'*y ...\n - vfl'*alphal + vfu'*alphau...\n - vrl'*betal + vru'*betau...\n + sum(wfexp) + sum(wrexp);\ngrad = [-b;-vfl;vfu;-vrl;vru;wfexp;wrexp];\nhess = [zeros(m+4*n,1);wfexp;wrexp];\nhess = diag(sparse(hess));\nend\n\n\nfunction pdxxxdistrib( x,z )\n%from pdco by Michael Saunders\n% pdxxxdistrib(x) or pdxxxdistrib(x,z) prints the\n% distribution of 1 or 2 vectors.\n%\n% 18 Dec 2000. First version with 2 vectors.\n\n two = nargin > 1;\n fprintf('\\n\\nDistribution of vector x')\n if two, fprintf(' z'); end\n\n x1 = 10^(floor(log10(max(x)+eps)) + 1);\n z1 = 10^(floor(log10(max(z)+eps)) + 1);\n x1 = max(x1,z1);\n kmax = 10;\n\n for k = 1:kmax\n x2 = x1; x1 = x1/10;\n if k==kmax, x1 = 0; end\n nx = length(find(x>=x1 & x=x1 & z vx_min) \n % calculate side slip angles based on exact side slip formulas\n alphaF = DeltaSteer_rad - atan((vy + dPsi*l_front_m)/vx);\n alphaR = - atan((vy - dPsi*l_rear_m)/vx);\n lambdaF = (omegaF - vx/tyreradius_front_m)/(vx/tyreradius_front_m);\n lambdaR = (omegaR - vx/tyreradius_rear_m)/(vx/tyreradius_rear_m);\nelse\n alphaF = 0;\n alphaR = 0;\n lambdaF = 0;\n lambdaR = 0;\nend\n\n\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/TireSlips.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.6066372415086093}} {"text": "function [f,ier]=nufft3d3(x,y,z,c,isign,eps,s,t,u)\n%NUFFT3D3: Nonuniform FFT in R^3 - Type 3.\n%\n% [FK,IER] = NUFFT3D3(NJ,XJ,YJ,ZJ,CJ,IFLAG,NK,SK,TK,UK);\n%\n% 1 nj\n% fk(k) = -- SUM cj(j) exp(+/-i (s(k),t(k),u(k))*(xj(j),yj(j),zj(j)))\n% nj j=1\n%\n% If (isign .ge.0) the + sign is used in the exponential.\n% If (isign .lt.0) the - sign is used in the exponential.\n%\n% Input parameters:\n%\n% nj number of sources (integer)\n% xj,yj,zj location of sources (real *8)\n%\n% on interval [-pi,pi].\n%\n% cj strengths of sources (complex *16)\n% isign determines sign of FFT (see above)\n% eps precision request (between 1.0e-15 and 1.0e-1)\n% nk number of (noninteger) Fourier modes computed\n% sk,tk,uk k-values (locations) of desired Fourier modes\n%\n% Output parameters:\n%\n% fk Fourier transform values (complex *16)\n% ier error return code\n% ier = 0 => normal execution.\n% ier = 1 => precision eps requested is out of range.\n%\n%\n\nnj=numel(x);\nnk=numel(s);\nif numel(y)~=nj, error('y must have the same number of elements as x'); end\nif numel(z)~=nj, error('z must have the same number of elements as x'); end\nif numel(c)~=nj, error('c must have the same number of elements as x'); end\nif numel(t)~=nk, error('t must have the same number of elements as s'); end\nif numel(u)~=nk, error('u must have the same number of elements as s'); end\n \nf=zeros(nk,1)+1i*zeros(nk,1);\nier=0;\n\nmex_id_ = 'nufft3d3f90(i int[x], i double[], i double[], i double[], i dcomplex[], i int[x], i double[x], i int[x], i double[], i double[], i double[], io dcomplex[], io int[x])';\n[f, ier] = nufft3d(mex_id_, nj, x, y, z, c, isign, eps, nk, s, t, u, f, ier, 1, 1, 1, 1, 1);\nend\n\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openFfm/nufft3d3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.606630710468586}} {"text": "function [ B_cone, B_rod ] = BleachingParameters( A_cone, A_rod )\n%\n% [ B_cone, B_rod ] = BleachingParameters( A_cone, A_rod )\n%\n% This function computes sigmoid response\n%\n% input:\n% -A_cone: adaptation for cones in cd/m^2\n% -A_rod: adaptation for rods in cd/m^2\n%\n% output:\n% -B_cone: bleaching parameter for cones\n% -B_rod: bleaching parameter for rods\n%\n% Copyright (C) 2011-14 Francesco Banterle\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n\nB_cone = 2 * 1e6 / (2*1e6 + A_cone);\nB_rod = 0.04 / (0.04 + A_rod);\n\nend\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/source_code/Tmo/util/BleachingParameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6066307083058671}} {"text": "% Hessian of the measurement function in BOT-demo.\n\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nfunction dY = bot_d2h_dx2(x,s)\n % Space for Hessians. Note that we need a Hessian for\n % each dimension in the measurement space, that is we need\n % a Hessian for each sensor in this case. \n dY = zeros(size(s,2),size(x,1),size(x,1));\n \n % Loop through sensors.\n for i=1:size(s,2)\n % Derivative twice wrt. x\n dx2 = -2*(x(1)-s(1,i)) / ((x(1)-s(1,i))^2+(x(2)-s(2,i))^2)^2;\n % Derivative twice wrt. y \n dy2 = -2*(x(2)-s(2,i)) / ((x(1)-s(1,i))^2+(x(2)-s(2,i))^2)^2;\n % Derivative wrt. x and y\n dxdy = ((x(2)-s(2,i))^2-(x(1)-s(1,i))^2) / ((x(1)-s(1,i))^2+(x(2)-s(2,i))^2)^2;\n dh = [dx2 dxdy 0 0;...\n\t dxdy dy2 0 0;...\n\t 0 0 0 0;...\n 0 0 0 0];\n dY(i,:,:) = dh;\n end", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/demos/eimm_demo/bot_d2h_dx2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6066307009075987}} {"text": "function [price, opt, L] = PROJ_GMDB_DCA(proj_params, S_0, gmdb_params, r, q, modelInput)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% About: Pricing Function for DCA-Style Garuanteed Minimum Withdraw Benefit (GMWB) using PROJ method\n%\n% Terminal Payoff: Payoff(tau) = L*exp(g*tau) + (Gam(tau) - L*exp(g*tau))^+\n% Gam(tau) = S_M * sum_{m=0}^M(alpha*gamma / S_m)\n% tau = time of death (discrete periods)\n%\n% Models Supported: Levy Processes, including jump diffusions and Black-Scholes model\n% Returns: price of contract\n%\n% NOTE: this is the SLOW \"Direct\" version for testing purpose. In general, use PROJ_GMDB_DCA_Fast\n%\n% Author: Justin Lars Kirkby\n% References: 1) Equity-Linked Guaranteed Minimum Death Benefits with Dollar Cost Averaging, J.L.Kirkby & D.Nguyen, 2021\n%\n% ----------------------\n% Contract/Model Params \n% ----------------------\n% S_0 = initial stock price (e.g. 100)\n% r = interest rate (e.g. 0.05)\n% q = dividend yield (e.g. 0.05)\n% M = number of subintervals of [0,T] (total of M+1 monitoring points in time grid, including S_0)\n% gmdb_params = container of GMDB contract params, see below\n% modelInput = model inputs, see below\n%\n% ----------------------\n% Numerical (PROJ) Params \n% ----------------------\n% proj_params = numerical params\n% proj_params.N = number of basis elements, e.g. N = 2^10\n% proj_params.L1 = gridwidth param, e.g. L1 = 8\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ------------------\n% GMDB Contract Params\n% ------------------\nL = gmdb_params.L; % Guarantee Level: Set L = -1 to use ATMF value for L\nalpha = gmdb_params.alpha; % Period premium payment, paid every dt time units\ngamma = gmdb_params.gamma; % Proportion of investment retained by policyholder (fee is 1-gamma)\ncontract_type = gmdb_params.contract_type; % Contract type: 1 = GMDB, 2 = GMDB-RS (Ratchet strike)\np = gmdb_params.death_prob; % death probability distribution, must be consistent with dt\ng = gmdb_params.g;\n\n% ------------------\n% Model Inputs\n% ------------------\ndt = modelInput.dt; % Time increment, premiums paid / underlying S is monitored every dt\nphiR = modelInput.rnCHF; % Risk neutral CHF for time period dt\n\n\nZ = gen_func(-r, dt, p);\nif g == 0\n Zrg = Z;\nelse\n Zrg = gen_func(-(r-g), dt, p);\nend\n\nif L == -1\n MF = gen_func(r - q - g, dt, p);\n Zg = gen_func(-g, dt, p);\n L = alpha * gamma * (exp((r-q)*dt)*MF - Zg) / (exp((r-q)*dt) - 1);\nend\n\ncall = 1;\nN = proj_params.N;\n\ns = 0;\n\nfor n = 1 : length(p)\n\n M = n; \n T = n*dt;\n if contract_type == 2 % GMDB-RS\n W = S_0;\n else\n W = S_0*L*exp(g*T) / (alpha*gamma*(M+1));\n end\n \n pr_alpha = getTruncationAlpha(T, proj_params.L1, modelInput, proj_params.model);\n\n if n == 1\n W = 2*W - S_0;\n opt_v = 0.5*PROJ_European(3, N, 2*pr_alpha, r, q, T, S_0, W, call, phiR, modelInput.c1);\n else\n if contract_type == 1 || contract_type == 2 % GMDB / GMDB-RS\n ER = 0;\n opt_v = PROJ_Asian(N, pr_alpha, S_0, M, W, call, T, r, q, phiR, ER);\n elseif contract_type == 3 % European (for upper bound)\n opt_v = PROJ_European(3, N, 2*pr_alpha, r, q, T, S_0, W, call, modelInput.rnCHF_T, modelInput.c1);\n if r ~= 0 % else there is no multiplier)\n opt_v = opt_v * ((1 - exp(-r*(n+1)*dt)) / (1 - exp(-r*dt)))/(n+1);\n end\n elseif contract_type == 4 % geometric Asian (for lower bound)\n opt_v = PROJ_Geometric_Asian(N, pr_alpha, S_0, M, W, call, T, r, q, modelInput.rnSYMB);\n end\n end\n\n % fprintf('%.12f \\n', opt_v);\n s = s + p(n) * (n + 1) * opt_v; \n \nend\n\nopt = s * alpha * gamma / S_0;\nprice = L*Zrg - alpha * (exp(r*dt) - Z) / (exp(r*dt) - 1) + opt;\n\nend\n\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/PROJ/LEVY/GMDB_DCA/PROJ_GMDB_DCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6066306935093295}} {"text": "% Run file to produce the CME experiment from the paper\n% S. Dolgov, D. Savostyanov,\n% \"Alternating minimal energy methods for linear systems in higher\n% dimensions\"\n\ntry\n maxNumCompThreads(1);\ncatch\n % Just skip. Sometimes if you specify -singleCompThread in the command\n % line, MATLAB will fail at maxNumCompThreads with scary, so tell him\n % it's okay.\nend;\n\nn = 64*ones(20,1);\nT = 10;\nLt = 12;\ntol = 1e-6;\nkickrank = 4;\nnswp = 20;\ntrunc_norm = 'fro';\nverb = 3;\n\ntol_gmres = 1e-3; % I would not set anything lower\n\nd = numel(n);\n\nAp = cell(d,1);\n% Cascadic MPO -- production reactions\nAp{1} = zeros(1,n(1),n(1),3);\nAp{1}(1,:,:,1) = eye(n(1));\nAp{1}(1,:,:,2) = diag((0:n(1)-1)./(5+(0:n(1)-1)));\nAp{1}(1,:,:,3) = (diag(ones(n(1)-1,1),-1)-eye(n(1)))*0.7*diag([ones(n(1)-1,1);0]);\nfor i=2:d-1\n Ap{i} = zeros(3,n(i),n(i),3);\n Ap{i}(1,:,:,1)=eye(n(i));\n Ap{i}(3,:,:,3)=eye(n(i));\n Ap{i}(1,:,:,2)=diag((0:n(i)-1)./(5+(0:n(i)-1)));\n Ap{i}(2,:,:,3)=(diag(ones(n(i)-1,1),-1)-eye(n(i)))*diag([ones(n(i)-1,1);0]);\nend;\nAp{d} = zeros(3,n(d),n(d));\nAp{d}(2,:,:) = (diag(ones(n(d)-1,1),-1)-eye(n(d)))*diag([ones(n(d)-1,1);0]);\nAp{d}(3,:,:) = eye(n(d));\n% Laplace MPO -- destruction reactions\nAd = cell(d,1);\nAd{1} = zeros(1,n(1),n(1),2);\nAd{1}(1,:,:,1) = (diag(ones(n(1)-1,1),1)-eye(n(1)))*diag((0:n(1)-1))*0.07;\nAd{1}(1,:,:,2) = eye(n(1));\nfor i=2:d-1\n Ad{i} = zeros(2,n(i),n(i),2);\n Ad{i}(1,:,:,1)=eye(n(i));\n Ad{i}(2,:,:,2)=eye(n(i));\n Ad{i}(2,:,:,1)=(diag(ones(n(i)-1,1),1)-eye(n(i)))*diag((0:n(i)-1))*0.07;\nend;\nAd{d} = zeros(2,n(d),n(d),1);\nAd{d}(1,:,:) = eye(n(d));\nAd{d}(2,:,:) = (diag(ones(n(d)-1,1),1)-eye(n(d)))*diag((0:n(d)-1))*0.07;\n\n% QTT-tize each dimension separately, it is more stable due to smaller size\nApq = [];\nAdq = [];\nfor i=1:d\n r1 = size(Ap{i},1);\n r2 = size(Ap{i},4);\n Aloc = cell2core(tt_matrix, Ap(i));\n Aloc = tt_reshape(Aloc, factor(n(i))'*[1,1], 1e-13, r1, r2);\n Apq = tkron(Apq, Aloc);\n \n r1 = size(Ad{i},1);\n r2 = size(Ad{i},4);\n Aloc = cell2core(tt_matrix, Ad(i));\n Aloc = tt_reshape(Aloc, factor(n(i))'*[1,1], 1e-13, r1, r2);\n Adq = tkron(Adq, Aloc);\nend;\n\n% Now the final CME operator\nA = Apq+Adq;\nI = tt_eye(A.n);\n\n\n% Global time scheme\ntau = T/2^Lt;\nGt = IpaS(Lt,-1)/tau;\niGt = tt_qtoepl(tkron(tt_ones(2,Lt), tt_tensor([0;1])), Lt)*tau;\nMt = tt_eye(2,Lt);\ne1t = tt_unit(2,Lt,1);\net = tt_ones(2,Lt);\neNt = tt_unit(2,Lt,2^Lt);\n\n% Global matrix\nB = tkron(I,tt_eye(2,Lt)) - tkron(A,iGt*Mt);\n\n\n% Initial state\nu = [];\nfor i=1:d\n u = tkron(u, tt_unit(factor(n(i))', numel(factor(n(i))), 1)); %QTT\nend;\nU0 = tkron(u,et);\n\n% RHS\nf = tkron(u, et);\n\n% Symmetrized matrix and RHS\nB2 = B'*B;\nB2 = round(B2, 1e-13);\nf2 = B'*f;\nf2 = round(f2, 1e-13);\n\n% Use MEX library. It is safe, since in the last TT-Toolbox it switches to\n% pure Matlab automatically, if you did not compile the MEXes.\nismex = true;\n\n% Solvers\n% Reference solution\ntic;\nU_ex = amen_solve2(B, f, tol*1e-3, 'x0', U0, 'nswp', nswp*3, 'kickrank', kickrank, 'trunc_norm', trunc_norm, 'ismex', true, 'verb', 1, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2);\ntoc;\n \n% ALS(SD)\ntic;\n[U_alstpz,td_alstpz] = alstpz_solve(B,f,tol, 'x0',U0, 'max_full_size', 50, 'kickrank', kickrank, 'nswp', nswp, 'kicktype', 'svd', 'symm', false, 'ismex', ismex, 'verb', verb);\ntoc;\n% ALS(SD)+SYMM\ntic;\n[U_alstpz_s,td_alstpz_s] = alstpz_solve(B2,f2,tol, 'x0',U0, 'max_full_size', 50, 'kickrank', kickrank, 'nswp', nswp, 'kicktype', 'svd', 'symm', false, 'ismex', ismex, 'verb', verb);\ntoc;\n% AMEN+SVD\ntic;\n[U_amen_svd,td_amen_svd] = amen_solve2(B, f, tol, 'x0', U0, 'nswp', nswp, 'kicktype', 'svd', 'kickrank', kickrank, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2);\ntoc;\n% AMEN+SVD+SYMM\ntic;\n[U_amen_svd_s,td_amen_svd_s] = amen_solve2(B2, f2, tol, 'symm', false, 'x0', U0, 'nswp', nswp, 'kicktype', 'svd', 'kickrank', kickrank, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2);\ntoc;\n% AMEN+ALS\ntic;\n[U_amen_als,td_amen_als] = amen_solve2(B, f, tol, 'x0', U0, 'nswp', nswp, 'kickrank', kickrank, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2);\ntoc;\n% AMEN+ALS+SYMM\ntic;\n[U_amen_als_s,td_amen_als_s] = amen_solve2(B2, f2, tol, 'symm', false, 'x0', U0, 'nswp', nswp, 'kickrank', kickrank, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2);\ntoc;\n% DMRG\ntic;\n[U_dmrg,td_dmrg] = dmrg_solve3(B, f, tol, 'x0', U0, 'nswp', nswp, 'kickrank', 0, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2, 'step_drank', 0, 'step_dpow', 0, 'min_dpow', 0.5, 'dirfilter', 1);\ntoc;\n% DMRG+SYMM\ntic;\n[U_dmrg_s,td_dmrg_s] = dmrg_solve3(B2, f2, tol, 'symm', false, 'x0', U0, 'nswp', nswp, 'kickrank', 0, 'trunc_norm', trunc_norm, 'ismex', ismex, 'verb', verb, 'max_full_size', 50, 'local_restart', 50, 'local_iters', 2, 'resid_damp', 2, 'step_drank', 0, 'step_dpow', 0, 'min_dpow', 0.5, 'dirfilter', 1);\ntoc;\n\n% TT-GMRES\n[U_gmres,td_gmres] = tt_gmres(core(B), core(f), tol_gmres, 10, 15, tol_gmres, tol_gmres, [], [], [], [], verb);\n\n% This is a time-dep problem => check the last snapshots\nif (~isempty(whos('U_ex')))\n u_ex = chunk(U_ex, 1, f.d-Lt)*dot(eNt, chunk(U_ex, f.d-Lt+1, f.d)).';\n u_ex = tt_reshape(u_ex, n);\nend;\nfprintf('Snapshot errors: \\n');\nif (~isempty(whos('U_alstpz')))\n u_alstpz = chunk(U_alstpz, 1, f.d-Lt)*dot(eNt, chunk(U_alstpz, f.d-Lt+1, f.d)).';\n u_alstpz = tt_reshape(u_alstpz, n);\n fprintf('alstpz:\\t\\t%3.5e\\n', norm(u_alstpz-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_alstpz_s')))\n u_alstpz_s = chunk(U_alstpz_s, 1, f.d-Lt)*dot(eNt, chunk(U_alstpz_s, f.d-Lt+1, f.d)).';\n u_alstpz_s = tt_reshape(u_alstpz_s, n);\n fprintf('alstpz_s:\\t\\t%3.5e\\n', norm(u_alstpz_s-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_amen_svd')))\n u_amen_svd = chunk(U_amen_svd, 1, f.d-Lt)*dot(eNt, chunk(U_amen_svd, f.d-Lt+1, f.d)).';\n u_amen_svd = tt_reshape(u_amen_svd, n);\n fprintf('amen_svd:\\t\\t%3.5e\\n', norm(u_amen_svd-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_amen_svd_s')))\n u_amen_svd_s = chunk(U_amen_svd_s, 1, f.d-Lt)*dot(eNt, chunk(U_amen_svd_s, f.d-Lt+1, f.d)).';\n u_amen_svd_s = tt_reshape(u_amen_svd_s, n);\n fprintf('amen_svd_s:\\t\\t%3.5e\\n', norm(u_amen_svd_s-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_amen_als')))\n u_amen_als = chunk(U_amen_als, 1, f.d-Lt)*dot(eNt, chunk(U_amen_als, f.d-Lt+1, f.d)).';\n u_amen_als = tt_reshape(u_amen_als, n);\n fprintf('amen_als:\\t\\t%3.5e\\n', norm(u_amen_als-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_amen_als_s')))\n u_amen_als_s = chunk(U_amen_als_s, 1, f.d-Lt)*dot(eNt, chunk(U_amen_als_s, f.d-Lt+1, f.d)).';\n u_amen_als_s = tt_reshape(u_amen_als_s, n);\n fprintf('amen_als_s:\\t\\t%3.5e\\n', norm(u_amen_als_s-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_dmrg')))\n u_dmrg = chunk(U_dmrg, 1, f.d-Lt)*dot(eNt, chunk(U_dmrg, f.d-Lt+1, f.d)).';\n u_dmrg = tt_reshape(u_dmrg, n);\n fprintf('dmrg:\\t\\t%3.5e\\n', norm(u_dmrg-u_ex)/norm(u_ex));\nend;\nif (~isempty(whos('U_dmrg_s')))\n u_dmrg_s = chunk(U_dmrg_s, 1, f.d-Lt)*dot(eNt, chunk(U_dmrg_s, f.d-Lt+1, f.d)).';\n u_dmrg_s = tt_reshape(u_dmrg_s, n);\n fprintf('dmrg_s:\\t\\t%3.5e\\n', norm(u_dmrg_s-u_ex)/norm(u_ex));\nend;\n\n% Compare with KSL\nNksl = 50;\n% Set the ranks to the proper valus returned by AMEN\nu_ksl = chunk(U_amen_als, 1, f.d-Lt)*dot(eNt, chunk(U_amen_als, f.d-Lt+1, f.d)).';\nu_ksl = round(u_ksl, tol*0.1);\nr_ksl = u_ksl.r; \ntic;\nu_ksl = u+0*tt_rand(u.n,u.d,r_ksl,-1);\nfor j=1:Nksl\n u_ksl = tt_ksl_ml(u_ksl, A, tt_zeros(u_ksl.n), T/Nksl);\nend;\nttimes_ksl=toc;\nu_ksl = tt_reshape(u_ksl, n);\nfprintf('ksl:\\t\\t%3.5e\\n', norm(u_ksl-u_ex)/norm(u_ex));\nfprintf('CPU Time of the KSL: %g\\n', ttimes_ksl);\n\n\n% % Result history processing\nerr_alstpz = zeros(nswp,1);\nerr_alstpz_s = zeros(nswp,1);\nerr_amen_svd = zeros(nswp,1);\nerr_amen_svd_s = zeros(nswp,1);\nerr_amen_als = zeros(nswp,1);\nerr_amen_als_s = zeros(nswp,1);\nerr_dmrg = zeros(nswp,1);\nerr_dmrg_s = zeros(nswp,1);\n% Measure the errors\nfor i=1:nswp\n if (~isempty(whos('td_alstpz')))\n err_alstpz(i) = norm(td_alstpz{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_alstpz_s')))\n err_alstpz_s(i) = norm(td_alstpz_s{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_amen_svd')))\n err_amen_svd(i) = norm(td_amen_svd{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_amen_svd_s')))\n err_amen_svd_s(i) = norm(td_amen_svd_s{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_amen_als')))\n err_amen_als(i) = norm(td_amen_als{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_amen_als_s')))\n err_amen_als_s(i) = norm(td_amen_als_s{2}{end,i}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_dmrg')))\n err_dmrg(i) = norm(td_dmrg{2}{end-1,i*2-1}-U_ex)/norm(U_ex);\n end;\n if (~isempty(whos('td_dmrg_s')))\n err_dmrg_s(i) = norm(td_dmrg_s{2}{end-1,i*2-1}-U_ex)/norm(U_ex);\n end;\nend;\n\n% Prepare the data in the TikZ-readable form\ndats = [(1:nswp)', td_alstpz{1}(end,:)', err_alstpz, td_alstpz_s{1}(end,:)', err_alstpz_s, ...\n td_amen_svd{1}(end,:)', err_amen_svd, td_amen_svd_s{1}(end,:)', err_amen_svd_s, ...\n td_amen_als{1}(end,:)', err_amen_als, td_amen_als_s{1}(end,:)', err_amen_als_s, ...\n td_dmrg{1}(end-1,1:2:end)', err_dmrg, td_dmrg_s{1}(end-1,1:2:end)', err_dmrg_s];\n% dats layout:\n% iter(1) t_alstpz(2) e_alstpz(3) t_alstpz_s(4) e_alstpz_s(5)\n% t_as(6) e_as(7) t_as_s(8) e_as_s(9)\n% t_aa(10) e_aa(11) t_aa_s(12) e_aa_s(13)\n% t_d(14) e_d(15) t_d_s(16) e_d_s(17)\n\n% Process the GMRES output. It is different...\nif (~isempty(whos('td_gmres')))\n iter_gmres = min([find(td_gmres{1}==0, 1), numel(td_gmres{1})+1])-1;\n err_gmres = zeros(iter_gmres, 1);\n for i=1:iter_gmres\n err_gmres(i) = norm(tt_tensor(td_gmres{2}{i})-U_ex)/norm(U_ex);\n end;\n dat_gmres = [(1:iter_gmres)', td_gmres{1}(1:iter_gmres)', err_gmres];\nend;\n\n% Draw 'em for humans\n% iter\nfigure(1);\nsemilogy(dats(:,1), dats(:,[3,5,7,9,11,13,15,17]), dat_gmres(1:min(iter_gmres,nswp),1), dat_gmres(1:min(iter_gmres,nswp),3));\nlegend('alstz', 'alstz-s', 'amen-svd', 'amen-svd-s', 'amen-als', 'amen-als-s', 'dmrg', 'dmrg-s', 'gmres');\n% time\nfigure(2);\nloglog(dats(:,2),dats(:,3), dats(:,4),dats(:,5), ...\n dats(:,6),dats(:,7), dats(:,8),dats(:,9), ...\n dats(:,10),dats(:,11), dats(:,12),dats(:,13), ...\n dats(:,14),dats(:,15), dats(:,16),dats(:,17), ...\n dat_gmres(:,2), dat_gmres(:,3));\n\n% % Uncomment this if you want to draw the data elsewhere\n% save('cme20_err.dat', '-ascii', 'dats');\n% save('cme20_err_gmres.dat', '-ascii', 'dat_gmres');\n\n", "meta": {"author": "oseledets", "repo": "TT-Toolbox", "sha": "1b87616b1e84de89699697fe196eba814aabe954", "save_path": "github-repos/MATLAB/oseledets-TT-Toolbox", "path": "github-repos/MATLAB/oseledets-TT-Toolbox/TT-Toolbox-1b87616b1e84de89699697fe196eba814aabe954/tests/test_amen_cme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6065585725645386}} {"text": "function [V, converged, i] = newtonpf(Ybus, Sbus, V0, ref, pv, pq, mpopt)\n%NEWTONPF Solves power flow using full Newton's method (power/polar)\n% [V, CONVERGED, I] = NEWTONPF(YBUS, SBUS, V0, REF, PV, PQ, MPOPT)\n%\n% Solves for bus voltages using a full Newton-Raphson method, using nodal\n% power balance equations and polar coordinate representation of\n% voltages, given the following inputs:\n% YBUS - full system admittance matrix (for all buses)\n% SBUS - handle to function that returns the complex bus power\n% injection vector (for all buses), given the bus voltage\n% magnitude vector (for all buses)\n% V0 - initial vector of complex bus voltages\n% REF - bus index of reference bus (voltage ang reference & gen slack)\n% PV - vector of bus indices for PV buses\n% PQ - vector of bus indices for PQ buses\n% MPOPT - (optional) MATPOWER option struct, used to set the\n% termination tolerance, maximum number of iterations, and\n% output options (see MPOPTION for details).\n%\n% The bus voltage vector contains the set point for generator\n% (including ref bus) buses, and the reference angle of the swing\n% bus, as well as an initial guess for remaining magnitudes and\n% angles.\n%\n% Returns the final complex voltages, a flag which indicates whether it\n% converged or not, and the number of iterations performed.\n%\n% See also RUNPF, NEWTONPF_S_CART, NEWTONPF_I_POLAR, NEWTONPF_I_CART.\n\n% MATPOWER\n% Copyright (c) 1996-2019, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% default arguments\nif nargin < 7\n mpopt = mpoption;\nend\n\n%% options\ntol = mpopt.pf.tol;\nmax_it = mpopt.pf.nr.max_it;\nlin_solver = mpopt.pf.nr.lin_solver;\n\n%% initialize\nconverged = 0;\ni = 0;\nV = V0;\nVa = angle(V);\nVm = abs(V);\n\n%% set up indexing for updating V\nnpv = length(pv);\nnpq = length(pq);\nj1 = 1; j2 = npv; %% j1:j2 - V angle of pv buses\nj3 = j2 + 1; j4 = j2 + npq; %% j3:j4 - V angle of pq buses\nj5 = j4 + 1; j6 = j4 + npq; %% j5:j6 - V mag of pq buses\n\n%% evaluate F(x0)\nmis = V .* conj(Ybus * V) - Sbus(Vm);\nF = [ real(mis([pv; pq]));\n imag(mis(pq)) ];\n\n%% check tolerance\nnormF = norm(F, inf);\nif mpopt.verbose > 1\n fprintf('\\n it max P & Q mismatch (p.u.)');\n fprintf('\\n---- ---------------------------');\n fprintf('\\n%3d %10.3e', i, normF);\nend\nif normF < tol\n converged = 1;\n if mpopt.verbose > 1\n fprintf('\\nConverged!\\n');\n end\nend\n\n%% attempt to pick fastest linear solver, if not specified\nif isempty(lin_solver)\n nx = length(F);\n if nx <= 10 || have_feature('octave')\n lin_solver = '\\'; %% default \\ operator\n else %% MATLAB and nx > 10 or Octave and nx > 2000\n lin_solver = 'LU3'; %% LU decomp with 3 output args, AMD ordering\n end\nend\n\n%% do Newton iterations\nwhile (~converged && i < max_it)\n %% update iteration counter\n i = i + 1;\n\n %% evaluate Jacobian\n [dSbus_dVa, dSbus_dVm] = dSbus_dV(Ybus, V);\n [dummy, neg_dSd_dVm] = Sbus(Vm);\n dSbus_dVm = dSbus_dVm - neg_dSd_dVm;\n\n j11 = real(dSbus_dVa([pv; pq], [pv; pq]));\n j12 = real(dSbus_dVm([pv; pq], pq));\n j21 = imag(dSbus_dVa(pq, [pv; pq]));\n j22 = imag(dSbus_dVm(pq, pq));\n\n J = [ j11 j12;\n j21 j22; ];\n\n %% compute update step\n dx = mplinsolve(J, -F, lin_solver);\n\n %% update voltage\n if npv\n Va(pv) = Va(pv) + dx(j1:j2);\n end\n if npq\n Va(pq) = Va(pq) + dx(j3:j4);\n Vm(pq) = Vm(pq) + dx(j5:j6);\n end\n V = Vm .* exp(1j * Va);\n Vm = abs(V); %% update Vm and Va again in case\n Va = angle(V); %% we wrapped around with a negative Vm\n\n %% evalute F(x)\n mis = V .* conj(Ybus * V) - Sbus(Vm);\n F = [ real(mis([pv; pq]));\n imag(mis(pq)) ];\n\n %% check for convergence\n normF = norm(F, inf);\n if mpopt.verbose > 1\n fprintf('\\n%3d %10.3e', i, normF);\n end\n if normF < tol\n converged = 1;\n if mpopt.verbose\n fprintf('\\nNewton''s method power flow (power balance, polar) converged in %d iterations.\\n', i);\n end\n end\nend\n\nif mpopt.verbose\n if ~converged\n fprintf('\\nNewton''s method power flow (power balance, polar) did not converge in %d iterations.\\n', i);\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/newtonpf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6065585469931983}} {"text": "function [gradISE,gradJhr,gradJrr]=GaussMixISELTCovGrads(w1,mu1,P1,w2,mu2,P2,L2,PDFVals12,PDFVals22)\n%%GAUSSMIXISELTCOVGRADS Compute the gradient of the non-normalized\n% integrated squared error (ISE) between two Gaussian mixture\n% PDFs with respect to the elements of square-roots of the\n% covariance matrices of the individual components of the\n% second Gaussian mixture. For a covariance matrix P, the\n% square root L is such that P=L*L'. However, L does not need\n% to be lower-triangular. This gradient can arise when\n% optimizing over the ISE with respect to the covariance\n% matrices. Optimizing over the square-root matrices rather\n% than the matrices themselves ensures that the covariance\n% matrices are always positive (semi)definite.\n%\n%INPUTS: w1 The N1X1 or 1XN1 vector of weights for the first Gaussian\n% mixture. All w1>0 and sum(w1)=1.\n% mu1 The xDimXN1 set of mean vectors for the first Gaussian mixture\n% distribution.\n% P1 The xDimXxDimXN1 set of positive definite covariance matrices\n% for the first Gaussian mixture distirbution.\n% w2, mu2, P2, The length N2, xDimXN2, and xDimXxDimXN2 set of weights,\n% mean vectors and positive-definite covariance matrices for the\n% second Gaussian mixture distribution.\n% L2 The xDimXxDimXN2 set of square roots of the covariance matrices\n% in P2 such that P2(:,:,i)=L2(:,:,i)*L2(:,:,i)'.\n% PDFVals12 A matrix such that the value in element (i,j) is\n% N(mu1(:,i);mu2(:,j),P1(:,:,i)+P2(:,:,j)), where N indicates the\n% multivariate Gaussian PDF evaluated at the first argument with\n% the second and third arguments being the mean and covarince\n% matrix. This parameter is returned by computeGaussMixISE.\n% PDFVals22 A matrix such that the value in element (i,j) is\n% N(mu2(:,i);mu2(:,j),P2(:,:,i)+P2(:,:,j)). This parameter is\n% returned by computeGaussMixISE.\n%\n%OUTPUTS: gradISE The xDimXxDimXN2 set of derivatives of the ISE with\n% respect to the elements of L2 (the square roots of P2).\n% gradJhr, gradJrr In Chapter 3 of [1], the ISE is expressed in terms of\n% Jhr and Jrr terms. These are the xDimXxDimXN2 gradients\n% of those terms.\n%\n%Formule for gradJhr and gradJrr are Equation 3.45 in Section 3.3.3.3 of\n%[1]. They relate to the ISE via Equation 3.20. See the function\n%computeGaussMixISE to compute the ISE.\n%\n%EXAMPLE 1:\n%In this example with a scalar PDF, we verify that the gradient obtained\n%from this function is consistent with numerical differentiation.\n% w1=[0.03,0.18,0.12,0.19,0.02,0.16,0.06,0.1,0.08,0.06];\n% n1=length(w1);\n% mu1=[1.45,2.20,0.67,0.48,1.49,0.91,1.01,1.42,2.77,0.89];\n% P1=[0.0487,0.0305,0.1171,0.0174,0.0295,0.0102, 0.0323, 0.0380, 0.0115, 0.0679];\n% P1=reshape(P1,[1,1,n1]);\n\n% %The second PDF is the first with the five least-weight components deleted.\n% w2=[0.18,0.12,0.19,0.16,0.1,0.08];\n% w2=w2/sum(w2);\n% n2=length(w2);\n% mu2=[2.20,0.67,0.48,0.91,1.42,2.77];\n% P2=[0.0305,0.1171,0.0174,0.0102,0.0380,0.0115];\n% P2=reshape(P2,[1,1,n2]);\n% \n% [ISEVal,PDFVals12,PDFVals22]=computeGaussMixISE(w1,mu1,P1,w2,mu2,P2);\n% L2=sqrt(P2);\n% epsVal=1e-8;\n% gradISENum=zeros(1,1,n2);\n% for k=1:n2\n% L2Cur=L2;\n% L2Cur(1,1,k)=L2Cur(1,1,k)+epsVal;\n% ISEValCur=computeGaussMixISE(w1,mu1,P1,w2,mu2,L2Cur.^2);\n% gradISENum(k)=(ISEValCur-ISEVal)/epsVal;\n% end\n% gradISE=GaussMixISELTCovGrads(w1,mu1,P1,w2,mu2,P2,L2,PDFVals12,PDFVals22);\n% RelErr=max(abs((gradISENum(:)-gradISE(:))./gradISENum(:)))\n%The relative error will be about 7.162e-6, which indicates good numeric\n%agreement.\n%\n%EXAMPLE 2:\n%In this example with a bivariate PDF, we verify that the gradient obtained\n%from this function is consistent with numerical differentiation.\n% w1=[0.25;0.5;0.25];\n% mu1=zeros(2,2);\n% mu1(:,1)=[1;-1];\n% mu1(:,2)=[-1;1];\n% mu1(:,3)=[0;0];\n% P1=zeros(2,2,2);\n% P1(:,:,1)=[4/9, 14/45;\n% 14/45,4/9];\n% P1(:,:,2)=[4/9, 0;\n% 0, 4/9];\n% P1(:,:,3)=[2/9, -1/9;\n% -1/9, 3/9];\n% \n% %The second distribution just throws out the first component.\n% w2=w1(2:3);\n% w2=w2/sum(w2);\n% mu2=mu1(:,2:3);\n% P2=P1(:,:,2:3);\n% \n% n2=length(w2);\n% [ISEVal,PDFVals12,PDFVals22]=computeGaussMixISE(w1,mu1,P1,w2,mu2,P2);\n% \n% numDim=size(mu2,1);\n% L2=zeros(numDim,numDim,n2);\n% for j=1:n2\n% L2(:,:,j)=chol(P2(:,:,j),'lower'); \n% end\n% \n% epsVal=1e-8;\n% gradISENumDiff=zeros(numDim,numDim,n2);\n% for j=1:n2\n% for curEl=1:(numDim^2)\n% [i1,i2]=ind2sub([numDim,numDim],curEl);\n% \n% LCur=L2(:,:,j);\n% LCur(i1,i2)=LCur(i1,i2)+epsVal;\n% \n% PCur=P2;\n% PCur(:,:,j)=LCur*LCur';\n% ISEValCur=computeGaussMixISE(w1,mu1,P1,w2,mu2,PCur);\n% gradISENumDiff(i1,i2,j)=(ISEValCur-ISEVal)/epsVal;\n% end\n% end\n% gradISE=GaussMixISELTCovGrads(w1,mu1,P1,w2,mu2,P2,L2,PDFVals12,PDFVals22);\n% RelErr=max(max(abs((gradISENumDiff-gradISE)./gradISENumDiff)))\n%The relative error will be about 6.99e-7, which indicates good numeric\n%agreement.\n%\n%REFERENCES:\n%[1] J. L. Williams, \"Gaussian mixture reduction for tracking multiple\n% maneuvering targets in clutter,\" Master's thesis, Air Force Institute\n% of Technology, Mar. 2003. [Online].\n% Available: http://www.dtic.mil/srch/doc?collection=t3&id=ADA415317\n%\n%May 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nNh=length(w1);\nNr=length(w2);\nxDim=size(mu1,1);\n\n%If only the covariance matrices are given.\nif(nargin<7||isempty(L2))\n L2=zeros(xDim,xDim,Nr);\n for i=1:Nr\n L2(:,:,i)=chol(P2(:,:,i),'lower');\n end\nend\n\n%If only the lower-triangular Cholesky decompositions of the covariance\n%matrices are given.\nif(isempty(P2))\n P2=zeros(xDim,xDim,Nr);\n for i=1:Nr\n P2(:,:,i)=L2(:,:,i)*L2(:,:,i)';\n end\nend\n\n%The formulae for the gradient of Jhr and Jrr are given in Equation 3.45 of\n%Section 3.3.3.3 of [1].\ngradJhr=zeros(xDim,xDim,Nr);\ngradJrr=zeros(xDim,xDim,Nr);\n\nfor j=1:Nr\n for i=1:Nh\n diff=mu1(:,i)-mu2(:,j);\n PSum=P1(:,:,i)+P2(:,:,j);\n PSumInv=inv(PSum);\n \n gradJhr(:,:,j)=gradJhr(:,:,j)+w1(i)*PDFVals12(i,j)*PSumInv*(diff*diff'-PSum)*PSumInv*L2(:,:,j);\n end\n gradJhr(:,:,j)=w2(j)*gradJhr(:,:,j);\nend\n\nfor j=1:Nr\n for i=1:Nr\n diff=mu2(:,i)-mu2(:,j);\n PSum=P2(:,:,i)+P2(:,:,j);\n PSumInv=inv(PSum);\n \n gradJrr(:,:,j)=gradJrr(:,:,j)+w2(i)*PDFVals22(i,j)*PSumInv*(diff*diff'-PSum)*PSumInv*L2(:,:,j);\n end\n gradJrr(:,:,j)=2*w2(j)*gradJrr(:,:,j);\nend\n\ngradISE=gradJrr-2*gradJhr;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Clustering_and_Mixture_Reduction/GaussMixISELTCovGrads.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6065120111762465}} {"text": "function [ qa, qb, ival ] = box_segment_clip_2d ( p1, p2, pa, pb )\n\n%*****************************************************************************80\n%\n%% BOX_SEGMENT_CLIP_2D uses a box to clip a line segment in 2D.\n%\n% Discussion:\n%\n% A box is assumed to be a rectangle with sides aligned on coordinate\n% axes. It can be described by its low and high corner, P1 and P2:\n%\n% points P so that P1(1:DIM_NUM) <= P(1:DIM_NUM) <= P2(1:DIM_NUM).\n%\n% Thanks to Dennis Strelow for pointing out a typographical error, \n% 13 July 2005.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2), P2(2), the low and high corners of the box.\n%\n% Input, real PA(2), PB(2), the endpoints of the line segment.\n%\n% Output, real QA(2), QB(2), the clipped coordinates.\n%\n% Output, integer IVAL:\n% -1, no part of the line segment is within the box.\n% 0, no clipping was necessary. The line segment is entirely within\n% the box.\n% 1, PA was clipped.\n% 2, PB was clipped.\n% 3, PA and PB were clipped.\n%\n dim_num = 2;\n\n l1 = 0;\n l2 = 0;\n\n qa(1:dim_num) = pa(1:dim_num);\n qb(1:dim_num) = pb(1:dim_num);\n%\n% Require that XMIN <= X.\n%\n if ( qa(1) < p1(1) & qb(1) < p1(1) )\n ival = -1;\n return\n end\n\n if ( qa(1) < p1(1) & p1(1) <= qb(1) )\n q(1) = p1(1);\n q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );\n qa(1:2) = q(1:2);\n l1 = 1;\n elseif ( p1(1) <= qa(1) & qb(1) < p1(1) )\n q(1) = p1(1);\n q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );\n qb(1:2) = q(1:2);\n l2 = 1;\n end\n%\n% Require that X <= XMAX.\n%\n if ( p2(1) < qa(1) & p2(1) < qb(1) )\n ival = -1;\n return\n end\n\n if ( p2(1) < qa(1) & qb(1) <= p2(1) )\n q(1) = p2(1);\n q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );\n qa(1:2) = q(1:2);\n l1 = 1;\n elseif ( qa(1) <= p2(1) & p2(1) < qb(1) )\n q(1) = p2(1);\n q(2) = qa(2) + ( qb(2) - qa(2) ) * ( q(1) - qa(1) ) / ( qb(1) - qa(1) );\n qb(1:2) = q(1:2);\n l2 = 1;\n end\n%\n% Require that YMIN <= Y.\n%\n if ( qa(2) < p1(2) & qb(2) < p1(2) )\n ival = -1;\n return\n end\n\n if ( qa(2) < p1(2) & p1(2) <= qb(2) )\n q(2) = p1(2);\n q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );\n qa(1:2) = q(1:2);\n l1 = 1;\n elseif ( p1(2) <= qa(2) & qb(2) < p1(2) )\n q(2) = p1(2);\n q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );\n qb(1:2) = q(1:2);\n l2 = 1;\n end\n%\n% Require that Y <= YMAX.\n%\n if ( p2(2) < qa(2) & p2(2) < qb(2) )\n ival = -1;\n return\n end\n\n if ( p2(2) < qa(2) & qb(2) <= p2(2) )\n q(2) = p2(2);\n q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );\n qa(1:2) = q(1:2);\n l1 = 1;\n elseif ( qa(2) <= p2(2) & p2(2) < qb(2) )\n q(2) = p2(2);\n q(1) = qa(1) + ( qb(1) - qa(1) ) * ( q(2) - qa(2) ) / ( qb(2) - qa(2) );\n qb(1:2) = q(1:2);\n l2 = 1;\n end\n\n ival = 0;\n\n if ( l1 )\n ival = ival + 1;\n end\n\n if ( l2 )\n ival = ival + 2;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/box_segment_clip_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6065120019989345}} {"text": "function mat_time = jd2MatTime (jdate)\n\n% convert Julian date to Gregorian (calendar) date\n\n% input\n\n% jdate = julian day\n\n% output\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% note: day may include fractional part\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\njd = jdate;\n\nz = fix(jd + .5);\nfday = jd + .5 - z;\n\nif (fday < 0)\n fday = fday + 1;\n z = z - 1;\nend\n\nif (z < 2299161)\n a = z;\nelse\n alpha = floor((z - 1867216.25) / 36524.25);\n a = z + 1 + alpha - floor(alpha / 4);\nend\n\nb = a + 1524;\nc = fix((b - 122.1) / 365.25);\nd = fix(365.25 * c);\ne = fix((b - d) / 30.6001);\nday = b - d - fix(30.6001 * e) + fday;\n\nif (e < 14)\n month = e - 1;\nelse\n month = e - 13;\nend\n\nif (month > 2)\n year = c - 4716;\nelse\n year = c - 4715;\nend\n\nmat_time = datenum(year, month, day, 0, 0, 0);\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/time/jd2MatTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6064182897271292}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_khwarizmian ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_KHWARIZMIAN converts a JED to a Khwarizmian YMDF date.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm F,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 324-325.\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F,\n% the YMDF date.\n%\n\n%\n% Determine the computational date (Y'/M'/D').\n%\n j = floor ( jed + 0.5 );\n f = ( jed + 0.5 ) - j;\n\n j_prime = j + 317;\n\n y_prime = floor ( j_prime / 365 );\n t_prime = mod ( j_prime, 365 );\n m_prime = floor ( t_prime / 30 );\n d_prime = mod ( t_prime, 30 );\n%\n% Convert the computational date to a calendar date.\n%\n d = d_prime + 1;\n m = mod ( m_prime, 13 ) + 1;\n y = y_prime - 5348 + floor ( ( 13 - m ) / 13 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/calpak/jed_to_ymdf_khwarizmian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6064182671572671}} {"text": "function [x, y] = trans_cam2fisheye(xcam, ycam, zcam, M, D)\nfx = M(1,1); fy = M(2,2);\ncx = M(1,3); cy = M(2,3);\nif D ~= 0\n k1 = D(1); k2 = D(2); k3 = D(3); k4 = D(4);\nend\n\nrcam = sqrt(xcam .^ 2 + ycam .^ 2 + zcam .^ 2) ;\nalpha = acos(zcam ./ rcam) ;\n\nif D ~= 0\n alpha_2 = alpha .^ 2;\n k_radial = 1 + k1 * alpha_2 + k2 * alpha_2.^2 + k3 * alpha_2.^3 + k4 * alpha_2.^4;\n alpha_d = alpha .* k_radial;\nelse\n alpha_d = alpha;\nend\n\nrcam_xy = sqrt(xcam.^2 + ycam.^2);\nalpha_d_x = xcam ./ rcam_xy .* alpha_d;\nalpha_d_y = ycam ./ rcam_xy .* alpha_d;\n\nx = alpha_d_x .* fx + cx ;\ny = alpha_d_y .* fy + cy ;\n\nend", "meta": {"author": "gain2217", "repo": "Robust_Elastic_Warping", "sha": "36ad3cb2f709fbea17225642ea1fa7b083924fd9", "save_path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping", "path": "github-repos/MATLAB/gain2217-Robust_Elastic_Warping/Robust_Elastic_Warping-36ad3cb2f709fbea17225642ea1fa7b083924fd9/two_views/transforms/trans_cam2fisheye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.606393903865762}} {"text": "function [M] = spm_nwpost (M,w)\n% Get posterior distribution over m,Lambda\n% FORMAT [M] = spm_nwpost (M,w)\n%\n% M M.prior - params of Normal-Wishart prior\n% w Multivariate data samples\n%\n% M M.post - params of Normal-Wishart posterior\n%\n% Bernardo and Smith, Bayesian Theory, 2000 (p.441)\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_nwpost.m 6548 2015-09-11 12:39:47Z will $\n\nmw=mean(w,2);\nSw=cov(w',1);\n\nN=size(w,2);\n\nprior=M.prior;\nP=prior.P;\na0=prior.a;\nB0=prior.B;\nbeta0=prior.beta;\nm0=prior.m;\n\npost.beta=beta0+N;\npost.m=(beta0*m0+N*mw)/post.beta;\n\npost.a=a0+N/2;\npost.B=B0+0.5*N*Sw+0.5*(beta0*N/post.beta)*(mw-m0)*(mw-m0)';\npost.a=a0+N/2;\n\n% Quantities for predictive density (over new samples)\npost.mu_w=post.m;\nw_s=(post.beta/(post.beta+1))*(post.a-0.5*(P-1));\npost.Lambda_w=w_s*inv(post.B);\npost.v_w=2*post.a-P+1;\n\n% Wrap up\npost.P=P;\npost.N=N;\nM.post=post;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mci/inference/spm_nwpost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.6063938917372615}} {"text": "function [ a, seed ] = r8ci_random ( n, seed )\n\n%*****************************************************************************80\n%\n%% R8CI_RANDOM randomizes a R8CI matrix.\n%\n% Discussion:\n%\n% The R8CI storage format is used for an N by N circulant matrix.\n% An N by N circulant matrix A has the property that the entries on\n% row I appear again on row I+1, shifted one position to the right,\n% with the final entry of row I appearing as the first of row I+1.\n% The R8CI format simply records the first row of the matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real A(N), the R8CI matrix.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n for i = 1 : n\n [ a(i), seed ] = r8_uniform_01 ( seed );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8ci_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6063279412641618}} {"text": "% MATLAB computation of pulse transformer model - DS Method\n% File: c:\\M_files\\shortcuts\\xfrmrds.m\n% 9/19/02; 4/17/04; 2/15/07\n% \ntic;clc;clear;\nK=1e3;pF=1e-12;mH=1e-3;uH=1e-6;ns=1e-9;ps=1e-12; % unit suffixes\n%\n% Components\n%\nR1=10;R2=1.5;R3=20*K;R4=1.5;R5=1*K;R6=0.5;R7=1;\nC1=20*pF;C2=5*pF;C3=20*pF;L1=1*uH;L2=2*mH;L3=1*uH;\n%\n% Get A, B, D, & E arrays; this function called only once.\n%\nNom=[R1 R2 R3 R4 R5 R6 R7 C1 C2 C3 L1 L2 L3];\n[A,B,D,E,I]=tfrmr2(Nom);\n%\n% * * * * * * * * * * * * Frequency response * * * * * * * * * * * *\n%\nEin=10; % Change Ein from 1V to 10V.\n%\nBF=2;ND=6;PD=50;NP=ND*PD+1;L=linspace(BF,BF+ND,NP);\n%\n% Since the output is vC3, we dont need the D and E arrays. \n% The cv output below is [vC1 vC2 vC3 iL1 iL2 iL3]'\n% (a column vector). Hence we need vC3 or cv(3).\n%\nfor i=1:NP\n F=10^L(i);s=2*pi*F*j;\n cx=(s*I-A)\\B*Ein;\n% cy=D*cx+E*Ein; % cy not used \n Vo=abs(cx(3)); % vC3 = Vo\n Vf(i)=20*log10(Vo); \nend\n%\n% * * * * * * * * * * * * * Transient response * * * * * * * * * * * \n%\nTx=1/max(max(abs(A)));\ndisp('Shortest circuit time constant');Tx\n%Per=input('Sweep time? (sec)');\n% set Sweep time to 200ns = 200e-9 to match Spice run.\nPer=200*ns;\nkmax=1e5; % kmax increased due to fast time constant Tx\ndt = 2*ps\nN=6;\n%dt=Per/kmax;N=6;\nt1=linspace(0,Per,kmax);IV=zeros(N,kmax);\n%\n% input ramp parameters\n%\np=Ein/(5*dt);b=6*dt;pw=5e4*dt;c=pw+6*dt;d=pw+11*dt;\nEa1=ramp1(p,t1(1),dt)-ramp1(p,t1(1),b)-ramp1(p,t1(1),c)+ramp1(p,t1(1),d);\n% initialize k = 1\nIV(:,1)=B*Ea1*dt;\n%\n% iterate for k = 2,3,...kmax\n%\nfor k=2:kmax\n Eak=ramp1(p,t1(k),dt)-ramp1(p,t1(k),b)-ramp1(p,t1(k),c)+ramp1(p,t1(k),d);\n IV(:,k)=A*IV(:,k-1)*dt+B*Eak*dt+IV(:,k-1);\nend\n%\n% Plot frequency response\n%\nsubplot(2,1,1)\nh=plot(L,Vf,'k');\nset(h,'LineWidth',2);\ngrid on;\naxis([BF BF+ND -40 30]);\nXT=linspace(BF,BF+ND,7);\nset(gca,'xtick',XT);\nylabel('dBV');title('AC Output Vc3');\nxlabel('Log Freq(Hz)');\n%\n% Plot time response\n%\nsubplot(2,1,2)\nh=plot(t1/ns,IV(1,:),'k',t1/ns,IV(3,:),'r');\nset(h,'LineWidth',2);\naxis auto\ngrid on;ylabel('Volts');title('Transient response, Vc1 & Vc3');\nxlabel('nsec');\nlegend('Vc1','Vc3');\n\nfigure(1) % display plot on screen.\n%\ndisp(' ');disp('Execution time in seconds');\nET=toc\n \n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/xfrmrds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.6063086027936984}} {"text": "function poly2 = resamplePolylineByLength(poly, step)\n%RESAMPLEPOLYLINEBYLENGTH Resample a polyline with a fixed sampling step.\n%\n% RES = resamplePolyline(POLY, STEP)\n% Resample the input polyline POLY by distributing new vertices on the\n% original polyline such that the (curvilinear) distance between the new\n% vertices is approximately equal to STEP. \n%\n% Example\n% poly = [0 10;0 0;10 0; 10 10; 20 10;20 0];\n% figure; drawPolyline(poly, 'k');\n% poly2 = resamplePolylineByLength(poly, 4);\n% hold on; \n% drawPolyline(poly2, 'm');\n% drawPoint(poly2, 'mo');\n% axis equal; axis([-10 30 -10 20]);\n% legend('Original polyline', 'Resampled polyline');\n%\n% See also \n% polygons2d, drawPolyline, resamplePolygon\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2011-12-09, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% parametrisation of the curve\ns = parametrize(poly);\n\n% compute the number of points for sampling the polygon\n% (equal to the number of segments plus one)\nLmax = s(end);\nn = round(Lmax / step) + 1;\n\n% distribute N points equally spaced\npos = linspace(0, Lmax, n);\n\npoly2 = zeros(n, size(poly, 2));\nfor i = 1:n\n % index of surrounding vertices before and after\n ind0 = find(s <= pos(i), 1, 'last');\n ind1 = find(s >= pos(i), 1, 'first');\n \n if ind0 == ind1\n % get position of a vertex in input polyline\n poly2(i, :) = poly(ind0, :);\n continue;\n end\n \n % position of surrounding vertices\n pt0 = poly(ind0, :);\n pt1 = poly(ind1, :);\n \n % weights associated to each neighbor\n l0 = pos(i) - s(ind0);\n l1 = s(ind1) - pos(i);\n \n % linear interpolation of neighbor positions\n if (l0 + l1) > Lmax * 1e-12\n poly2(i, :) = (pt0 * l1 + pt1 * l0) / (l0 + l1);\n else\n % if neighbors are too close, do not use interpolation\n poly2(i, :) = pt0;\n end\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/polygons2d/resamplePolylineByLength.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.606288373084762}} {"text": "function [ fea, out ] = ex_natural_convection( varargin )\n%EX_NATURAL_CONVECTION 2D Example for natural convection of air in a square cavity.\n%\n% [ FEA, OUT ] = EX_NATURAL_CONVECTION( VARARGIN ) Sets up and solves a natural convection\n% benchmark problem. Reference solutions are for example reported in G. Davis\n% \"Natural convection of air in a square cavity a bench mark numerical solution\",\n% IJNMF vol. 3, 249-254 (1983).\n%\n% Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% Ra scalar {1e3} Rayleigh number\n% Pr scalar {0.71} Prandtl number\n% l scalar {1} Side length of cavity\n% igrid scalar 0/{1} Cell type (0=quadrilaterals, 1=triangles)\n% hmax scalar {0.05} Max grid cell size\n% sf_u string {sflag2} Shape function for velocity\n% sf_p string {sflag1} Shape function for pressure\n% sf_T string {sflag2} Shape function for temperature\n% iphys scalar 0/{1} Use physics mode to define problem (=1)\n% iplot scalar 0/{1} Plot solution and error (=1)\n% .\n% Output Value/(Size) Description\n% -----------------------------------------------------------------------------------\n% fea struct Problem definition struct\n% out struct Output struct\n\n% Copyright 2013-2022 Precise Simulation, Ltd.\n\n\ncOptDef = { ...\n 'Ra', 1e3; ...\n 'Pr', 0.71; ...\n 'l', 1; ...\n 'igrid', 0; ...\n 'hmax', 0.05; ...\n 'sf_u', 'sflag2'; ...\n 'sf_p', 'sflag1'; ...\n 'sf_T', 'sflag2'; ...\n 'iphys', 1; ...\n 'iplot', 1; ...\n 'tol', 0.1; ...\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n% Reference values.\nRa_ref = [ 1e3 1e4 1e5 1e6 ];\nu_max_ref = [ 3.649 16.178 34.73 64.63 ];\ny_max_ref = [ 0.813 0.823 0.855 0.850 ];\nv_max_ref = [ 3.697 19.617 68.59 219.36 ];\nx_max_ref = [ 0.178 0.119 0.066 0.0379 ];\nNu_mean_ref = [ 1.118 2.243 4.519 8.800 ];\n\n% Model parameters.\nRa = opt.Ra; % Rayleigh number.\nPr = opt.Pr; % Prandtl number.\nl = opt.l; % Length of rectangular domain.\nsf_u = opt.sf_u; % FEM shape function type for velocity.\nsf_p = opt.sf_p; % FEM shape function type for pressure.\nsf_T = opt.sf_T; % FEM shape function type for temperature.\n\n\n% Geometry definition.\nfea.sdim = { 'x' 'y' };\nfea.geom.objects = { gobj_rectangle( 0, l, 0, l ) };\n\n\n% Grid generation.\nif( opt.igrid<=0 )\n fea.grid = rectgrid( round(l/opt.hmax), round(l/opt.hmax), [0 l;0 l] );\n if( opt.igrid<0 )\n fea.grid = quad2tri(fea.grid);\n end\nelse\n fea.grid = gridgen( fea, 'hmax', opt.hmax, 'fid', fid );\nend\n\n\n% Boundary conditions.\nn_bdr = max(fea.grid.b(3,:)); % Increment number of boundaries.\ndtol = opt.hmax;\nib_l = findbdr( fea, ['x<',num2str(dtol)] ); % Right boundary number.\nib_r = findbdr( fea, ['x>',num2str(l-dtol)] ); % Left boundary number.\nib_b = findbdr( fea, ['y<',num2str(dtol)] ); % Bottom boundary number.\nib_t = findbdr( fea, ['y>',num2str(l-dtol)] ); % Top boundary number.\n\n% Add pressure point constraint on point closest to origin.\n[~,ix] = min( fea.grid.p(1,:).^2 + fea.grid.p(2,:).^2 );\nfea.pnt.index = ix;\nfea.pnt.type = 'constr';\nfea.pnt.dvar = 'p';\nfea.pnt.expr = 0';\n\n\n% Problem definition.\nif ( opt.iphys==1 )\n\n fea = addphys(fea,@navierstokes); % Add Navier-Stokes equations physics mode.\n fea.phys.ns.eqn.coef{2,end} = { Pr };\n fea.phys.ns.eqn.coef{4,end} = { [num2str(Ra*Pr),'*T'] };\n fea.phys.ns.sfun = { sf_u sf_u sf_p }; % Set shape functions.\n\n fea = addphys(fea,@heattransfer); % Add heat transfer physics mode.\n fea.phys.ht.sfun = { sf_T };\n fea.phys.ht.eqn.coef{4,end} = { fea.phys.ns.dvar{1} };\n fea.phys.ht.eqn.coef{5,end} = { fea.phys.ns.dvar{2} };\n fea.phys.ht.bdr.sel([ib_l ib_r]) = 1;\n fea.phys.ht.bdr.coef{1,end}{ib_l} = 1;\n\n fea = parsephys(fea); % Check and parse physics modes.\n\nelse\n\n fea.dvar = { 'u' 'v' 'p' 'T' }; % Dependent variable name.\n fea.sfun = { sf_u sf_u sf_p sf_T }; % Shape function.\n\n % Define equation system.\n cvelx = fea.dvar{1}; % Convection velocities.\n cvely = fea.dvar{2};\n fea.eqn.a.form = { [2 3 2 3;2 3 1 1] [2;3] [1;2] []; ...\n [3;2] [2 3 2 3;2 3 1 1] [1;3] []; ...\n [2;1] [3;1] [] []; ...\n [] [] [] [2 3 2 3;2 3 1 1] };\n fea.eqn.a.coef = { {2*Pr Pr cvelx cvely} Pr -1 []; ...\n Pr {Pr 2*Pr cvelx cvely} -1 []; ...\n 1 1 [] []; ...\n [] [] [] {1 1 cvelx cvely} };\n fea.eqn.f.form = { 1 1 1 1 };\n fea.eqn.f.coef = { 0 [num2str(Ra*Pr),'*',fea.dvar{4}] 0 0 };\n\n % Define boundary conditions.\n fea.bdr.d = cell(4,n_bdr);\n [fea.bdr.d{1:2,:}] = deal(0);\n\n fea.bdr.d{4,ib_l} = 1;\n fea.bdr.d{4,ib_r} = 0;\n\n fea.bdr.n = cell(4,n_bdr);\n [fea.bdr.n{4,[ib_t ib_b n_bdr]}] = deal(0);\n [fea.bdr.n{3,setdiff(1:n_bdr,n_bdr)}] = deal(0);\n [fea.bdr.n{1:2,n_bdr}] = deal(0);\n\nend\n\n\n% Parse and solve problem.\nfea = parseprob(fea); % Check and parse problem struct.\nfea.sol.u = solvestat(fea,'fid',fid); % Call to stationary solver.\n\n\n% Postprocessing.\nif ( opt.iplot>0 )\n figure\n subplot(1,2,1)\n postplot(fea,'surfexpr','sqrt(u^2+v^2)')\n title('Velocity field')\n subplot(1,2,2)\n postplot(fea,'surfexpr','T')\n title('Temperature')\nend\n\n\n% Error checking.\nout.err = nan;\nout.pass = nan;\niref = find( Ra==Ra_ref );\nif ( ~isempty(iref) )\n n_evalution_points = 3*l/opt.hmax;\n x_eval = linspace( 0, l, n_evalution_points );\n x_mid = l/2*ones( 1, n_evalution_points );\n\n u_eval = evalexpr( 'u', [x_mid; x_eval], fea );\n [u_max,ix] = max( u_eval );\n y_max = x_eval( ix );\n\n v_eval = evalexpr( 'v', [x_eval; x_mid], fea );\n [v_max,ix] = max( v_eval );\n x_max = x_eval( ix );\n\n Nu_mean = abs( intbdr( 'Tx', fea, 1, 2 ) + intbdr( 'Tx', fea, 2, 2 ) )/2;\n\n out.u_max = u_max;\n out.y_max = y_max;\n out.v_max = v_max;\n out.x_max = x_max;\n out.Nu_mean = Nu_mean;\n\n out.err = [ abs(u_max_ref(iref)-u_max)/u_max_ref(iref);\n abs(y_max_ref(iref)-y_max)/y_max_ref(iref);\n abs(v_max_ref(iref)-u_max)/v_max_ref(iref);\n abs(x_max_ref(iref)-x_max)/x_max_ref(iref);\n abs(Nu_mean_ref(iref)-Nu_mean)/Nu_mean_ref(iref) ];\n out.pass = all( out.err .1*xgg);\ngx=(HX.*I); gy=(HY.*I);\nG=ref_image';\nxg=max(max(G)); ng=min(min(G)); cg=256/(xg-ng);\nimage(x,y,256-cg*(G-ng)); axis image; axis xy\nhold on\nquiver(x(:)*ones(1,NY),ones(NX,1)*y,gx,gy,2)\nxlabel('Spatial Domain X')\nylabel('Spatial Domain Y')\ntitle('Motion Vector Image')\nprint P8.9.ps\nhold off\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2188-synthetic-aperture-radar-signal-processing-with-matlab-algorithms/soumekh/sig_sub_b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6062785864843347}} {"text": "% minCEntropy clustering: partitional clustering using the minimum conditional Entropy objective\n%(C) Nguyen Xuan Vinh, 2010. Contact: vinh.nguyenx@gmail.com, vinh.nguyen@monash.edu\n%Input:\n% a: data, rows for objects, cols for features\n% K: number of desired clusters\n% sigma_factor: default kernel with sigma_0, specify sigma_factor to obtain\n% a new kernel width, sigma=sigma_0/sigma_factor\n% n_run: optional, number of runs, default: 1\n% init_mem: optional, initial clustering\n%Output:\n% max_mem: best clustering over n_run runs\n% max_obj: max objective value\n% S: kernel similarity matrix\n%Reference:\n% [1] N. X. Vinh, Epps, J., \"minCEntropy: a Novel Information Theoretic Approach for the Generation of\n% Alternative Clusterings,\" in IEEE Int. Conf. on Data Mining (ICDM) 2010.\n%Example:\n%\n% X = [randn(100,2)+5;randn(100,2)+[5*ones(100,1) -5*ones(100,1)]; randn(100,2)-5;randn(100,2)+[-5*ones(100,1) 5*ones(100,1)]];\n% [mem]=minCEntropy(X,2,1,10); %% run minCEntropy+ 10 times,\n% %% with K=2, sigma=sigma_0\n% figure;scatter(X(:,1),X(:,2),30,mem);title('minCEntropy clustering');\n\nfunction [max_mem,max_obj,all_mem,S]=minCEntropy(a,K,sigma_factor,n_run,SS,init_mem)\n\nif nargin<3 sigma_factor=1;end;\nif nargin<4 n_run = 1;end;\nif nargin<6 hasC=-1;end;\n \n[n dim]=size(a);\n\nif nargin<5\n SE=sqdistance(a');\n sigma0=sum(sum(sqrt(SE)))/n^2/2; %1/2 average pairwise distance\n sigma0=real(sigma0);\n sigma=sigma0/sigma_factor;\n sig2=4*sigma^2;\n S=exp(-SE/sig2);\nelse\n S=SS; %preprovided kernel matrix\nend\nSpc=zeros(n,K); %point->cluster similarity\nG=zeros(1,K); %cluster quality\nNj=zeros(1,K); %cluster size\n \nmax_obj=-inf;%best objective\nmax_mem=[];\nall_mem=zeros(n_run,n);\n\n\nfor run=1:n_run\n change_count=0;\n \n if hasC==-1\n %initialization with Kmeans, using only 1 iteration\n mem=kmeans(a,K,'Maxiter',0,'EmptyAction','singleton');\n %random initialization\n %mem=round(rand(1,n)*(K-1))+1;\n else\n n_run=1;\n mem=init_mem;\n end;\n\n setup();\n\n obj=sum(G./Nj);\n isContinue=1;\nwhile isContinue\nisContinue=0;\nfor i=1:n\n\n cur_clus=mem(i); \n %check point->cluster similarity\n max_inc=-inf; % maximum objective increase\n for new_clus=1:K\n if new_clus==cur_clus continue;end; \n cond2=G(cur_clus)/(Nj(cur_clus)-1)/Nj(cur_clus)-G(new_clus)/(Nj(new_clus)+1)/Nj(new_clus)-2*Spc(i,cur_clus)/(Nj(cur_clus)-1)+2*Spc(i,new_clus)/(Nj(new_clus)+1);\n if cond2>max_inc\n max_inc=cond2;\n max_clus=new_clus;\n end\n end\n \n if(max_inc>0) %make change \n new_clus=max_clus;\n change_count=change_count+1;\n isContinue=1;\n \n %update tables \n for t=1:n\n if t==i continue;end;\n Spc(t,cur_clus)=Spc(t,cur_clus)-S(t,i);\n Spc(t,new_clus)=Spc(t,new_clus)+S(t,i);\n end\n \n G(cur_clus)=G(cur_clus)-2*Spc(i,cur_clus);\n G(new_clus)=G(new_clus)+2*Spc(i,new_clus);\n \n %update membership\n mem(i)=new_clus; \n Nj(cur_clus)=Nj(cur_clus)-1;\n Nj(new_clus)=Nj(new_clus)+1;\n \n CC(i,cur_clus)=false;\n CC(i,new_clus)=true;\n\n cur_clus=new_clus;\n \n change_count=change_count+1;\n \n end %make change\n \nend%for i=1:n one round through the data set\nend%while point can still move\n\nobj=sum(G./Nj);\nfprintf('Sigma factor: %d, changes: %d, quality: %f\\n',sigma_factor,change_count,obj);\nif max_obj>>>>>>>Finished clustering. best quality: %f\\n',max_obj);\nmem=max_mem;\n\n%----------end main function------------------\n function setup() \n for i=1:n\n for j=1:K\n Spc(i,j)=sum(S(i,mem==j)); % point -> cluster similarity\n end\n end\n\n for j=1:K\n G(j)=sum(Spc(mem==j,j)); \n Nj(j)=sum(mem==j);\n end\n end\n\nend%main function", "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/32994-the-mincentropy-algorithm-for-alternative-clustering/minCEntropy/minCEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6062785786478445}} {"text": "function [FV] = mesh_shrink(FV,origin,dist),\n\n% mesh_shrink - implode vertices of mesh by specific distance\n%\n% FV = mesh_shrink(FV,origin,dist)\n%\n% FV is a struct with fields:\n%\n% FV.vertices - Nx3 matrix of Cartesian vertex coordindates (X,Y,Z)\n% FV.faces - Mx3 matrix of triangulation of FV.vertices\n%\n% origin - 1x3 row vector, usually (0,0,0)\n%\n% dist - how far to implode the mesh toward the origin;\n% this distance is relative to current distance from\n% the origin, not the total distance from the origin.\n% \n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence: GNU GPL, no implied or express warranties\n% History: 10/2002, Darren.Weber_at_radiology.ucsf.edu\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n xo = origin(1); yo = origin(2); zo = origin(3);\n \n Nvert = size(FV.vertices,1);\n \n fprintf('...mesh implosion...'); tic;\n \n for v = 1:Nvert,\n \n x = FV.vertices(v,1);\n y = FV.vertices(v,2);\n z = FV.vertices(v,3);\n \n % Find direction cosines for line from centre to vertex\n d = sqrt( (x-xo)^2 + (y-yo)^2 + (z-zo)^2 );\n \n l = (x-xo)/d; % cos alpha\n m = (y-yo)/d; % cos beta\n n = (z-zo)/d; % cos gamma\n \n % now decrease d by dist\n d = d - dist;\n \n % locate vertex at this new distance\n x = (l * d) + xo;\n y = (m * d) + yo;\n z = (n * d) + zo;\n \n FV.vertices(v,:) = [ x y z ];\n end\n \n t = toc; fprintf('...done (%5.2f sec)\\n',t);\n \nreturn\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/external/bioelectromagnetism_ligth/mesh_shrink.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6060722704232495}} {"text": "function N = delaunay_neighbors(q,P)\n % DELAUNAY_NEIGHBORS Find the Delaunay neighbors of q in a list of points P.\n % \n % N = delaunay_neighbors(q,P)\n % \n % Experimentally for uniformly randomly distributed points the number of\n % iterations is O(|P|) and specifically seems to do 1.355*|P| \"iterations\".\n % There's a sort on the angles so at best this implementation is O(|P|log|P|),\n % but it's very simple... so maybe the constants and overheads are much\n % smaller than doing a full Delaunay triangulation.\n %\n % Inputs:\n % q 2D position of query point\n % P #P by 2 list of nearby points\n % Outputs:\n % N #N list of indices into P of neighboring points\n %\n\n % Example:\n % q = [0 0];\n % P = rand(60,2)*2-1;\n % N = delaunay_neighbors(q,P);\n % Nm = find(adjacency_matrix(delaunay([P;q]))*sparse(size(P,1)+1,1,1,size(P,1)+1,1));\n % assert(isempty(setxor(N,Nm)));\n\n \n % 2----1\n % |θ₂ / \\\n % | / \\\n % | / \\\n % |/θq θ₀\\\n % q---------0\n %% Angle at p0-q-p1\n %thq = th(p1)-th(p0);\n %% Law of sines: θq/|01| = θ₀/|q1|\n %% θ₀ = |q1|*θq/|01|\n %th0 = l(p1)*thq/sqrt(sum((P(p0,:)-P(p1,:)).^2,2));\n % Vector from p0 to p1\n\n % Inputs:\n % P #P by 2 list of nearby points\n % l #P by 2 list of distances to origin: l = normrow(P)\n % p0 first 2d point\n % p1 second 2d point\n % p2 third 2d point\n % Outputs:\n % flag whether edge from origin to p1 forms a Delaunay edge between points\n % p1 and p2.\n % \n isdel = @(P,l,p0,p1,p2) ...\n acos((-P(p0,:)/l(p0))*(((P(p1,:)-P(p0,:))/sqrt(sum((P(p1,:)-P(p0,:)).^2,2)))')) + ...\n acos((-P(p2,:)/l(p2))*(((P(p1,:)-P(p2,:))/sqrt(sum((P(p1,:)-P(p2,:)).^2,2)))')) <= pi;\n\n %% Or perhaps: http://stackoverflow.com/a/8523979\n %function f = isdel(P,l,p0,p1,p2)\n % f = acos((-P(p0,:)/l(p0))*(((P(p1,:)-P(p0,:))/sqrt(sum((P(p1,:)-P(p0,:)).^2,2)))')) + ...\n % acos((-P(p2,:)/l(p2))*(((P(p1,:)-P(p2,:))/sqrt(sum((P(p1,:)-P(p2,:)).^2,2)))')) <= pi;\n % % Shewchuk's incircle test via determinant\n % h(1,:) = [P(p0,:) 1];\n % h(2,:) = [P(p1,:) 1];\n % h(3,:) = [P(p2,:) 1];\n % d = det([ ...\n % q(1) q(2) q(1)^2+q(2)^2 1 ; ...\n % h(1,1) h(1,2) h(1,1)^2+h(1,2)^2 h(1,3) ; ...\n % h(2,1) h(2,2) h(2,1)^2+h(2,2)^2 h(2,3) ; ...\n % h(3,1) h(3,2) h(3,1)^2+h(3,2)^2 h(3,3) ; ...\n % ]);\n % if f ~= (d<0)\n % fprintf('%d %d\\n',f,d<0);\n % pause\n % end\n % %if any(l([p0 p1 p2]) > 1e3)\n % %%if all((l([p0 p1 p2])>1e3)==[0;1;0]) && f\n % % fprintf('%d %d %d --> %d\\n',l([p0 p1 p2]) > 1e5,f);\n\n % % clf;\n % % hold on;\n % % tsurf([1 2 3;1 3 4],[0 0;P([p0 p1 p2],:)],'FaceColor','none','LineWidth',2,'EdgeColor','b');\n % % tsurf([1 2 4;1 4 2],[0 0;P([p0 p1 p2],:)],'FaceColor','none','LineWidth',1,'EdgeColor','r');\n % % scatter([0;P([p0 p1 p2],1)],[0;P([p0 p1 p2],2)],'.','SizeData',500);\n % % text([0;P([p0 p1 p2],1)],[0;P([p0 p1 p2],2)],['q';num2str((0:2)')],'FontSize',20);\n % % hold off;\n % % axis equal;\n % % axis([-3 3 -3 3]);\n % % drawnow;\n\n % % pause\n % %end\n %end\n\n % Subtract q from P and q\n P = bsxfun(@minus,P,q);\n q = [0 0];\n % Compute distances to origin\n l = sqrt(sum(P.^2,2));\n\n % Handle case where q is on the convex hull. \n % TODO: Shouldn't _always_ have to added bounding points.\n max_l = max(l);\n % This is HUGE number is a hack. Should handle boundary \"protectors\" explicitly then.\n % Something like angle between:\n % finite-∞-finite --> 0 \n % ∞-finite-∞ --> pi\n % finite-finite-∞ --> ?\n % Maybe this is a case for homogenous coordinates?\n s = 1e10*max_l;\n extra = [size(P,1)+(1:4)];\n P = [P;s*[1 1;1 -1;-1 -1;-1 1]];\n l = [l;repmat(s*sqrt(2),4,1)];\n assert(size(P,1)==size(l,1));\n\n % Number of input points\n n = size(P,1);\n % Compute angle with x-axis\n th = atan2(P(:,2),P(:,1));\n [th,I] = sort(th);\n [~,closest] = min(l);\n\n % Reorder so that closest comes first\n I = I([find(I==closest):end 1:find(I==closest)-1]);\n % Assumption: closest point must be Delaunay neighbor\n N = [I(1)];\n % Consider next two points\n p1i = 2;\n p2i = 3;\n p1 = I(p1i);\n p2 = I(p2i);\n p0 = N(end);\n k = 0;\n while true\n k = k+1;\n % is the edge q-p1 between p0 and p2 is delaunay\n if isdel(P,l,p0,p1,p2)\n % push p1 onto \"keepers stack\" N\n N = [N;p1];\n else\n % edge q-p1 between p0 and p2 is **not** delaunay\n % first try to work backward until finding delaunay\n while numel(N)>1 && ~isdel(P,l,N(end-1),N(end),p2)\n % MOVE BACKWARD\n k = k+1;\n p0 = N(end-1);\n p1 = N(end);\n N = N(1:end-1);\n end\n end\n if p1i == n\n break;\n end\n % MOVE FORWARD\n p1i = mod(p1i,n)+1;\n p2i = mod(p2i,n)+1;\n p1 = I(p1i);\n p2 = I(p2i);\n p0 = N(end);\n end\n N = setdiff(N,size(P,1)-(0:3));\n P = P(1:end-4,:);\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/delaunay_neighbors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.606002836697025}} {"text": "function [X, info] = IRhtv(A, b, varargin)\n% IRhtv Least squares solver with heuristic total variation penalization\n%\n% options = IRhtv('defaults')\n% [X,info] = IRhtv(A,b)\n% [X,info] = IRhtv(A,b,K)\n% [X,info] = IRhtv(A,b,options)\n% [X,info] = IRhtv(A,b,K,options)\n%\n% This penalized restarted iteration method incorporates a heuristic TV\n% penalization term (it does not produce a strict TV solution).\n%\n% It is assumed that x represents an n-times-n image such that N = n^2.\n%\n% IRhtv is a simplified driver for IRrestart, which uses an inner-outer \n% iteration scheme. Semi-convergent or hybrid iterative solvers are used \n% in the inner iterations, using one of the iterative methods in IRtools \n% (e.g., IRhybrid_gmres). In the case of IRhtv, the TV penalization \n% is updated at each outer iteration. \n%\n% The regularization parameter and number of inner iterations influence\n% the behavior and convergence of the outer iterations.\n%\n% With 'defaults' as input returns the default options. Otherwise outputs\n% the iterates specified in K, using max(K) as MaxIter, and using all other\n% default options. With options as input: uses the user-specified options\n% and all the other default options.\n%\n% Inputs:\n% A : either (a) a full or sparse matrix\n% (b) a matrix object that performs the matrix*vector operation\n% (c) user-defined function handle\n% b : right-hand side vector\n% K : (optional) integer vector that specifies which (total) iterates are \n% returned in X; the maximum number of iterations is assumed to be max(K)\n% [ positive integer | vector of positive components ]\n% options : structure with the following fields (optional)\n% x0 - initial guess for the iterations; default = zero vector\n% [ array | {'none'} ]\n% MaxIterIn - maximum number of inner iterations\n% MaxIterOut - maximum number of outer iterations\n% x_true - true solution; allows us to returns error norms with\n% respect to x_true at each iteration\n% [ array | {'none'} ]\n% RegParam - a value or a method to find the regularization used in\n% the inner iterations\n% [non-negative scalar | {'gcv'} | 'discrep' ]\n% This also determines which stopping rule is used for\n% the inner iterations.\n% If 'gcv' is chosen, the inner iteration is stopped when\n% the GCV function minimum stabilizes or increases \n% within a certain window of iterations (see 'stopGCV',\n% 'FlatTol' and 'MinTol').\n% If 'discrep' is chosen, and NoiseLevel is rovided,\n% then the discrepancy principle is used as stopping\n% criterion (see 'NoiseLevel' and 'eta').\n% stopGCV - stopping criterion for the inner iterations when\n% GCV is used\n% [ 'GCVvalues' | {'resflat'} ]\n% FlatTol - tolerance for detecting flatness (stabilization)\n% in the GCV function as a stopping criterion for the\n% inner iterations\n% [ {10^-6} | non-negative scalar ]\n% MinTol - window of iterations - if the GCV minimum continues\n% to increase over this window, then the inner\n% iterations are stopped:\n% [ {3} | positive integer ]\n% RegMatrix - priorconditioner for the inner iterations\n% [ {'identity'} | square nonsingular matrix |\n% function handle ]\n% NoiseLevel - norm of noise in rhs divided by norm of rhs\n% (must be assigned in RegParam is 'discrep')\n% [ {none} | nonnegative scalar ]\n% eta - safety factor for the discrepancy principle\n% [ {1.01} | scalar greater than (and close to) 1 ]\n% RegParam0 - first regularization parameter, used only on the \n% very first iteration (needed if RegParam is 'discrep')\n% [ {1} | positive scalar ]\n% stopOut - stopping criterion for the outer iterations;\n% [ {'xstab'} | 'Lxstab' | 'regPstab' ]\n% inSolver - solver to be employed during the inner iterations\n% [ {'gmres'} | 'lsqr' ]\n% adaptConstr - approximate constraint or regularization to be\n% incorporated\n% [ {'tv'} | 'tvnn' ]\n% nonnegativity - may be used to also impose nonnegativity\n% (similarly to 'tvnn')\n% [ 'on' | {'off'} ]\n% IterBar - shows the progress of the outer iterations\n% [ {'on'} | 'off' ]\n% NoStopIn - specifies whether the inner iterations should\n% proceed after a stopping criterion has been satisfied\n% [ 'on' | {'off'}]\n% NoStopOut - specifies whether the outer iterations should\n% proceed after a stopping criterion is satisfied\n% [ 'on' | {'off'} ]\n% verbosity - switch on or off the \"verbosity\" of the function\n% [ {'on'} | 'off' ]\n% Note: the options structure can be created using the function IRset.\n%\n% Outputs:\n% X : computed solutions, stored column-wise (at the iterations listed in K)\n% info: structure with the following fields:\n% its - number of the last computed iteration\n% saved_iterations - iteration numbers of iterates stored in X \n% StopFlag_in - string that describes the inner stopping condition:\n% * Stopping criterion of the inner iterations is\n% never satisfied\n% * Stopping criterion is satisfied at least once\n% during the inner iterations\n% StopFlag_out - string that describes the outer stopping condition;\n% depending on the inputs it can be one of the following:\n% * Outer stopping criterion is never satisfied\n% * Diagonal weighting matrix is numerically zero\n% * Solution stabilizes\n% * Transformed solution stabilizes\n% * Regularization parameter stabilizes\n% Rnrm - relative residual norms at each iteration\n% Xnrm - solution norms at each iteration\n% Enrm - relative error norms (requires x_true) at each iteration\n% StopReg - struct containing information about the solution that\n% satisfies the stopping criterion. Fields:\n% It : iteration where the stopping criterion is satisfied\n% X : solution satisfying the stopping criterion\n% Enrm : the corresponding relative error (requires x_true)\n% BestReg - struct containing information about the solution that\n% minimizes Enrm (requires x_true). Fields:\n% It : iteration where the minimum is attained\n% X : best solution\n% Enrm : best relative error\n% Xout - approximate solutions at the end of each inner cycle,\n% stored column-wise\n% itsInOut - 3-column matrix whose the columns store\n% 1. outer iteration count\n% 2. inner iteration count (i.e., for each cycle)\n% 3. total iteration count\n%\n% See also: IRell1, IRirn, IRrestart, IRget, IRset\n\n% Silvia Gazzola, University of Bath\n% Per Christian Hansen, Technical University of Denmark\n% James G. Nagy, Emory University\n% April, 2018.\n\n% This file is part of the IR Tools package and is distributed under the \n% 3-Clause BSD License. A separate license file should be provided as part \n% of the package.\n\n% Set default values for options.\ndefaultopt = struct('x0', 'none', 'MaxIterIn', 30 , 'MaxIterOut', 20 , ...\n 'RegParam', 'gcv', 'stopGCV', 'resflat', ...\n 'resflatTol', 0.05, 'GCVflatTol', 10^-6, 'GCVminTol', 3,...\n 'x_true', 'none', 'IterBar', 'on', 'NoStop', 'off', 'NoStopIn', 'off',...\n 'NoStopOut', 'off', 'stopOut', 'xstab', 'stabOut', 1e-6, ...\n 'thr0', 1e-10, 'NoiseLevel', 'none', 'eta', 1.01, 'RegParam0', 1,...\n 'inSolver', 'gmres', 'adaptConstr', 'tv', 'nonnegativity', 'off', ...\n 'verbosity', 'off');\n \n% If input is 'defaults,' return the default options in X.\nif nargin==1 && nargout <= 1 && isequal(A,'defaults')\n X = defaultopt;\n return;\nend\n\n% Check for acceptable number of optional input arguments.\nswitch length(varargin)\n case 0 \n K = []; options = [];\n case 1\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = [];\n else\n K = []; options = varargin{1};\n end\n case 2\n if isa(varargin{1}, 'double')\n K = varargin{1}; options = varargin{2};\n else\n K = varargin{2}; options = varargin{1};\n end\n otherwise\n error('Too many input parameters')\nend\n\nn = length(b(:));\nnosquare = 0;\ntest_sq = ones(n,1);\ntry\n test_sq = A_times_vec(A, test_sq);\n if (length(test_sq)~=n)\n nosquare = 1;\n end\ncatch\n nosquare = 1;\nend\n\nif isfield(options, 'inSolver') && ~isempty(options.inSolver)\n inSolver = IRget(options, 'inSolver', [], 'fast');\n if strcmp(inSolver, 'gmres')\n if nosquare\n warning(['The matrix A is rectangular, and a solver like hybrid gmres cannot handle it. ',...\n 'The solver is changed to hybrid lsqr.'])\n options.inSolver = 'lsqr';\n end\n end\nend\n\nif isempty(options)\n options = defaultopt;\nend\n\noptions = IRset(defaultopt, options);\ninSolver = IRget(options, 'inSolver', [], 'fast');\n\nif nosquare && strcmp(inSolver, 'gmres')\n options.inSolver = 'lsqr';\nend\n\nnn = IRget(options, 'nonnegativity', [], 'fast');\n\nif strcmp(nn, 'on')\n options.adaptConstr = 'tvnn';\nend\n\n% Call IRrestart with the specified options.\noptions = rmfield(options, 'nonnegativity');\n[X, info] = IRrestart(A, b, K, options);", "meta": {"author": "jnagy1", "repo": "IRtools", "sha": "040ef13d27873b6391aedd4ec06c453e1add9066", "save_path": "github-repos/MATLAB/jnagy1-IRtools", "path": "github-repos/MATLAB/jnagy1-IRtools/IRtools-040ef13d27873b6391aedd4ec06c453e1add9066/IRcodes/IRhtv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6060028269827042}} {"text": "function nu = transport( X, Y, xi )\n%TRANSPORT Calculates vector transport\n% NU = TRANSPORT( X, Y, XI ) calculates the vector transport from\n% \n% T_X --> X_Y\n% \n% where X and Y are given in Tucker format (ttensor) and applies it \n% to the tangent vector XI. XI is decomposed into\n% XI = Y_tilde x U1 x U2 x U3 \n% + S x U1_tilde x U2 x U3 \n% + S x U1 x U2_tilde x U3 \n% + S x U1 x U2 x U3_tilde \n% \n% where only Y_tilde, U1_tilde, U2_tilde and U3_tilde are stored\n% as a struct in factorized form.\n%\n% See also calcProjection, addFactorized\n%\n\n% GeomCG Tensor Completion. Copyright 2013 by\n% Michael Steinlechner\n% Questions and contact: michael.steinlechner@epfl.ch\n% BSD 2-clause license, see LICENSE.txt\n\n V1 = Y.U{1}'*X.U{1};\n V2 = Y.U{2}'*X.U{2};\n V3 = Y.U{3}'*X.U{3};\n\n V1_tilde = Y.U{1}'*xi.U1_tilde;\n V2_tilde = Y.U{2}'*xi.U2_tilde;\n V3_tilde = Y.U{3}'*xi.U3_tilde;\n\n M1 = ttm( xi.Y_tilde, {V1, V2, V3} );\n M2 = ttm( X.core, {V1_tilde, V2, V3 } );\n M3 = ttm( X.core, {V1, V2_tilde, V3 } );\n M4 = ttm( X.core, {V1, V2, V3_tilde } );\n\n %first part:\n nu.Y_tilde = M1 + M2 + M3 + M4;\n\n %second part;\n \n Y1 = ttm(xi.Y_tilde, {X.U{1}, V2, V3} );\n Y2 = ttm(xi.Y_tilde, {V1, X.U{2}, V3} );\n Y3 = ttm(xi.Y_tilde, {V1, V2, X.U{3}} );\n\n G1_1 = ttm( X.core, {xi.U1_tilde, V2, V3} );\n G1_2 = ttm( X.core, {X.U{1}, V2_tilde, V3} );\n G1_3 = ttm( X.core, {X.U{1}, V2, V3_tilde} );\n\n G2_1 = ttm( X.core, {V1_tilde, X.U{2}, V3} );\n G2_2 = ttm( X.core, {V1, xi.U2_tilde, V3} );\n G2_3 = ttm( X.core, {V1, X.U{2}, V3_tilde} );\n\n G3_1 = ttm( X.core, {V1_tilde, V2, X.U{3}} );\n G3_2 = ttm( X.core, {V1, V2_tilde, X.U{3}} );\n G3_3 = ttm( X.core, {V1, V2, xi.U3_tilde} );\n\n S1_inv = pinv( double( tenmat( Y.core, 1 ) ));\n S2_inv = pinv( double( tenmat( Y.core, 2 ) ));\n S3_inv = pinv( double( tenmat( Y.core, 3 ) ));\n\n U1_tilde = double( tenmat(Y1 + G1_1 + G1_2 + G1_3, 1) ) * S1_inv;\n U2_tilde = double( tenmat(Y2 + G2_1 + G2_2 + G2_3, 2) ) * S2_inv;\n U3_tilde = double( tenmat(Y3 + G3_1 + G3_2 + G3_3, 3) ) * S3_inv;\n\n nu.U1_tilde = U1_tilde - Y.U{1} * ( Y.U{1}' * U1_tilde );\n nu.U2_tilde = U2_tilde - Y.U{2} * ( Y.U{2}' * U2_tilde );\n nu.U3_tilde = U3_tilde - Y.U{3} * ( Y.U{3}' * U3_tilde );\n\nend\n\n\n\n\n\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/geomCG/transport.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6060008104342997}} {"text": "function [grid1, grid2, freq1, freq2, biv, cond2on1, cond1on2, cexp1, cexp2] = bivkernrest(data1,data2,res1,res2,observed)\n%[grid1, grid2, freq1, freq2, biv, cond2on1, cond1on2, cexp1, cexp2] = bivkern(data1,data2,res1,res2)\n%data1,2 = data for which a kernel density needs to be derived\n%res1,2 = step size\n%observed = vector of dummies that identifies which elements of data1,2 are\n%observations (1) rather than restrictions (0)\n%\n%restrictions are added by extending the data vectors with\n%data1(i) = y for data2(i) = x, observed(i) = 0\n%for example, data1(17) = 0, data2(17) = 0, observed(17) = 0\n%\n%Richard Tol, 13 September 2013\n\ntic\n\nampl = 0.1; %bandwidth of the restriction\nrange = 4; %data are evaluated between minimum minus range*standard deviation and maximum plus range*standard deviation\n\ndata1std = std(data1(observed==1));\ndata1min = res1*round((min(data1(observed==1)) - range*data1std)/res1); %minimum at observed minus range*standard deviation\ndata1min = max(0,data1min);\ndata1max = res1*((max(data1(observed==1)) + range*data1std)/res1); %maximum at observed plus range*standard deviation\nnopnt = length(data1);\nnocon = nopnt - sum(observed);\nnoobs = nopnt - nocon;\n\ndata2std = std(data2(observed==1));\ndata2min = res2*round((min(data2(observed==1)) - range*data2std)/res2); %minimum at observed minus range*standard deviation\n%data2min = max(0,data2min);\ndata2max = res2*round((max(data2(observed==1)) + range*data2std)/res2); %maximum at observed plus range*standard deviation\n\n%make grid\nnogrid1 = round((data1max-data1min)/res1);\ngrid1 = zeros(nogrid1,1);\ngrid1(1) = data1min;\nfor i=2:nogrid1\n grid1(i) = grid1(i-1) + res1;\nend\n\nnogrid2 = round((data2max-data2min)/res2);\ngrid2 = zeros(nogrid2,1);\ngrid2(1) = data2min;\nfor i=2:nogrid2\n grid2(i) = grid2(i-1) + res2;\nend\n\n%bandwith\nsigma = cov(data1(observed==1), data2(observed==1))*1.06^2*noobs^-0.4;\nh = inv(sigma);\nh1 = 1.06 * noobs^-0.2 * std(data1); %for univariate\nh2 = 1.06 * noobs^-0.2 * std(data2); %for univariate\n\n%normal kernel\nbiv = zeros(nogrid1,nogrid2);\nvbiv = biv;\nvfreq1 = ones(nogrid1,noobs);\nvfreq2 = ones(nogrid2,noobs);\nx= zeros(2,1);\nfor i=1:nopnt,\n %disp(i);\n vfreq1(:,i) = exp(-0.5*((grid1-data1(i))/(h1*observed(i)+ampl*h1*(1-observed(i)))).^2)/(h1*observed(i)+ampl*h1*(1-observed(i)))/sqrt(2*pi);\n vfreq2(:,i) = exp(-0.5*((grid2-data2(i))/(h2*observed(i)+ampl*h2*(1-observed(i)))).^2)/(h2*observed(i)+ampl*h2*(1-observed(i)))/sqrt(2*pi);\n dev1 = grid1-data1(i);\n dev2 = grid2-data2(i);\n for k=1:nogrid1,\n for l=1:nogrid2,\n x1 = dev1(k);\n x2 = dev2(l);\n vbiv(k,l) = exp(-0.5*((h(1,1)*observed(i)+h(1,1)/ampl*(1-observed(i)))*x1^2 + (h(2,2)*observed(i)+h(2,2)/ampl*(1-observed(i)))*x2^2 + (h(1,2)*observed(i)+h(1,2)/ampl*(1-observed(i)))*x1*x2));\n end\n end\n biv = biv + vbiv/sum(sum(vbiv));\nend\nbiv = biv/sum(sum(biv));\nfreq1 = sum(vfreq1,2);\nfreq1 = freq1/sum(freq1);\nfreq2 = sum(vfreq2,2);\nfreq2 = freq2/sum(freq2);\n\ncond2on1=biv./repmat(sum(biv,2),1,nogrid2);\ncond1on2=biv./repmat(sum(biv,1),nogrid1,1);\ncond1on2=cond1on2';\n\ncexp1 = sum(cond1on2.*repmat(grid1,1,nogrid2)',2);\ncexp2 = sum(cond2on1.*repmat(grid2',nogrid1,1),2);\n\ntoc\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/43503-bivariate-kernel-regression-with-restrictions/bivkernrest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6060007992118748}} {"text": "function result = isintersect_3dof(SHAPE, LINE)\n% isintersect(SHAPE, LINE)\n% this function check whether we intersect the shape or not\n% SHAPE could be polygon or line\n% LINE is always line\n%\n\nvert_num = size(SHAPE(:,1),1);\nresult = 0;\n\nm = (LINE(2, 2) - LINE(1, 2)) / (LINE(2, 1) - LINE(1, 1));\nb = LINE(1, 2) - m * LINE(1, 1);\nradius = 0.1;\n\nfor k = 1:vert_num-1\n % y = m * x + b\n \n m_obs = (SHAPE(k, 2) - SHAPE(k+1, 2)) / (SHAPE(k, 1) - SHAPE(k+1, 1));\n b_obs = SHAPE(k, 2) - m_obs * SHAPE(k, 1);\n \n % consider this lines ???\n \n if (m_obs + radius > m) && (m_obs - radius < m) && (b_obs + radius > b) && (b_obs - radius < b)\n result = 1;\n return;\n end\n \n % ???\n \n x_intersection = (b - b_obs)/(m_obs - m);\n \n x_max = max (SHAPE(k, 1),SHAPE(k+1, 1));\n x_min = min (SHAPE(k, 1), SHAPE(k+1, 1));\n \n y_max = max (SHAPE(k, 2), SHAPE(k+1, 2));\n y_min = min (SHAPE(k, 2), SHAPE(k+1, 2));\n \n x_edge_max = max(LINE(1, 1), LINE(2, 1));\n x_edge_min = min(LINE(1, 1), LINE(2, 1));\n \n y_edge_max = max(LINE(1, 2), LINE(2, 2));\n y_edge_min = min(LINE(1, 2), LINE(2, 2));\n \n y_intersection = m_obs * x_intersection + b_obs;\n \n if ((x_intersection >= (x_min-radius) && x_intersection <= (x_max + radius)) ...\n && (x_intersection >= (x_edge_min - radius) && x_intersection <= (x_edge_max+radius)) ...\n && y_intersection<= y_edge_max + radius && y_intersection >= y_edge_min - radius ...\n && y_intersection<= y_max+radius && y_intersection >= y_min - radius)\n result = 1;\n return;\n end\nend\n", "meta": {"author": "olzhas", "repo": "rrt_toolbox", "sha": "b07e72cebe7053661083f4c4d1843aae88e1ad3c", "save_path": "github-repos/MATLAB/olzhas-rrt_toolbox", "path": "github-repos/MATLAB/olzhas-rrt_toolbox/rrt_toolbox-b07e72cebe7053661083f4c4d1843aae88e1ad3c/func/isintersect_3dof.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.6059987121203477}} {"text": "% Discrete Cepstral Envelope (DCE)\n%\n% Input\n% af : Array of structures with matrices containing sinusoidal\n% parameters (as the output of sin_analysis.m).\n% Each matrix is made of:\n% The 1st line for the frequency of each sinusoid [Hz]\n% The 2nd line for their amplitude (linear scale)\n% The DC has to be included (in the first column)\n% fs : [Hz] Signal's sampling frequency\n% order : Cepstral order\n% [extrap_dcny] : If true (default), alleviate stability problems of the DCE \n% by replacing the DCE value and extrapolating sinusoidal\n% components up to Nyquist.\n% If false, use the sinusoidal components as they are. \n% [scale] : empty : Frequency linear scale (default)\n% 'mel' : see frq2mel (for MFCC computation)\n% 'bark' : see frq2bark\n% 'erb' : see frq2erb\n% [Bw] : [Hz] Standard-deviation of the Gaussian used as weighting\n% function (for emphasizing the importance of the low\n% frequencies in the solution).\n% Bw As to be big enough to have the weights still\n% significant up to Nyquist.\n% [lr] : Regularization parameter (as in [2]) (def. 0)\n% [dftlen] : DFT's length, if the 4th output argument is requested.\n%\n% Output\n% cc : Cepstral coefficients\n% E : The amplitude cepstral envelope\n% \n% References\n% [1] T. Galas and X. Rodet, \"Generalized discrete cepstral analysis for\n% deconvolution of source-filter system with discrete spectra,\"\n% in IEEE Applications of Signal Processing to Audio and Acoustics (ASSP)\n% Workshop, pp. 71-72, 1991.\n% [2] M. Campedel-Oudot, O. Cappe and E. Moulines, \"Estimation of the Spectral\n% Envelope of Voiced Sounds Using a Penalized Likelihood Approach\", IEEE\n% Transactions on Speech and Audio Processing, vol. 9, no. 5, pp. 469-481,\n% 2001.\n% \n% Copyright (c) 2011 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 [cc E] = env_dce_sfa(af, fs, order, extrap_dcny, scale, Bw, lr, dftlen)\n\n % Input parameters\n if nargin<4; extrap_dcny=true; end\n if nargin<5; scale = []; end\n if nargin<6 || isempty(Bw); Bw = 2000*(fs/16000); end % To make it as\n % similar as possible to the DCE-MFA\n if nargin<7 || isempty(lr); lr = 0.035; end % [2]\n if nargin<8; dftlen=4096; end\n\n if ~isempty(scale)\n Bw = 100*fs;\n lr = 0.035; % To make it as similar as possible to [2]\n eval(['fnscale=@frq2' scale ';']);\n af.f = 0.5*fs*fnscale(af(n).f)/fnscale(fs/2);\n end\n\n % If asked, extrapolate components at DC and up to Nyquist\n if extrap_dcny; af = env_extrap_sins_dcny(af, fs); end\n\n af.f = af.sins(1,:);\n af.a = log(af.sins(2,:));\n\n\n % Prepare the weighting functions\n fk = af.f(:);\n Nk = length(fk);\n wk = exp(-fk.^2 / (2 * Bw * Bw))';\n wk = wk./sum(wk);\n Wk = diag(wk);\n\n % Compute the DCE envelope\n fk = af.f(:);\n ak = af.a(:);\n Nk = length(fk);\n Bk = [ones(Nk,1) cos(2*pi*fk/fs*(1:order))];\n\n BWB = (Bk'*Wk*Bk);\n rt = (Bk'*Wk*(ak));\n\n if lr>0\n cc = (BWB+lr*diag(ones(size(BWB,1),1)))\\rt;\n else\n cc = BWB\\rt;\n end\n\n % If asked, compute the envelope\n if nargout>1\n if isempty(scale)\n E = fft(cc, dftlen);\n E = exp(E(1:end/2+1));\n else\n if strcmp(scale,'bark')\n E = barkcc2spec(cc, fs, dftlen);\n E = E(1:end/2+1);\n elseif strcmp(scale,'mel')\n E = exp(fft(cc, dftlen));\n E = E(1:dftlen/2+1);\n E = cc2hspec(cc, fs, dftlen);\n E = fwcep2hspec(cc, fs, dftlen);\n end\n end\n end\n\n % Plot final solution\n if 0\n hold off;\n\n global S Erefg selfr;\n if ~isempty(S);\n Sbins = fs*(0:dftlen/2)/dftlen;\n plot(Sbins, mag2db(abs(S)), ':k');\n hold on;\n else; hold off; end\n if ~isempty(Erefg);\n Erefgbins = 0.5*fs*(0:length(Erefg)-1)/length(Erefg);\n plot(Erefgbins, mag2db(abs(Erefg)), 'k');\n hold on;\n end\n\n plot(af.f, mag2db(exp(af.a)),'xr');\n hold on;\n F = fs*(0:dftlen/2)/dftlen;\n% plot(F, mag2db(abs(L)), 'g');\n hold on;\n plot(F, mag2db(abs(E)), 'b', 'LineWidth', 2);\n keyboard\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/envelope/env_dce_sfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.6058994268636309}} {"text": "function Y = ttm(X,V,varargin)\n%TTM Tensor times matrix.\n%\n% Y = TTM(X,A,N) computes the n-mode product of tensor X with a\n% matrix A; i.e., X x_N A. The integer N specifies the dimension\n% (or mode) of X along which A should be multiplied. If size(A) =\n% [J,I], then X must have size(X,N) = I. The result will be the\n% same order and size as X except that size(Y,N) = J.\n%\n% Y = TTM(X,{A,B,C,...}) computes the n-mode product of tensor X\n% with a sequence of matrices in the cell array. The n-mode\n% products are computed sequentially along all dimensions (or modes)\n% of X. The cell array contains ndims(X) matrices.\n%\n% Y = TTM(X,{A,B,C,...},DIMS) computes the sequence tensor-matrix\n% products along the dimensions specified by DIMS.\n%\n% Y = TTM(...,'t') performs the same computations as above except\n% the matrices are transposed.\n%\n% Examples\n% X = tensor(rand(5,3,4,2));\n% A = rand(4,5); B = rand(4,3); C = rand(3,4); D = rand(3,2);\n% Y = ttm(X, A, 1) %<-- computes X times A in mode-1\n% Y = ttm(X, {A,B,C,D}, 1) %<-- same as above\n% Y = ttm(X, A', 1, 't') %<-- same as above\n% Y = ttm(X, {A,B,C,D}, [1 2 3 4]) %<-- 4-way multiply\n% Y = ttm(X, {D,C,B,A}, [4 3 2 1]) %<-- same as above\n% Y = ttm(X, {A,B,C,D}) %<-- same as above\n% Y = ttm(X, {A',B',C',D'}, 't') %<-- same as above\n% Y = ttm(X, {C,D}, [3 4]) %<-- X times C in mode-3 & D in mode-4\n% Y = ttm(X, {A,B,C,D}, [3 4]) %<-- same as above\n% Y = ttm(X, {A,B,D}, [1 2 4]) %<-- 3-way multiply\n% Y = ttm(X, {A,B,C,D}, [1 2 4]) %<-- same as above\n% Y = ttm(X, {A,B,D}, -3) %<-- same as above\n% Y = ttm(X, {A,B,C,D}, -3) %<-- same as above\n%\n% See also TENSOR, TENSOR/TTT, TENSOR/TTV.\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\n\n%% Check the number of arguments\nif (nargin < 2)\n error('TTM requires at least two arguments.');\nend\n\n%% Create 'n' and 'tflag' arguments from varargin\nn = 1:ndims(X);\ntflag = '';\nif numel(varargin) == 1\n if ischar(varargin{1})\n tflag = varargin{1};\n else\n n = varargin{1};\n end\nelseif numel(varargin) == 2\n n = varargin{1};\n tflag = varargin{2};\nend\n\n%% Handle cell array\nif iscell(V) \n % Copy n into dims\n dims = n;\n % Check that the dimensions are valid\n [dims,vidx] = tt_dimscheck(dims,ndims(X),numel(V));\n % Calculate individual products\n Y = ttm(X, V{vidx(1)}, dims(1), tflag);\n for i = 2 : numel(dims)\n Y = ttm(Y, V{vidx(i)}, dims(i), tflag);\n end\n % All done\n return;\nend\n\n%% Check the second argument\nif ndims(V) ~= 2\n error('tensor/ttm: 2nd argument must be a matrix.');\nend\n\n%% Check n\nif (numel(n) ~= 1 || (n < 0) || n > ndims(X))\n error('Dimension N must be between 1 and NDIMS(X).');\nend\n\n%% COMPUTE THE PRODUCT \n\nN = ndims(X);\nsz = size(X);\norder = [n,1:n-1,n+1:N];\nnewdata = double(permute(X,order));\nnewdata = reshape(newdata,sz(n),prod(sz([1:n-1,n+1:N])));\nif tflag == 't'\n newdata = V'*newdata;\n p = size(V,2);\nelse\n newdata = V*newdata;\n p = size(V,1);\nend\nnewsz = [p,sz(1:n-1),sz(n+1:N)];\nY = tensor(newdata,newsz);\nY = ipermute(Y,order);\n\n\nreturn;\n\nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/@tensor/ttm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6058546923233631}} {"text": "function mean = uniform_01_mean ( )\n\n%*****************************************************************************80\n%\n%% UNIFORM_01_MEAN returns the mean of the Uniform 01 PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real MEAN, the mean of the discrete uniform PDF.\n%\n mean = 0.5;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/uniform_01_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6058546913890583}} {"text": "function Y = ttm(X,V,varargin)\n%TTM Tensor times matrix.\n%\n% Y = TTM(X,A,N) computes the n-mode product of tensor X with a\n% matrix A; i.e., X x_N A. The integer N specifies the dimension\n% (or mode) of X along which A should be multiplied. If size(A) =\n% [J,I], then X must have size(X,N) = I. The result will be the\n% same order and size as X except that size(Y,N) = J.\n%\n% Y = TTM(X,{A,B,C,...}) computes the n-mode product of tensor X\n% with a sequence of matrices in the cell array. The n-mode\n% products are computed sequentially along all dimensions (or modes)\n% of X. The cell array contains ndims(X) matrices.\n%\n% Y = TTM(X,{A,B,C,...},DIMS) computes the sequence tensor-matrix\n% products along the dimensions specified by DIMS.\n%\n% Y = TTM(...,'t') performs the same computations as above except\n% the matrices are transposed.\n%\n% Examples\n% X = tensor(rand(5,3,4,2));\n% A = rand(4,5); B = rand(4,3); C = rand(3,4); D = rand(3,2);\n% Y = ttm(X, A, 1) %<-- computes X times A in mode-1\n% Y = ttm(X, {A,B,C,D}, 1) %<-- same as above\n% Y = ttm(X, A', 1, 't') %<-- same as above\n% Y = ttm(X, {A,B,C,D}, [1 2 3 4]) %<-- 4-way multiply\n% Y = ttm(X, {D,C,B,A}, [4 3 2 1]) %<-- same as above\n% Y = ttm(X, {A,B,C,D}) %<-- same as above\n% Y = ttm(X, {A',B',C',D'}, 't') %<-- same as above\n% Y = ttm(X, {C,D}, [3 4]) %<-- X times C in mode-3 & D in mode-4\n% Y = ttm(X, {A,B,C,D}, [3 4]) %<-- same as above\n% Y = ttm(X, {A,B,D}, [1 2 4]) %<-- 3-way multiply\n% Y = ttm(X, {A,B,C,D}, [1 2 4]) %<-- same as above\n% Y = ttm(X, {A,B,D}, -3) %<-- same as above\n% Y = ttm(X, {A,B,C,D}, -3) %<-- same as above\n%\n% See also TENSOR, TENSOR/TTT, TENSOR/TTV.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2015, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2015) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\n\n\n%% Check the number of arguments\nif (nargin < 2)\n error('TTM requires at least two arguments.');\nend\n\n%% Create 'n' and 'tflag' arguments from varargin\nn = 1:ndims(X);\ntflag = '';\nif numel(varargin) == 1\n if ischar(varargin{1})\n tflag = varargin{1};\n else\n n = varargin{1};\n end\nelseif numel(varargin) == 2\n n = varargin{1};\n tflag = varargin{2};\nend\n\n%% Handle cell array\nif iscell(V) \n % Copy n into dims\n dims = n;\n % Check that the dimensions are valid\n [dims,vidx] = tt_dimscheck(dims,ndims(X),numel(V));\n % Calculate individual products\n Y = ttm(X, V{vidx(1)}, dims(1), tflag);\n for i = 2 : numel(dims)\n Y = ttm(Y, V{vidx(i)}, dims(i), tflag);\n end\n % All done\n return;\nend\n\n%% Check the second argument\nif ndims(V) ~= 2\n error('tensor/ttm: 2nd argument must be a matrix.');\nend\n\n%% Check n\nif (numel(n) ~= 1 || (n < 0) || n > ndims(X))\n error('Dimension N must be between 1 and NDIMS(X).');\nend\n\n%% COMPUTE THE PRODUCT \n\nN = ndims(X);\nsz = size(X);\norder = [n,1:n-1,n+1:N];\nnewdata = double(permute(X,order));\nnewdata = reshape(newdata,sz(n),prod(sz([1:n-1,n+1:N])));\nif tflag == 't'\n newdata = V'*newdata;\n p = size(V,2);\nelse\n newdata = V*newdata;\n p = size(V,1);\nend\nnewsz = [p,sz(1:n-1),sz(n+1:N)];\nY = tensor(newdata,newsz);\nY = ipermute(Y,order);\n\n\nreturn;\n\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@tensor/ttm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6058546876860362}} {"text": "function [flowx,flowy] = specific_wind(x,y,nel)\n%circular_wind Reference problem 3.4 convective wind \n% [flowx,flowy] = specific_wind(x,y,nel);\n% input\n% x x coordinate vector\n% y y coordinate vector \n% nel number of elements\n%\n% specifies circular wind /Morton pp.10/\n% IFISS function: DJS; 5 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n flowx = 2*y.*(1-x.*x); \n flowy = -2*x.*(1-y.*y);\n return\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/convection/test_problems/circular_wind.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6058455404170959}} {"text": "function [ i, j ] = r8mat_min_index ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8MAT_MIN_INDEX returns the location of the minimum entry of an R8MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows in A.\n%\n% Input, integer N, the number of columns in A.\n%\n% Input, real A(M,N), the M by N matrix.\n%\n% Output, integer I, J, the indices of the minimum entry of A.\n%\n i = -1;\n j = -1;\n\n for jj = 1 : n\n for ii = 1 : m\n if ( ii == 1 && jj == 1 )\n i = ii;\n j = jj;\n elseif ( a(ii,jj) < a(i,j) )\n i = ii;\n j = jj;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_min_index.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6058455324301049}} {"text": "function pde = DataDivCurlLinear(varargin)\n%%\n% curl u = g in \\Omega,\n% div (eps* u) = f in \\Omega,\n% n \\cdot (eps * u) = g_N on \\Gamma_0\n% Reference: a linear vector field with modifiable curl and div\n\nif isempty(varargin)\n alpha = 1; % strength of irrotational part (x,y,z)\n beta = 1; % strength of solenoidal part (z,x,y)\nelse\n alpha = varargin{1};\n beta = varargin{2};\nend\n\npde.Eps = @(p) [1+p(:,1)*0 p(:,3)*0 p(:,3)*0; ...\n p(:,3)*0 1+p(:,2)*0 p(:,3)*0; ...\n 0*p(:,1) 0*p(:,2) 1+p(:,3)*0];\n\n\npde.exactu = @(p) alpha*[p(:,1), p(:,2), p(:,3)] + ...\n beta*[p(:,3), p(:,1), p(:,2)];\npde.f = @(p) 3*alpha*ones(size(p,1),1); \npde.g = @(p) beta*[ones(size(p,1),1),...\n ones(size(p,1),1),...\n ones(size(p,1),1)];\n\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/PDWG/DataDivCurlLinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6056990579390014}} {"text": "function w = perform_vf_reorientation(v, options)\n\n% perform_vf_reorientation - try to reorient the vf.\n%\n% w = perform_vf_reorientation(v, options);\n%\n% Flip the orientation of some vectors to ensure a coherent vector field.\n% v and w are (n,n,2) 2D vector field matrices.\n%\n% options.method can be 'xproj', 'yproj', 'circproj', 'localproj',\n% 'custproj', 'randomized', 'laplacian'.\n%\n% 'randomized' uses a slow simulated annealing method to optimize \n% an Ising energy.\n% 'laplacian' solves a big linear system and is the best method (but slow).\n%\n% For 'custproj' you have to provide an additional vector options.w.\n%\n% See also: perform_vf_normalization.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nw = getoptions(options, 'w', [1 0]);\nmethod = getoptions(options, 'method', 'xproj');\n\nif size(v,3)~=2\n error('Works only for 2D vector fields.');\nend\n\nn = size(v,1);\np = size(v,2);\n\n\n\nif strcmp(method, 'laplacian')\n\n % Try to solve the following linear system for some s(k) at each\n % location k:\n % s(k) = 1/|V_k| * sum_{i \\in V_k} s(k)*cos(theta(k)-theta(i))\n % where V_k are the neighbors of point k and theta(k) is the angle\n % theta(k)=atan2(v_y(k),v_x(k));\n \n % normalize \n d = sqrt(sum(v.^2,3)); d(d0 & Y+dy<=n & Y+dy>0);\n I1 = I(J);\n J1 = X(J)+dx+(Y(J)+dy-1)*n;\n i = [i; I1]; j = [j; J1];\n s = [s; cos( theta(I1)-theta(J1) )];\n sdiag(J) = sdiag(J)+1;\n end\n % add diagonal terms\n i = [i; I]; j = [j; I]; s = [s; -sdiag]; \n % enforce constraint\n I = find(i>1); \n i = i(I); j = j(I); s = s(I);\n i = [i; 1]; j = [j; 1]; s = [s; 1];\n L = sparse(i,j,s);\n % solve \n y = zeros(n^2,1); y(1)=1;\n use_cg = getoptions(options, 'use_cg', 0);\n % use_cg = 0;\n if use_cg\n if not(isfield(options, 'niter_max'))\n options.niter_max = 500;\n end\n options.x = y*0+1;\n [s,err] = perform_conjugate_gradient(L'*L,L'*y,options);\n else\n s = L\\y;\n end \n \n s = reshape(s,n,n);\n s = sign(s); \n w = v .* repmat(d, [1 1 2]) .* repmat(s, [1 1 2]); \n\n return;\nend\n\nif strcmp(method, 'laplacian1')\n %%%%%% OLD %%%%%%%%%\n % normalize \n d = sqrt(sum(v.^2,3)); d(d=1 & x+dx<=n & y+dy>=1 & y+dy<=n);\n x = x(I); y = y(I); \n w = a( max(1-dx,1):min(end-dx,end), max(1-dy,1):min(end-dy,end) );\n w(abs(w)<1e-3) = 1e-3;\n i = [i; x+(y-1)*n ];\n j = [j; x+dx+(y+dy-1)*n ];\n z = [ z; w(:) ];\n % add to diagonal\n u(x+(y-1)*n) = u(x+(y-1)*n) + 1;\n end\n % add diagonal term\n [y,x] = meshgrid(1:n,1:n); x = x(:); y = y(:);\n i = [i; x+(y-1)*n ];\n j = [j; x+(y-1)*n ];\n z = [ z; -u(:) ];\n \n A = sparse(i,j,z);\n b = zeros(n^2+1, 1); b(end)=1;\n use_cg = getoptions(options, 'use_cg', 1);\n if use_cg\n if not(isfield(options, 'niter_max'))\n options.niter_max = 500;\n end\n y = b;\n A1 = A'*A; y = A'*b;\n options.x = y*0+1;\n [s,err] = perform_conjugate_gradient(A1,y,options);\n else\n s = A\\b;\n end\n s = reshape(s,n,n);\n s = sign(s);\n \n w = v(2:end-1,2:end-1,:);\n w = w .* repmat(d, [1 1 2]) .* repmat(s, [1 1 2]); \n return;\n \nend\n\nif strcmp(method, 'propagation')\n \n % normalize \n d = sqrt(sum(v.^2,3)); d(d1\n error('Problem with computations.');\n end\n if mtau>0\n tau = repmat(tau, [1 1 2]);\n av = v(i+1,j,:).*tau(1,1,:) + v(i-1,j,:).*tau(2,1,:) + v(i,j+1,:).*tau(3,1,:) + v(i,j-1,:).*tau(4,1,:);\n av = av / mtau;\n if sum(av.*v(i,j,:))<0\n v(i,j,:) = -v(i,j,:);\n end\n end\n for s=1:length(neigh)\n is = i+neigh{s}(1); js = j+neigh{s}(2);\n w = squeeze(v(i,j,:)); \n Prio(is,js) = min( Prio(is,js), Prio(i,j) + 1-abs( sum(w.*neigh{s}')) );\n if S(is,js)==0\n % add to the front\n list(:,end+1) = [is;js];\n S(is,js) = 1; % the front\n end\n end\n end\n progressbar(iter,iter);\n \n w = v(2:end-1,2:end-1,:);\n w = w .* repmat(d, [1 1 2]); \n return;\nend\n\nif strcmp(method, 'localproj')\n % special case.\n for i=1:n\n for j=1:n\n m = zeros(1,1,2);\n if i>1\n m = m + v(i-1,j,:);\n end\n if j>1\n m = m + v(i,j-1,:);\n end\n if i>1 && j>1\n m = m + v(i-1,j-1,:);\n end\n s = dot( m, v(i,j,:) );\n if s<0\n v(i,j,:) = -v(i,j,:);\n end\n \n end\n end \n \n w = v;\n return;\nend\n\nif strcmp(method, 'randomized')\n\n % normalize \n d = sqrt(sum(v.^2,3)); d(dy\ne = 1;\nfor y = 1:ny\n for x = nx:-1:1\n %fprintf('x %d ',order(x)); fprintf('y %d ',order(y));\n if dagx(order(x),order(y)) == 1 \n I(e) = order(x);\n J(e) = order(y);\n e = e + 1;\n %fprintf('x order %d',x);\n %fprintf('y order %d',y);\n %fprintf('\\n');\n end\n end\nend\n\n\n% fprintf('the arcs are: %d',I);\n% fprintf('\\n');\n% fprintf('the arcs are: %d',J);\n% fprintf('\\n');\n\n\n% Now we have to decide which arcs are part of the essential graph and\n% which are undirected edges in the essential graph.\n% Undecided arc in the DAG are 1, directed in EG are 2 and undirected in EG\n% are 3.\n\n\nfor e = 1:length(I)\n if dagx(I(e),J(e)) == 1\n cont = true;\n for w = 1:nx \n if dagx(w,I(e)) == 2\n if dagx(w,J(e)) ~= 0\n dagx(w,J(e)) = 2;\n else\n for ww = 1:nx\n if dagx(ww,J(e)) ~= 0\n dagx(ww,J(e)) = 2;\n end\n end % and now skip the rest and start with another arc from the list\n w = nx;\n cont = false;\n end\n end\n end\n if cont\n exists = false;\n for z = 1:nx\n %fprintf('test %d',dagx(z,J(e)));\n if dagx(z,J(e)) ~= 0 & z ~= I(e) & dagx(z,I(e)) == 0\n exists = true; \n for ww = 1:nx\n if dagx(ww,J(e)) == 1\n dagx(ww,J(e)) = 2;\n end \n end\n end\n end\n if ~ exists\n for ww = 1:nx\n if dagx(ww,J(e)) == 1\n dagx(ww,J(e)) = 3;\n end \n end \n end\n end\n end \nend\n\n%print_dag(dagx); % Just checking output\n\n\n\n\n\n\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/graph/dag_to_essential_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6056171941586561}} {"text": "%% OPTI Toolbox Differentiation Demo\n%\n% This file demonstrates each of the different differentiation algorithms\n% supplied with the OPTI Toolbox. Note you should be familiar with the \n% operation of OPTI Toolbox by reading the accompanying examples, as well \n% as you should have completed the NLP demo.\n%\n% Copyright (C) 2011 Jonathan Currie (I2C2)\n\n%% Gradient vs Jacobian\n% The terms Gradient and Jacobian are associated with differentiation\n% functions, and for the purposes of this toolbox they are basically\n% interchangeable:\n%\n% Gradient - The first derivative of the objective function (1 x n)\n% Jacobian - The first derivative of the constraint function (m x n)\n%\n% Where you will note the main difference is the gradient is a vector, and\n% the Jacobian is a matrix. However this is just a rule of thumb and will\n% not hold in all instances (constraint functions with one row for\n% example!). All functions are named as returning a Jacobian, which could\n% also be a Gradient Vector.\n \n%% Problem 1\n% For the following examples we are going to use this nonlinear objective\n% function:\n\nfun = @(x) sin(pi*x(1)/12) * cos(pi*x(2)/16);\n\nx = [0.75 0.25]';\n\n%% Example 1 - Automatic Differentiation (AD)\n% Automatic differentiation is one of the most powerful differentiation\n% strategies which can provide error free gradients of a function by\n% applying the chain rule to each operation. \n%\n% The AD routines implemented in OPTI are supplied by adiff, a Matlab\n% project by William McIlhagga. While most Matlab functions are overloaded,\n% you cannot use external code (i.e. via MEX) or any toolbox or class\n% functions.\n\ndx = autoJac(fun,x)\n\n%% Example 2 - Numerical Differentiation (ND)\n% Numerical differentiation using finite differences is a computationally\n% expensive procedure which can result in an inaccurate gradient if the\n% internal perturbations are not chosen correctly. \n%\n% The ND routine implemented in OPTI is the Intel MKL djacobi function\n% which approximates the derivative using central differences. This is\n% implemented via a MEX function which repeatedly calls the function in\n% order to close in on the gradient.\n\ndx = mklJac(fun,x)\n\n%% Example 3 - Symbolic Differentiation (SD)\n% Symbolic differentiation analytically differentiates the function as a\n% symbolic expression, resulting in a single expression for the gradient.\n% Complications occur if the function cannot be analytically differentiated\n% or the symbolic routine cannot find a derivative.\n%\n% The SD routine implemented in OPTI uses the Matlab Symbolic Toolbox as\n% well as two wrapper functions in order to generate the gradient. The\n% wrapper functions convert the function handle to a symbolic expression\n% and vice-versa.\n\ngrad = symJac(fun)\n\nif(~isempty(grad)) %don't run if Symbolic Toolbox not installed\n dx = grad(x)\nend\n\n%% Problem 2\n% For the next few examples we will be solving this NLP:\n\nobj = @(x) log(1+x(1)^2) - x(2);\n\nlb = [-2 -2]';\nub = [2 2]';\n\n%% Example 4 - Applying AD to NLP Solving\n% To use AD to generate the objective gradient for IPOPT create a function\n% handle which calls autoJac, and then pass this to the optiprob function:\n\ngrad = @(x) autoJac(obj,x);\n\nopts = optiset('solver','ipopt');\nOpt = opti('obj',obj,'grad',grad,'bounds',lb,ub,'options',opts)\n\n[x,fval,exitflag,info] = solve(Opt,[0;0]);\nfval\ninfo\n\n%% Example 5 - Applying ND to NLP Solving\n% To use ND to generate the objective gradient for IPOPT just replace the\n% above with mklJac:\n\ngrad = @(x) mklJac(obj,x);\n\nOpt = opti('obj',obj,'grad',grad,'bounds',lb,ub,'options',opts)\n\n[x,fval,exitflag,info] = solve(Opt,[0;0]);\nfval\ninfo\n\n%% Example 6 - Applying SD to NLP Solving\n% To use SD we can generate the analytical gradient and use this as our\n% gradient function:\n\ngrad = symJac(obj)\n\nif(~isempty(grad))\n Opt = opti('obj',obj,'grad',grad,'bounds',lb,ub,'options',opts)\n\n [x,fval,exitflag,info] = solve(Opt,[0;0]);\n fval\n info\nelse\n display('Cannot run example without Symbolic Toolbox!');\nend\n\n%% Conclusion\n% By default OPTI Toolbox will always use Numerical Differentiation\n% (mklJac) for gradients / Jacobians if one has not been provided. This\n% provides the best combination of flexibility with complex objective / \n% constraint functions and performance. However if you can use SD to\n% generate a gradient this would be a preferred method. \n%\n% If you find the optimizer is failing with ND and AD is a suitable \n% candidate you can try it to ensure your gradients are accurate.\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/Demos/Differentiation_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6056171813084704}} {"text": "function [t,u,v,idx,xnode]=raysurf(p0,v0,node,face)\n%\n% [t,u,v,idx,xnode]=raysurf(p,v,node,face)\n%\n% perform a Havel-styled ray tracing for a triangular surface\n%\n% author: Qianqian Fang, \n%\n% input:\n% p0: list of starting points of the rays\n% v0: directional vector of the rays, \n% node: a list of node coordinates (nn x 3)\n% face: a surface mesh triangle list (ne x 3)\n%\n% output:\n% t: distance from p0 to the intersection point for each surface\n% triangle, if t(i)=NaN, no intersection was found for that ray\n% u: bary-centric coordinate 1 of all intersection points\n% v: bary-centric coordinate 2 of all intersection points\n% the final bary-centric triplet is [u,v,1-u-v]\n% idx: idx lists the IDs of the face elements that intersects \n% each ray\n% xnode: optional output, if requested, xnode gives the intersection\n% point coordinates; to compute manually, xnode=p0+repmat(t,1,3).*v0\n%\n% Reference: \n% [1] J. Havel and A. Herout, \"Yet faster ray-triangle intersection (using \n% SSE4),\" IEEE Trans. on Visualization and Computer Graphics,\n% 16(3):434-438 (2010)\n% [2] Q. Fang, \"Comment on 'A study on tetrahedron-based inhomogeneous \n% Monte-Carlo optical simulation',\" Biomed. Opt. Express, (in\n% press)\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nlen=size(p0,1);\nif(len==0)\n error('p0 can not be empty');\nend\nif(size(node,2)<3)\n error('node must contain at least 3 columns');\nend\nif(size(face,2)<3)\n error('face must contain at least 3 columns');\nend\n\nif(size(v0,1)==1 || size(v0,2)==1 && len>1)\n v0=repmat(v0(:)',len,1);\nend\n\nt=zeros(len,1)*nan;\nu=t;\nv=t;\nidx=t;\n\nfor i=1:len\n [ti,ui,vi,id]=raytrace(p0(i,:),v0(i,:),node,face);\n if(isempty(id)) continue; end\n ti=ti(id);\n tpid=find(ti>=0);\n if(isempty(tpid)) continue; end\n [tmin,tloc]=min(ti(find(ti>=0)));\n t(i)=tmin;\n u(i)=ui(id(tpid(tloc)));\n v(i)=vi(id(tpid(tloc)));\n idx(i)=id(tpid(tloc));\nend\n\nif(nargout>=5)\n xnode=p0+repmat(t,1,3).*v0;\nend\n\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/raysurf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6056171654382994}} {"text": "function [X_out] = etrf2000itrf2008(X_in, date)\n\n% SYNTAX:\n% [X_out] = etrf2000itrf2008(X_in, date);\n%\n% INPUT:\n% X_in = input coordinates (XYZ)\n% date = reference date\n%\n% OUTPUT:\n% X_out = output coordinates (XYZ)\n%\n% DESCRIPTION:\n% ETRF2000 to ITRF2008 coordinate converter.\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by:\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%decimal year (YYYY.DDD)\n[~, frac] = date2doy(datenum(date));\nt = date(1) + frac;\n\n%ITRF2008 - ETRF2000 parameters\n% (http://etrs89.ensg.ign.fr/memo-V8.pdf)\n\n%translation [mm]\nT1 = 52.1; T1dot = 0.1;\nT2 = 49.3; T2dot = 0.1;\nT3 = -58.5; T3dot = -1.8;\n\n%scale factor\nD = 1.34e-9; Ddot = 0.08e-9;\n\n%rotation [mas]\nR1 = 0.891; R1dot = 0.081;\nR2 = 5.390; R2dot = 0.490;\nR3 = -8.712; R3dot = -0.792;\n\n%propagate parameters to epoch t\nT1 = T1 + T1dot*(t - 2000.0);\nT2 = T2 + T2dot*(t - 2000.0);\nT3 = T3 + T3dot*(t - 2000.0);\nD = D + Ddot *(t - 2000.0);\nR1 = R1 + R1dot*(t - 2000.0);\nR2 = R2 + R2dot*(t - 2000.0);\nR3 = R3 + R3dot*(t - 2000.0);\n\n%convert translation parameters to [m]\nT1 = T1 * 1e-3;\nT2 = T2 * 1e-3;\nT3 = T3 * 1e-3;\n\n%convert rotation parameters to [rad]\nR1 = R1 * 4.848136e-9;\nR2 = R2 * 4.848136e-9;\nR3 = R3 * 4.848136e-9;\n\n%translation vector\nT = [T1; T2; T3];\n\n%rotation/scale matrix\nR = [1 -R3 R2; R3 1 -R1; -R2 R1 1];\n\n%7-parameters Helmert inverse transformation\nX_out = inv(R)/(1+D)*(X_in - T);\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/geo/etrf2000itrf2008.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.6054547148218451}} {"text": "function s = y2s(y)\n% S = y2s(Y)\n%\n% Admittance to Scattering transformation\n% for square matrices at multiple frequencies\n% \n% s = inv(I+y) * (I-y)\n% ver 0.0 original\t31.03.1998\n% ver 0.1 +freq\t\t27.09.2002\n% ver 0.2 +octave supp.\t01.06.2005 \n\n if size(size(y),2) > 2 \n nF = size(y,3); \n else nF = 1; \n end;\n \nI = diag(ones(1, size(y,2)));\n\n\n for i=1:nF\n s(:,:,i) = inv(I+y(:,:,i)) * (I-y(:,:,i)); \n end;\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/6080-s-parameter-toolbox-+-z-y-h-g-abcd-t/sbox/y2s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6054225850334723}} {"text": "function [Ft3]=tri6_subtri3(Ft6,Vt6)\n\n% function [Ft3]=tri6_subtri3(Ft6,Vt6)\n% ------------------------------------------------------------------------\n% The input 6-node triangles are either oriented such that the first node\n% is a corner node or that the first node is a mid-edge node. The two cases\n% are highlighted below. \n% \n% Case I\n% 1\n% / \\\n% 2 6\n% / \\\n% 3___4___5\n% Case II\n% 6\n% / \\\n% 5 1\n% / \\\n% 4___3___2\n%\n% The output will follow one of these rules and maintains face normals\n% directions:\n% \n% Case I\n% 1\n% / \\\n% 2___6\n% / \\ / \\\n% 3___4___5\n%\n% Case II\n% 6\n% / \\\n% 5___1\n% / \\ / \\\n% 4___3___2\n% \n% ------------------------------------------------------------------------\n%%\n%Check face order based on first\na=Vt6(Ft6(1,2),:)-Vt6(Ft6(1,1),:); %2 1 edge\nb=Vt6(Ft6(1,6),:)-Vt6(Ft6(1,1),:); %6 1 edge\nc=Vt6(Ft6(1,3),:)-Vt6(Ft6(1,2),:); %3 2 edge\n\nam=sqrt(sum(a.^2));\nbm=sqrt(sum(b.^2));\ncm=sqrt(sum(c.^2));\n\nphi=abs(acos(dot(a,b)./(am*bm)));\nphi=mod(phi,pi); %Angle between 2 1 and 6 1 edge \ntheta=abs(acos(dot(a,c)./(am*cm)));\ntheta=mod(theta,pi); %Angle between 2 1 and 3 2 edge \n\nif phi>theta\n Ft3=[Ft6(:,[1 2 6]); Ft6(:,[2 3 4]); Ft6(:,[4 5 6]); Ft6(:,[2 4 6])]; %Clockwise\nelse \n Ft3=[Ft6(:,[1 2 3]); Ft6(:,[3 4 5]); Ft6(:,[5 6 1]); Ft6(:,[1 3 5])]; %Anti-clockwise\nend\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/tri6_subtri3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6054225850334723}} {"text": "function DEM_FEP_Least_Action\n%--------------------------------------------------------------------------\n% This routine uses a Lorenz system to show that the most likely autonomous\n% path (or deterministic path) is uniquely identified by its initial and\n% final states. In other words, if we knew the end state of an autonomous\n% trajectory, then we would implicitly know the path taken from the initial\n% particular state, even if we did not know the external states. This point\n% is demonstrated using numerical analyses of the Lorenz system; treating\n% the first state and an active state and the third as an external state.\n% In this example, 1024 solutions are obtained from the same initial\n% particular (i.e., sensory and active) states but sampling from a Gaussian\n% distribution over external states. The ensuing trajectories over 128 time\n% bins of 1/128 seconds are shown in the left panels. The sample\n% distribution over active states is shown as a (scaled) histogram along\n% the x-axis. Paths that end within 1/8 of an arbitrary active state (here,\n% ?? = -4) are shown in red. The corresponding autonomous (i.e., active)\n% paths are shown as a function of time in the right panels. one can repeat\n% this analysis for different levels of random fluctuations; e.g.,log\n% precisions of 2 and 16. The key thing to observe is that as the amplitude\n% of random fluctuations decreases (i.e., its precision increases) the\n% paths that begin and end in the same place collapse to a single\n% trajectory of least action. This is the most likely or deterministic\n% path. Clearly, this behaviour rests upon a diffeomorphic mapping between\n% the initial and final states: for example, a final active state of -8 has\n% the least two paths of least action (xT in the code below).\n%__________________________________________________________________________\n% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: DEM_FEP_Least_Action.m 7512 2019-01-05 21:15:16Z karl $\n\n% generative model\n%========================================================================== % switch for demo\nspm_figure('GetWin','DEM'); clf\n\n% flow\n%--------------------------------------------------------------------------\ndt = 1/128; \nG.f = @(x,v,P,G) v(:) + [-P(1) P(1) 0; P(3) -1 -x(1); x(2) 0 P(2)]*x*dt;\n\n% set up\n%--------------------------------------------------------------------------\nT = 128; % length of trajectory\nN = 1024; % number of paths\ng = exp(-8); % amplitude of random fluctuations\ns = exp(2); % amplitude deviations\nP = [10; -8/3; 28]; % Rayleigh parameter\nx0 = [1; 1; 25];\nfor k = 1:N\n \n % random fluctuations (and action)\n %----------------------------------------------------------------------\n U.u = randn(T,3)*g;\n A(k) = (1/2)*sum(U.u(:).^2)/(g^2)/T;\n \n % random deviations in external states (and probability)\n %----------------------------------------------------------------------\n dx = randn*s;\n A(k) = A(k) + (1/2)*sum(dx.^2)/(s^2);\n \n % integrate timeseries with random initial hidden state\n %----------------------------------------------------------------------\n G.x = x0;\n G.x(3) = x0(3) + dx;\n x(:,:,k) = spm_int_L(P,G,U);\n \nend\n\n% plot ensemble densities\n%--------------------------------------------------------------------------\nsubplot(2,2,1),cla, hold on\ntd = fix(linspace(1,N,32));\nfor t = td\n plot(x(:,1,t),x(:,3,t),':','MarkerSize',1)\n plot(x(T,1,t),x(T,3,t),'r.','MarkerSize',8)\nend\naxis square, axis([-20 20 0 60])\ntitle('Paths from initial state','FontSize',16)\nxlabel('active state'),ylabel('external state'),drawnow\n\n% find trajectories that start and end at the same place\n%==========================================================================\n\n\n% get surprisal of final (active) state using sample density\n%--------------------------------------------------------------------------\nnb = 32;\nxN = squeeze(x(end,1,:));\n[n,a] = hist(xN,nb);\nn = 2*nb*n/sum(n);\nbar(a,n,1)\n\n% identify and plot trajectories with the same endpoints\n%--------------------------------------------------------------------------\nxT = -4;\nk = find(abs(xN - xT) < 1/8);\nfor t = k(:)'\n plot(x(:,1,t),x(:,3,t),'r')\nend\nplot([x0(1),x0(1)],[0 48],'r-.')\nplot([xT ,xT ],[0 48],'r-.')\n\n% paths as a function of time\n%--------------------------------------------------------------------------\nsubplot(2,2,2), hold on\npst = (1:T)*dt;\nfor t = k(:)'\n plot(pst,x(:,1,t),'r')\nend\ntitle('Autonomous paths','FontSize',16)\nxlabel('time (seconds)'),ylabel('active state'),axis square\n\n\nreturn\n\n% NB: numerical analysis of the action and surprisal\n%--------------------------------------------------------------------------\nfor i = 1:N\n [d,j] = min(abs(xn - xN(i)));\n L(i) = -log(n(j));\nend\nL = log(spm_softmax(L(:)));\nA = log(spm_softmax(A(:)));\n\nsubplot(2,2,2)\nplot(L,A,'.',L,L,':')\ntitle('Action and surprisal','FontSize',16)\nxlabel('Surprisal of final state'),ylabel('Action of path'),axis square\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/DEM_FEP_Least_Action.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6053998908145937}} {"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction weights_new = importance_weights(particle_system, new_rho)\n% IMPORTANCE_WEIGHTS: Function updates the importance weights for each\n% binary model based on the geometric bridge model and the empirical\n% distribution\n\n% Extract inputs to function\nmodels = particle_system.models;\nmodel_val = particle_system.model_val;\nold_wts = particle_system.weights;\nold_rho = particle_system.rho;\n\n% Determine the number of models and trials\n[n_models, ~] = size(models);\n\n% Declare a vector to store weights\nweights_new = zeros(n_models,1);\n\nfor i=1:n_models\n\n % Evaluate posterior ratios: pi(M) \\propto exp(rho*f(M))\n post_new_rho = new_rho*model_val(i);\n post_old_rho = old_rho*model_val(i);\n\n % Find the weights corresponding to each model\n weights_new(i) = old_wts(i)*exp(post_new_rho - post_old_rho);\n\nend\n\n% Check for NaNs and set weight to zero\nnan_weight = isnan(weights_new);\nweights_new(nan_weight) = 0;\n\n% Renormalize weights\nweights_new = weights_new/sum(weights_new);\n\nend", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/algorithms/SMC_Code/importance_weights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6053768057680744}} {"text": "function v = lexicmp(a,b, tol)\n\n% compare using lexicographical ordering the arrays\n%\n% v = lexicmp(a,b, tol);\n%\n% tol (default 1e-9) is a tolerance of equality.\n%\n% return -1 if ab, 0 if a=b.\n%\n% Copyright (c) 2008 Gabriel Peyre\n\ntol = 1e-9;\na = a(:);\nb = b(:);\n\nn = max(length(a),length(b));\na(n+1:end) = -Inf;\nb(n+1:end) = -Inf;\n\nfor i=1:n\n if a(i)b(i)+tol\n v = +1; return;\n end\nend\nv = 0;\n\n", "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/lexicmp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6053128312560422}} {"text": "function [ nodes_per_layer, n ] = hex_grid_approximate_n ( box, n_goal )\n\n%*****************************************************************************80\n%\n%% HEX_GRID_APPROXIMATE_N seeks a hex grid of about N nodes.\n%\n% Discussion:\n%\n% The parameter NODES_PER_LAYER controls the number of nodes, but\n% in a somewhat obscure way. This routine experiments with various\n% values until it is convinced it has the value of NODES_PER_LAYER\n% that comes as close as possible to producing N nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 March 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real BOX(2,2), the lower and upper corners\n% of the rectangular region.\n%\n% Input, integer N_GOAL, the desired number of nodes.\n%\n% Output, integer NODES_PER_LAYER, the number of nodes per layer\n% which produces a mesh with about N_GOAL nodes.\n%\n% Output, integer N, the number of nodes in the mesh.\n%\n m = 2;\n\n if ( n_goal <= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HEX_GRID_APPROXIMATE_N - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input value of N_GOAL = %d\\n', n_goal );\n error ( 'HEX_GRID_APPROXIMATE_N - Fatal error!' );\n end\n\n nodes_per_layer_low = 0;\n n_low = 0;\n\n nodes_per_layer = round ( sqrt ( n_goal ) );\n\n nodes_per_layer_high = n_goal;\n n_high = n_goal * n_goal;\n\n while ( 1 )\n\n n = hex_grid_n ( nodes_per_layer, box );\n\n if ( n == n_goal )\n break\n end\n\n if ( n < n_goal )\n nodes_per_layer_low = nodes_per_layer;\n n_low = n;\n else\n nodes_per_layer_high = nodes_per_layer;\n n_high = n;\n end\n\n if ( nodes_per_layer_low + 1 == nodes_per_layer_high )\n if ( n - n_low <= n_high - n )\n nodes_per_layer = nodes_per_layer_high;\n n = n_high;\n else\n nodes_per_layer = nodes_per_layer_low;\n n = n_low;\n end\n break\n end\n\n nodes_per_layer = ...\n round ( ( nodes_per_layer_low + nodes_per_layer_high ) / 2 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/square_hex_grid/hex_grid_approximate_n.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.605312822600004}} {"text": "function [ly] = nm2ly(nm)\n% Convert length from nanometers to light years.\n% Chad A. Greene 2012\nly = nm*1.057000834025e-25;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/nm2ly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.6052565034464636}} {"text": "function [M] = ft_connectivity_mim(inputdata, varargin)\n\n% FT_CONNECTIVITY_MIM computes the multivariate interaction measure from a\n% data-matrix containing the cross-spectral density. This implements the method\n% described in Ewald et al., Estimating true brain connectivity from EEG/MEG data\n% invariant to linear and static trasformations in sensor space. Neuroimage, 2012;\n% 476:488.\n%\n% Use as\n% [m] = hcp_connectivity_mim(inputdata, ...)\n%\n% The input data should be an array organized as\n% Channel x Channel x Frequency\n%\n% The output m contains the newChannel x newChannel x Frequency connectivity measure,\n% with newChannel equal to max(indices).\n%\n% Additional optional input arguments come as key-value pairs:\n% 'indices' = 1xN vector with indices of the groups to which the channels belong,\n% e.g. [1 1 2 2] for a 2-by-2 connectivity between 2 planar MEG channels.\n%\n%\n% See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS\n\n% Copyright (C) 2011-2014 by the Human Connectome Project, WU-Minn Consortium (1U54MH091657)\n% Copyright (C) 2021 Jan-Mathijs Schoffelen, DCCN\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\nindices = ft_getopt(varargin, 'indices');\n\nif isempty(indices) && isequal(size(inputdata(:,:,1)), [2 2])\n % simply assume two channels\n indices = [1 1 2 2];\nend\n\nsizein = size(inputdata);\nsizeout = [sizein 1];\nsizeout(1:2) = max(indices);\n\n% compute the inverse of the auto terms only once for speed up\ninvC = cell(sizeout(1),sizeout(3));\nfor kk = 1:sizeout(3)\n for k = 1:sizeout(1)\n invC{k,kk} = pinv(real(inputdata(indices==k,indices==k,kk)));\n end\nend\n\nM = zeros(sizeout);\nfor kk = 1:sizeout(3)\n for k = 1:sizeout(1)\n for m = 1:sizeout(1)\n indx1 = indices==k;\n indx2 = indices==m;\n %cs_aa_re = real(input(indx1,indx1));\n %cs_bb_re = real(input(indx2,indx2));\n cs_ab_im = imag(inputdata(indx1,indx2,kk));\n \n %inv_cs_bb_re = pinv(cs_bb_re);\n %inv_cs_aa_re = pinv(cs_aa_re);\n inv_cs_bb_re = invC{m,kk};\n inv_cs_aa_re = invC{k,kk};\n transp_cs_ab_im = transpose(cs_ab_im);\n M(k,m,kk) = trace(inv_cs_aa_re*cs_ab_im*inv_cs_bb_re*transp_cs_ab_im); % try to speed up by dividing calculation in steps\n end\n end\nend\n\n% taking the mldivide and mrdivide operators doesn't change the results, but speeds up by a factor of 4 over 1000 iterations (on LM Notebook)\n% m = trace(cs_aa_re\\cs_ab_im*inv_cs_bb_re*transp_cs_ab_im);\n\n% % % block_a=cs_aa_re\\cs_ab_im;\n% % % block_b=cs_bb_re\\transpose(cs_ab_im);\n% % % m = trace(block_a*block_b);\n\n% m = trace(cs_aa_re\\cs_ab_im*(cs_bb_re\\transpose(cs_ab_im)));\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/connectivity/ft_connectivity_mim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6052564823539704}} {"text": "function out = PeubSource(k, p, d, L, accuracy)\n%upper bound for the error probability of the binary source\n%achievability via sphere covering\n%k - source blocklength\n%p - source bias\n%d - distortion threshold\n%L = log M, where M is the number of representation points\n%accuracy = accuracy of Csum: 1 - more accurate, 0 - faster\n\n%\n% Created in 2012 by Victoria Kostina (vkostina@caltech.edu)\n%\n\nKbig = 80;\n\nif accuracy < 0\n %normal approximation\n Rd = h(p) - h(d);\n Vs = p*(1-p)*(log2((1-p)/p))^2;\n if p ~= 1/2 && k >= Kbig\n out = Q( (L - k*Rd - log2(k))/sqrt(k*Vs) );\n else\n out = PeubSource(L, k, p, d);\n end\n return;\nend\n\nif d == 0\n %lossless\n out = PeubSourceLossless(L, k, p);\nelseif p == 1/2\n %FAIR coin flip source\n out = PeubSourceFair(L, k, d);\nelse\n %arbitrary p source\n out = PeubSourceBiased(L, k, p, d);\nend\n% fprintf('SphereCoveringA: L = %i, k = %i, Peub = %f\\n', L, k, out);\n\n function out = PeubSourceLossless(L, k, p)\n csum = 0;\n kstar = k;\n for i = 0:k\n csum = csum + C(k, i, 'ub');\n if log2(csum) > L\n kstar = i - 1;\n break;\n end\n end\n out = 1 - binocdf(kstar,k,p);\n end\n\n function out = PeubSourceFair(L, k, d)\n if k <= Kbig\n out = 2^L *log(1 - Csum(k, floor(k*d), 'lb', accuracy) /(2^k));\n else\n out = -2^(L-k)*Csum(k, floor(k*d), 'lb', accuracy);\n end\n out = exp(out);\n end\n\n function out = PeubSourceBiased(L, k, p, d)\n q = max ( 0, (p-d)/(1-2*d));\n if q == 0\n q = p;\n end\n out = 0;\n for t = 0:k\n out = out + binopdfbound(t,k,p, 'ub')*e(k,t);\n if isnan(out)\n break;\n end\n end\n \n function out = e(k,t)\n out = 0;\n if 1\n for T = 0:k\n out = out + binopdfbound(T, k, q, 'ub')*Pwithin(k, t, T);\n end\n else\n T = round(q*k); %#ones\n out = Pwithin(k, t, T);\n end\n \n if k <= Kbig\n out = 2^L*log( 1 - out);\n out = exp(out);\n else\n out = exp(-2^L*out);\n end\n \n end\n \n function out = Pwithin(k,t, T)\n %y of type T is within a given x of type t - almost exact lower bound\n t0 = max ( 0, ceil( (t+T - k*d)/2) ); %# ones in 11111 zone (T ones in codewords)\n \n out = logC(T, t0, 'lb') + logC(k-T, t - t0, 'lb') - logC(k, t, 'ub');\n out = 2^out;\n end\n \n end\nend", "meta": {"author": "yp-mit", "repo": "spectre", "sha": "57af76799e4eb43aa707cc13c4c5220d281e0b78", "save_path": "github-repos/MATLAB/yp-mit-spectre", "path": "github-repos/MATLAB/yp-mit-spectre/spectre-57af76799e4eb43aa707cc13c4c5220d281e0b78/jscc/BMS-BSC/PeubSource.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6052564773588092}} {"text": "function y = BF_PreProcess(y,preProcessHow)\n% BF_PreProcess Preprocess a time series, y\n\n% ------------------------------------------------------------------------------\n% Copyright (C) 2020, Ben D. Fulcher ,\n% \n%\n% If you use this code for your research, please cite the following two papers:\n%\n% (1) B.D. Fulcher and N.S. Jones, \"hctsa: A Computational Framework for Automated\n% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).\n% DOI: 10.1016/j.cels.2017.10.001\n%\n% (2) B.D. Fulcher, M.A. Little, N.S. Jones, \"Highly comparative time-series\n% analysis: the empirical structure of time series and their methods\",\n% J. Roy. Soc. Interface 10(83) 20130048 (2013).\n% DOI: 10.1098/rsif.2013.0048\n%\n% This function is free software: you can redistribute it and/or modify it under\n% the terms of the GNU General Public License as published by the Free Software\n% Foundation, either version 3 of the License, or (at your option) any later\n% version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT\n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n% details.\n%\n% You should have received a copy of the GNU General Public License along with\n% this program. If not, see .\n% ------------------------------------------------------------------------------\n\nif ~isempty(preProcessHow)\n switch preProcessHow\n case 'diff1'\n % Takes incremental differences of the input time series\n y = diff(y);\n case 'rescale_tau'\n % Coarse-graining at a given scale, as in multiscale entropy approaches\n % Find first zero of the autocorrelation function\n tau = CO_FirstCrossing(y,'ac',0,'discrete');\n % Buffer the time series into nonoverlapping windows of length tau\n y_buffer = BF_MakeBuffer(y,tau);\n % Mean each window to get a coarse-grained time series\n y = mean(y_buffer,2);\n otherwise\n error('Unknown preprocessing setting: ''%s''',preProcessHow);\n end\nend\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/PeripheryFunctions/BF_PreProcess.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6052536025051308}} {"text": "function x = blend_rst_0dn ( r, s, t, n, bound_rst )\n\n%*****************************************************************************80\n%\n%% BLEND_RST_0DN extends vector data at corners into a cube.\n%\n% Diagram:\n%\n% 010-----r10-----110 011-----r11-----111\n% | . | | . |\n% | . | | . |\n% 0s0.....rs0.....1s0 0s1.....rs1.....1s1 S\n% | . | | . | |\n% | . | | . | |\n% 000-----r00-----100 001-----r01-----101 +----R\n% BOTTOM TOP\n%\n% 011-----0s1-----001 111-----1s1-----101\n% | . | | . |\n% | . | | . |\n% 01t.....0st.....00t 11t.....1st.....10t T\n% | . | | . | |\n% | . | | . | |\n% 010-----0s0-----000 110-----1s0-----100 S----+\n% LEFT RIGHT\n%\n% 001-----r01-----101 011-----r11-----111\n% | . | | . |\n% | . | | . |\n% 00t.....r0t.....100 01t.....r1t.....11t T\n% | . | | . | |\n% | . | | . | |\n% 000-----r00-----100 010-----r10-----110 +----R\n% FRONT BACK\n%\n% Discussion:\n%\n% BLEND_RST_0DN is equivalent to a trilinear finite element method.\n% Data along the edges, faces, and interior of the cube is\n% interpolated from the data at the corners.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% William Gordon,\n% Blending-Function Methods of Bivariate and Multivariate Interpolation\n% and Approximation,\n% SIAM Journal on Numerical Analysis,\n% Volume 8, Number 1, March 1971, pages 158-177.\n%\n% William Gordon and Charles Hall,\n% Transfinite Element Methods: Blending-Function Interpolation over\n% Arbitrary Curved Element Domains,\n% Numerische Mathematik,\n% Volume 21, Number 1, 1973, pages 109-129.\n%\n% William Gordon and Charles Hall,\n% Construction of Curvilinear Coordinate Systems and Application to\n% Mesh Generation,\n% International Journal of Numerical Methods in Engineering,\n% Volume 7, 1973, pages 461-477.\n%\n% Joe Thompson, Bharat Soni, Nigel Weatherill,\n% Handbook of Grid Generation,\n% CRC Press, 1999.\n%\n% Parameters:\n%\n% Input, real R, S, T, the (R,S,T) coordinates of the\n% point to be evaluated.\n%\n% Input, integer N, the dimension of the vector space.\n%\n% External, BOUND_RST, is a function which is given (R,S,T)\n% coordinates and an component value I, and returns XI, the value\n% of the I-th component of the N-vector at that point. BOUND_RST\n% will only be called for \"corners\", that is, for values (R,S,T)\n% where R, S and T are either 0.0 or 1.0. BOUND_RST has the form:\n% function xi = bound_rst ( r, s, t, i )\n%\n% Output, real X(N), the interpolated value at the\n% point (R,S,T).\n%\n for i = 1 : n\n%\n% Get the I-th coordinate component at the corners.\n%\n x000 = bound_rst ( 0.0, 0.0, 0.0, i );\n x001 = bound_rst ( 0.0, 0.0, 1.0, i );\n x010 = bound_rst ( 0.0, 1.0, 0.0, i );\n x011 = bound_rst ( 0.0, 1.0, 1.0, i );\n x100 = bound_rst ( 1.0, 0.0, 0.0, i );\n x101 = bound_rst ( 1.0, 0.0, 1.0, i );\n x110 = bound_rst ( 1.0, 1.0, 0.0, i );\n x111 = bound_rst ( 1.0, 1.0, 1.0, i );\n%\n% Interpolate the I-th coordinate component at the edges.\n%\n xr00 = blend_101 ( r, x000, x100 );\n xr01 = blend_101 ( r, x001, x101 );\n xr10 = blend_101 ( r, x010, x110 );\n xr11 = blend_101 ( r, x011, x111 );\n\n x0s0 = blend_101 ( s, x000, x010 );\n x0s1 = blend_101 ( s, x001, x011 );\n x1s0 = blend_101 ( s, x100, x110 );\n x1s1 = blend_101 ( s, x101, x111 );\n\n x00t = blend_101 ( t, x000, x001 );\n x01t = blend_101 ( t, x010, x011 );\n x10t = blend_101 ( t, x100, x101 );\n x11t = blend_101 ( t, x110, x111 );\n%\n% Interpolate the I-th component on the faces.\n%\n x0st = blend_112 ( s, t, x000, x001, x010, x011, x0s0, x0s1, x00t, x01t );\n\n x1st = blend_112 ( s, t, x100, x101, x110, x111, x1s0, x1s1, x10t, x11t );\n\n xr0t = blend_112 ( r, t, x000, x001, x100, x101, xr00, xr01, x00t, x10t );\n\n xr1t = blend_112 ( r, t, x010, x011, x110, x111, xr10, xr11, x01t, x11t );\n\n xrs0 = blend_112 ( r, s, x000, x010, x100, x110, xr00, xr10, x0s0, x1s0 );\n\n xrs1 = blend_112 ( r, s, x001, x011, x101, x111, xr01, xr11, x0s1, x1s1 );\n%\n% Interpolate the I-th coordinate component of the interior point.\n%\n x(i) = blend_123 ( r, s, t, x000, x001, x010, x011, x100, x101, x110, x111, ...\n xr00, xr01, xr10, xr11, x0s0, x0s1, x1s0, x1s1, x00t, x01t, x10t, x11t, ...\n x0st, x1st, xr0t, xr1t, xrs0, xrs1 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blend/blend_rst_0dn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6052178488038896}} {"text": "function model = gmm_estimate(data)\n% gmm_estimate Estimates a GMM on a set of points\n%\n% Originally a part of: Maggot (developed within EU project CogX)\n% Original author: Matej Kristan, 2009\n%\n% Input:\n% - data (matrix): Points for which to estimate a model\n%\n% Output:\n% - model (vector): values for corresponding points\n%\n\nN = length(data);\nmodel.Mu = data;\nmodel.Cov{N} = cell(N, 1);\nfor i = 1:N\n model.Cov{i} = 0;\nend\nmodel.w = ones(1,N) / N;\n\npdf0 = model;\n\n% first we'll spherize the distribution\n[Mu, C] = spherize(pdf0.Mu, pdf0.Cov, pdf0.w) ;\n[U, S, V] = svd(C) ;\nT = (diag(1./sqrt(diag(S))))*U' ;\n\npdf0.Mu = bsxfun(@minus, pdf0.Mu, Mu) ;\npdf0.Mu = T * pdf0.Mu ;\nfor i = 1 : length(pdf0.w)\n pdf0.Cov{i} = T*pdf0.Cov{i}*T' ;\nend\n\nC = T*C*T' ;\n% calculate the optimal bandwidth by Kristan's estimator\nH = optimal_bandwidth( pdf0.Mu, pdf0.Cov, pdf0.w, C, length(pdf0.w)) ;\n\npdf.Mu = Mu ;\npdf.Cov = {H} ;\npdf.w = 1 ;\n\niT = inv(T) ;\npdf.Mu = iT * pdf.Mu ;\npdf.Mu = bsxfun(@minus, pdf.Mu, -Mu) ;\nfor i = 1 : length(pdf.w)\n pdf.Cov{i} = iT * pdf.Cov{i} * iT';\nend\nH = pdf.Cov{1} ;\n\nfor i = 1:N\n model.Cov{i} = H ;\nend\n\nend\n\nfunction [new_mu, new_Cov] = spherize(Mu, Cov, w)\n\nif length(w)==1\n new_mu = Mu ;\n if ~isempty(Cov)\n new_Cov = Cov{1} ;\n else\n new_Cov = zeros(size(new_mu,1),size(new_mu,1)) ;\n end\n return ;\nend\n\nsumw = sum(w) ;\nw = w / sumw ;\nnew_mu = sum(bsxfun(@times,Mu, w),2) ;\n\nn = size(new_mu,1) ;\n\nif ~isempty(Cov)\n new_Cov = zeros(n,n) ;\n if n==1\n new_Cov = sum(w.*(cell2mat(Cov) + Mu.*Mu)) ;\n else\n for j=1:length(w)\n new_Cov = new_Cov + w(j)*( Cov{j} + Mu(:,j)*Mu(:,j)') ;\n end\n end\n new_Cov = new_Cov - new_mu*new_mu' ;\nelse\n new_Cov = zeros(n,n) ;\n if n==1\n new_Cov = sum(w.*(Mu.*Mu)) ;\n else\n for j=1:length(w)\n new_Cov = new_Cov + w(j)*( Mu(:,j)*Mu(:,j)') ;\n end\n end\n new_Cov = new_Cov - new_mu*new_mu' ;\n \nend\n\nend\n\nfunction [H] = optimal_bandwidth( Mu, Cov, w, Cov_smp, N_eff )\n\nd = size(Mu,1) ;\nG = (Cov_smp *(4 / ((d + 2) * N_eff))^(2 / (d + 4)));\n\nalpha_scale = 1 ;\nF = Cov_smp * alpha_scale; % for numerical stability. it could have been: F = Cov_smp;\n% could also constrain to say that F = identity!\nRf2 = integral_squared_hessian(Mu, w, Cov, F, G);\n\nh_amise = (N_eff ^ (-1) * det(F)^(-1 / 2) /( sqrt(4 * pi) ^ d * Rf2 * d ))^(1 / (d + 4)) ;\nH = (F * h_amise ^ 2) * alpha_scale ;\n\nend\n\nfunction I = integral_squared_hessian(Mu, w, Cov, F, G)\n% Calculates an integral over the squared Hessian of a Gaussian mixture\n% model.\n% Follows Wand and Jones \"Kernel Smoothing\", page 101., assuming H=h*F.\n\nI = NaN ;\nif ( isempty(Mu) )\n return;\nend\n% read dimension and number of components\n[ d, N ]= size(Mu) ;\n\n% precompute normalizer constNorm = ( 1 / 2pi)^(d/2)\nconstNorm = (1/(2*pi))^(d/2) ;\nI = 0 ;\n\n% test if F is identity for speedup\ndelta_F = sum(sum(abs(F-eye(size(F))))) ;\nif delta_F < 1e-3\n % generate a summation over the nonsymmetric matrix\n for l1 = 1 : N\n S1 = Cov{l1} + G ;\n Mu1 = Mu(:,l1) ;\n w1 = w(l1) ;\n for l2 = l1 : N\n S2 = Cov{l2};\n Mu2 = Mu(:,l2) ;\n w2 = w(l2) ;\n A = inv(S1 + S2) ;\n dm = (Mu1 - Mu2) ;\n m = dm'*A*dm ;\n f_t = constNorm*sqrt(det(A))*exp(-0.5*m) ;\n c = 2*sum(sum(A.*A'))*(1-2*m) + (1-m)^2 *trace(A)^2 ;\n \n % determine the weight of the term current\n if ( l1 == l2 )\n eta = 1 ;\n else\n eta = 2 ;\n end\n I = I + f_t*c*w2*w1*eta ;\n end\n end\nelse\n % generate a summation over the nonsymmetric matrix\n for l1 = 1 : N\n S1 = Cov{l1} ;\n Mu1 = Mu(:,l1) ;\n w1 = w(l1) ;\n for l2 = l1 : N\n S2 = Cov{l2} + G;\n Mu2 = Mu(:,l2) ;\n w2 = w(l2) ;\n A = inv(S1 + S2) ;\n dm = (Mu1 - Mu2) ;\n ds = dm'*A ;\n b = ds'*ds ;\n B = A - 2*b ;\n C = A - b ;\n \n f_t = constNorm*sqrt(det(A))*exp(-0.5*ds*dm) ;\n c = 2*trace(F*A*F*B) + trace(F*C)^2 ;\n \n % determine the weight of the term current\n if ( l1 == l2 )\n eta = 1 ;\n else\n eta = 2 ;\n end\n I = I + f_t*c*w2*w1*eta ;\n end\n end\nend\n\nend\n", "meta": {"author": "votchallenge", "repo": "toolkit-legacy", "sha": "2fb78d5301dadc102fb329b3a3f1bb02c670e8ee", "save_path": "github-repos/MATLAB/votchallenge-toolkit-legacy", "path": "github-repos/MATLAB/votchallenge-toolkit-legacy/toolkit-legacy-2fb78d5301dadc102fb329b3a3f1bb02c670e8ee/utilities/gmm_estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6052075214807409}} {"text": "function [fx] = f_metaToM(x,P,u,inF)\n% evolution function for meta-learning (k-ToM vs sequence)\n% function [fx] = f_metaToM(x,P,u,inF)\n% This function update the belief of an agent who has to identify whether\n% he faces an intentional agent (k-ToM) or an inanimate patter (sequence).\n% Learning here derives from VB-Laplace update rules of the agent's\n% posterior belief. practically speaking, this function (i) wraps modified\n% evolution functions of both k-ToM learning and sequence learning, and\n% (ii) updates the probability Pi that the agent is facing an intentional\n% agent given a new observation u (the probability that the agent faces an\n% inanimate pattern is 1-Pi).\n% IN:\n% - x: hidden states (see indexing in inF.indlev)\n% - P: evolution params:\n% P(1)= agent's prior opponent's (log-) volatility on opponent's params\n% P(2)= agent's (invsigmoid-) dilution coefficient\n% - u: sequence of past actions:\n% u(1)= opponent's last move\n% u(2)= learner's last move\n% u(3:K+2) = sequence of K past opponent's moves\n% - inF: input structure (see prepare_metaToM.m)\n% OUT:\n% - fx: updated hidden states\n% [see RecToMfunction.m and f_BSL.m]\n\not = u(1); % opponent's last move\nfx = NaN(size(x)); % initialize updated states\n\n% 1- update P(agent=kToM)\nPi0 = VBA_sigmoid(x(inF.meta.indx)); % prior P(agent=1)\n% partial forgetting of prior belief on opponent's type?\nif inF.meta.diluteP\n dc = VBA_sigmoid(P(inF.meta.indP)); % dilution coefficient\n Pi0 = (1-dc).*Pi0 + dc./2;\nend\n\n% Get k-ToM's likelihood, ie P(o|k-ToM).\nxktom = x(inF.ktom.indx);\ninFktom = inF.ktom.inF;\nntotPar = inFktom.indParev+inFktom.indParobs; % total number of params\nlevel = inFktom.lev; % depth of k-ToM's recursive beliefs (k=level)\nindlev = defIndlev(level,ntotPar); % states indexing\nif level==0 % 0-ToM [should be useless]\n mx = xktom(1); % E[log-odds of P(o=1)]\n Vx = exp(xktom(2)); % V[log-odds of P(o=1)]\n Els1 = VBA_Elogsig(mx,Vx);\n Els0 = VBA_Elogsig(-mx,Vx);\n ELL = ot.*Els1 + (1-ot).*Els0;\n h_kToM = exp(ELL); % P(o|k-ToM)\nelse\n Pk = VBA_sigmoid(x(1:(level-1))); % P(k'), with k'=0,...,k-1\n Pk = [Pk;max(0,1-sum(Pk))]; % insert last P(k'=k-1) \n f = zeros(level,1); % E[x(theta)]\n Vx = zeros(level,1); % V[x(theta)]\n for j=1:level % loop over possible opponent's levels (k'=j-1)\n f(j) = xktom(indlev(j).f); % E[x(theta)|k'=j-1]\n df = xktom(indlev(j).df); % d[x(theta)]/dtheta for k'=j-1\n Sig = exp(xktom(indlev(j).Par(2:2:2*ntotPar))); % V[theta|k'=j-1]\n Vx(j) = sum(Sig.*df.^2); % V[x(theta)|k'=j-1]\n end\n Els1 = VBA_Elogsig(f,Vx);\n Els0 = VBA_Elogsig(-f,Vx);\n ELL = ot.*Els1 + (1-ot).*Els0;\n h_kToM = exp(Pk'*ELL); % P(o|k-ToM)\nend\n\n% Get sequence's likelihood, ie P(o|seq).\nxseq = x(inF.seq.indx);\ninFseq = inF.seq.inF;\nuseq = u; % remove agent's previous move\nuseq(2) = [];\nK = inFseq.K; % sequence depth\nyb = useq(2:K+1); % previous outcomes\nif VBA_isWeird (yb)\n h_seq = 1/2;\nelse\n if K >0\n indSeq = bin2dec(num2str(yb'))+1; % index of sequence of previous outcomes\n else\n indSeq = 1;\n end\n m = xseq(indSeq);\n v = exp(xseq((2^K)+indSeq));\n Els1 = VBA_Elogsig(m,v);\n Els0 = VBA_Elogsig(-m,v);\n ELL = ot.*Els1 + (1-ot).*Els0;\n h_seq = exp(ELL); % P(o|seq)\nend\n\n% VB update of P(agent=kToM)\nPi = Pi0.*h_kToM./(Pi0.*h_kToM+(1-Pi0).*h_seq);\nfx(inF.meta.indx) = VBA_sigmoid(Pi, 'inverse', true);\n\n\n% 2- update k-ToM belief\ninFktom.metaweight = Pi;\nPar_ktom = P(inF.ktom.indP);\nuktom = u(1:2);\nfx(inF.ktom.indx) = RecToMfunction(xktom,Par_ktom,uktom,inFktom);\n\n% 3- update seq learner belief\ninFseq.metaweight = 1-Pi;\nPar_seq = P(inF.seq.indP);\nfx(inF.seq.indx) = f_BSL(xseq,Par_seq,useq,inFseq);\n\n\n\n\n\n", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/f_metaToM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6051028820240921}} {"text": "function b = fastnnls(x,y,tol,b)\n\n% $ Version 1.02 $ Date 28. July 1998 $ Not compiled $\n%\n% See also:\n% 'unimodal' 'monreg' 'fastnnls'\n%\n% FASTNNLS Fast non-negative least squares\n% The inputs are the matrix of predictor variables (x),\n% vector of predicted variable (y), and optional inputs\n% tolerance on the size of a regression coefficient that is\n% considered zero (tol), and initial guess for the regression\n% vector (b0). The output is the non-negatively constrained\n% least squares solution (b).\n%\n% If tol is set to 0, the default tolerance will be used.\n% \n% FASTNNLS is fastest when a good estimate of the regression\n% vector is input. This eliminates much of the computation\n% involved in determining which coefficients will be nonzero\n% in the final regression vector. This makes it very useful\n% in alternating least squares routines. Note that the input\n% b0 must be a feasible (i.e. nonnegative) solution.\n%\n% The FASTNNLS algorithm is based on the one developed by\n% Bro and de Jong, J. Chemometrics, Vol. 11, No. 5, 393-401, 1997\n%\n%I/O: b = fastnnls(x,y,tol,b0);\n%\n%See also: MCR, PARAFAC\n\n% Copyright (C) 1995-2006 Rasmus Bro & Claus Andersson\n% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk\n%\n% This program is free software; you can redistribute it and/or modify it under \n% the terms of the GNU General Public License as published by the Free Software \n% Foundation; either version 2 of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful, but WITHOUT \n% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS \n% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n% You should have received a copy of the GNU General Public License along with \n% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin \n% Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n\n[m,n] = size(x);\nif (nargin < 3 | tol == 0)\n tol = max(size(x))*norm(x,1)*eps;\nend\nif nargin < 4\n b = zeros(n,1);\nend\n\np = logical(zeros(1,n));\np(find(b>0)) = ones(size(find(b>0)));\nr = ~p;\n\nsp = x(:,p)\\y;\nb(find(p)) = sp;\nwhile min(sp) < 0\n b(find(b<0)) = zeros(size(find(b<0)));\n p = logical(zeros(1,n));\n p(find(b>0)) = ones(size(find(b>0)));\n r = ~p;\n sp = x(:,p)\\y;\n b(find(p)) = sp;\nend\n\nw = x'*(y-x*b);\n[wmax,ind] = max(w);\nflag = 0;\nwhile (wmax > tol & any(r))\n p(ind) = 1; \n r(ind) = 0;\n sp = x(:,p)\\y;\n while min(sp) < -tol\n tsp = zeros(n,1);\n tsp(find(p)) = sp; \n fb = find(b);\n rat = b(fb)./(eps+(b(fb)-tsp(fb)));\n alpha = min(rat(rat>tol));\n b = b + alpha*(tsp-b);\n p = b > tol;\n r = ~p; \n sp = x(:,p)\\y;\n end\n b(find(p)) = sp;\n w = x'*(y-x*b); \n [wmax,ind] = max(w);\n if p(ind)\n wmax = 0;\n end\nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/nway331/fnnls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6050517284646082}} {"text": "function [dx,dy]= centered_gradient(input,dx,dy, nx,ny)\ndx = zeros(1,round(nx*ny*+nx));\ndy = zeros(1,round(nx*ny*+nx));\nnx = round(nx);\nny = round(ny);\nsize(input);\nfor i = 1:ny-1\n for j = 1: nx-1\n k = round(i * nx + j);\n if(nx+k < length(input))\n dx(k) = 0.5*(input(k+1) - input(k-1));\n dy(k) = 0.5*(input(k+nx) - input(k-nx));\n end\n end\nend\nz = 1;\nfor j = 2: nx-1\n \n dx(z) = 0.5*(input(z+1) - input(j-1));\n dy(z) = 0.5*(input(z+nx) - input(z));\n\n k = (ny - 1) * nx + z;\nif(k < length(input))\n dx(k) = 0.5*(input(k+1) - input(k-1));\n dy(k) = 0.5*(input(k) - input(k-nx));\nend\n z = z +1;\nend\nfor i = 1: ny-1\n p = (i * nx)+1;\n if(p+nx < length(input))\n dx(p) = 0.5*(input(p+1) - input(p));\n dy(p) = 0.5*(input(p+nx) - input(p-nx));\n end\n k = (i+1) * nx - 1;\nif(k+nx < length(input))\n dx(k) = 0.5*(input(k) - input(k-1));\n dy(k) = 0.5*(input(k+nx) - input(k-nx));\nend\n\n \n dx(1) = 0.5*(input(2) - input(1));\n dy(1) = 0.5*(input(nx) - input(1));\n\n dx(nx-1) = 0.5*(input(nx-1) - input(nx-2));\n dy(nx-1) = 0.5*(input(2*nx-1) - input(nx-1));\n\n dx((ny-1)*nx) = 0.5*(input((ny-1)*nx + 1) - input((ny-1)*nx));\n dy((ny-1)*nx) = 0.5*(input((ny-1)*nx) - input((ny-2)*nx));\n if(ny*nx-2 0\n for k = 0 : Denominator\n tvec_mid = calc_dc(ts(i) + k*(ts(i+1) - ts(i))/Denominator, n_order, 0); % [1*8]vector\n nx(1, 8*(i-1) + 1 : 8*(i-1) + 8) = tvec_mid.*n(1);\n nx(1, 8*(i-1) + 1 + xll : 8*(i-1) + 8 + xll) = tvec_mid.*n(2);\n nx(1, 8*(i-1) + 1 + 2*xll : 8*(i-1) + 8 + 2*xll)= tvec_mid.*n(3);\n A(ieq,:) = nx;\n b(ieq,:) = dot(n, p);\n % dot(plane.n, p1 - plane.p) < 0 \n % => dot(plane.n, p1) - dot(plane.n, plane.p) < 0 \n % => dot(plane.n, p1) < dot(plane.n, plane.p) \n %% Ax < b\n ieq = ieq + 1;\n end\n end\n end\n \n \n% % Modify the number of iterations\n options = optimoptions('fmincon');\n options.MaxIterations = 2000; % Defaults = 1000\n lb = []; ub = []; x0 = []; \n p = quadprog(Q_all,f,A,b,Aeq,beq, lb,ub,x0, options);\n\n% \tp = quadprog(Q_all,f,A,b,Aeq,beq);\n \n minValue = p'*Q_all*p;\n\t\n px = p(1:xll,1);\n py = p(xll + 1:2*xll,1);\n pz = p(xll*2 + 1:3*xll,1);\nend\n\n", "meta": {"author": "LenaShengzhen", "repo": "AerialRobotics", "sha": "b3fe62f2df62cb91e8b5a53791868f9848c74005", "save_path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics", "path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics/AerialRobotics-b3fe62f2df62cb91e8b5a53791868f9848c74005/Motion_Planning/5Trajectory_Planning/QPbyUseSFC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6046672459843158}} {"text": "% set values, load data\nnx = 144;\nny = 256;\nnc = 8;\nniter = 250;\nmu = 2^-3;\nnlevels = 3;\nbeta = 2^8.5;\n\nload braindat;\nload kmask;\nload brainxinf;\n% load braindb4xinf;\nmask = true(nx,ny);\n\n% mask = abs(xinf) > 0.1*max(col(abs(xinf)));\n\n% generate and sample data\nA = (1/sqrt(nx*ny))*Gdft('mask', true(nx,ny), 'fftshift', 1, ...\n 'ifftshift', 1);\n\ndat = A*reshape(coilim, [nx*ny nc]); clear coilim;\n\nkmask = kmask((256-nx)/2+1:256-(256-nx)/2,:);\ndat = col(dat(col(kmask),:));\n\nn = kmask; b = 1:nx*ny;\nn = b(n); clear b;\n\n% build system matrices\nA = Apsm('knownfn', 'time', 'v', 1, 'n', n(:), 'smap', smap, 'immask', ...\n true(nx,ny), 'nk', nx*ny);\nW = Godwt1(mask, 'level', nlevels, 'wname', 'haar');\nP = Gdiag(1./(col(sum(abs(smap).^2,3)) + mu));\n\n% don't regularize approx coeffs\nbeta = beta*ones(nx,ny);\nbeta(1:nx/2^nlevels,1:ny/2^nlevels) = 0;\nbeta = col(beta);\n\n% initializations\nx = A'*dat; x = x./ col(sum(abs(smap).^2,3));\nx = x(mask);\nz = W*x;\neta = zeros(size(z));\n\n% system matrix\nA = Apsm('knownfn', 'time', 'v', 1, 'n', n(:), 'smap', smap, 'immask', ...\n mask, 'nk', nx*ny);\n\n% algorithm book-keeping\nshrink = @(t, a) (t-a .* sign(t)) .* (abs(t) > a);\ni = 0;\nthetime(1) = 0;\nxdist(1) = norm(col(x) - col(xinf(mask)));\n\n% go\ntic;\nwhile i < niter\n printm('iteration %d of %d', i+1, niter);\n \n z = shrink(W*x + eta, beta./mu);\n x = qpwls_pcg1(x, [A; sqrt(mu)*W], 1, [dat(:); sqrt(mu)*(z - eta)], ...\n 0, 'niter', 5, 'precon', P);\n eta = eta - (z - W*x);\n \n thetime(i+2) = toc;\n xdist(i+2) = norm(col(x) - col(xinf(mask)));\n i = i+1;\nend\ntoc;\nx = embed(x, mask);\nim(x)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/muckley/mri-sense/sing_al_p1_brain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.6046672334139204}} {"text": "function ref = buildRefTraj(q,dq,ddq,ref)\n% ref = buildRefTraj(q,dq,ddq,ref)\n%\n% This function computes the piecewise polynomial trajectories that make up\n% the reference trajectory for the feedback linearization\n%\n% INPUTS:\n% q = [nConfig, nTime] = reference trajectory in configuration space\n% dq = [nConfig, nTime] = dq/dt = rates in time for ref traj\n% ddq = [nConfig, nTime] = ddq/ddt = accelerations for ref traj\n% ref = prototype for ref struct, with fields:\n% .wn = natural frequency of the controller\n% .xi = damping ratio of the controller\n% .c = [1, nConfig] = mapping from configuration to phase\n% .H = [nMeasure, nConfig] = mapping from configuration to measurement\n%\n% OUTPUTS:\n%\n% ref = full ref struct, with added fields:\n% .pp = piecewise-polynomial trajectories for:\n% .h = reference measurement vector\n% .dh = dMeasurement/dPhase\n% .ddh = second derivative of measurements with respect to phase \n% .dhdt = dMeasurement/dTime\n% \n%\n\n% Trajectories: measurement and phase vs time:\nhRef = ref.H*q; % Target measurement\ndhRef = ref.H*dq;\nddhRef = ref.H*ddq;\npRef = ref.c*q; % Phase\ndpRef = ref.c*dq;\nddpRef = ref.c*ddq;\n\n% Compute derivatives wrt phase using chain rule:\ndhRefdp = dhRef./dpRef;\nddhRefddp = (ddhRef - dhRefdp.*ddpRef)./(dpRef.^2);\n\n% Represent trajectories as piecewise-polynomial\nref.pp.h = pchip(pRef,hRef);\nref.pp.dh = pchip(pRef,dhRefdp); % Derivative wrt phase (for ref traj)\nref.pp.dhdt = pchip(pRef,dhRef); % Derivative wrt time (for stabilization)\nref.pp.ddh = pchip(pRef,ddhRefddp);\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/feedbackLinearization/buildRefTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6046670446608865}} {"text": "%IMM_PREDICT Interacting Multiple Model (IMM) Filter prediction step\n%\n% Syntax:\n% [X_p,P_p,c_j,X,P] = IMM_PREDICT(X_ip,P_ip,MU_ip,p_ij,ind,dims,A,Q)\n%\n% In:\n% X_ip - Cell array containing N^j x 1 mean state estimate vector for\n% each model j after update step of previous time step\n% P_ip - Cell array containing N^j x N^j state covariance matrix for \n% each model j after update step of previous time step\n% MU_ip - Vector containing the model probabilities at previous time step\n% p_ij - Model transition probability matrix\n% ind - Indexes of state components for each model as a cell array\n% dims - Total number of different state components in the combined system\n% A - State transition matrices for each model as a cell array.\n% Q - Process noise matrices for each model as a cell array.\n%\n% Out:\n% X_p - Predicted state mean for each model as a cell array\n% P_p - Predicted state covariance for each model as a cell array\n% c_j - Normalizing factors for mixing probabilities\n% X - Combined predicted state mean estimate\n% P - Combined predicted state covariance estimate\n% \n% Description:\n% IMM filter prediction step.\n%\n% See also:\n% IMM_UPDATE, IMM_SMOOTH, IMM_FILTER\n\n% History:\n% 01.11.2007 JH The first official version.\n%\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% $Id: imm_update.m 111 2007-11-01 12:09:23Z jmjharti $\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nfunction [X_p,P_p,c_j,X,P] = imm_predict(X_ip,P_ip,MU_ip,p_ij,ind,dims,A,Q)\n % Number of models \n m = length(X_ip);\n \n % Default values for state mean and covariance\n MM_def = zeros(dims,1);\n PP_def = diag(20*ones(dims,1));\n\n % Normalizing factors for mixing probabilities\n c_j = zeros(1,m);\n for j = 1:m\n for i = 1:m\n c_j(j) = c_j(j) + p_ij(i,j).*MU_ip(i);\n end\n end\n\n % Mixing probabilities\n MU_ij = zeros(m,m);\n for i = 1:m\n for j = 1:m\n MU_ij(i,j) = p_ij(i,j) * MU_ip(i) / c_j(j);\n end\n end\n\n % Calculate the mixed state mean for each filter\n X_0j = cell(1,m);\n for j = 1:m\n X_0j{j} = zeros(dims,1);\n for i = 1:m\n X_0j{j}(ind{i}) = X_0j{j}(ind{i}) + X_ip{i}*MU_ij(i,j);\n end\n end\n \n % Calculate the mixed state covariance for each filter\n P_0j = cell(1,m);\n for j = 1:m\n P_0j{j} = zeros(dims,dims);\n for i = 1:m\n P_0j{j}(ind{i},ind{i}) = P_0j{j}(ind{i},ind{i}) + MU_ij(i,j)*(P_ip{i} + (X_ip{i}-X_0j{j}(ind{i}))*(X_ip{i}-X_0j{j}(ind{i}))');\n end\n end\n\n % Space for predictions\n X_p = cell(1,m);\n P_p = cell(1,m);\n\n % Make predictions for each model\n for i = 1:m\n [X_p{i}, P_p{i}] = kf_predict(X_0j{i}(ind{i}),P_0j{i}(ind{i},ind{i}),A{i},Q{i});\n end\n\n % Output the combined predicted state mean and covariance, if wanted.\n if nargout > 3\n % Space for estimates\n X = zeros(dims,1);\n P = zeros(dims,dims);\n \n % Predicted state mean\n for i = 1:m\n X(ind{i}) = X(ind{i}) + MU_ip(i)*X_p{i};\n end\n\n % Predicted state covariance\n for i = 1:m\n P(ind{i},ind{i}) = P(ind{i},ind{i}) + MU_ip(i)*(P_p{i} + (X_ip{i}-X(ind{i}))*(X_ip{i}-X(ind{i}))');\n end\n end\n \n \n", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/imm_predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.6046670291832408}} {"text": "% PROPAGATE A GAUSSIAN ERROR DISTRIBUTION OF EACH JOINT TO AN ERROR IN\n% END EFFECTORS' POSITION\n% AN ELLIPSE IS DRAWN TO REPRESENT THE ERROR IN POSITION\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\n\n%load arm parameters\nrobot= load_robot('example','scara')\n\n%find errors around pose\nq=[pi/4 3*pi/4 0 0];\n\n%Matriz de errores en las articulaciones\n% sigmaq1=sigmaq2=0.0017 rad, sigmaq3=0.01 m.\nsigmaq1=0.017;%rad, 0.01 grados\nsigmaq2=0.017;%rad\nsigmaq3=0.01;% m\nRq=[sigmaq1^2 0 0;\n 0 sigmaq2^2 0;\n 0 0 sigmaq3^2]\n\nteta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalfa = eval(robot.DH.alpha);\n\nJq = eval(robot.J)\n\n\nRp=Jq*Rq*Jq'\n\nT=directkinematic(robot, q);\n\ndrawrobot3d(robot,q), hold on\ndraw_ellipse([T(1,4),T(2,4)], Rp, 'r')", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/demos/more_demos/draw_errors_jacobian_scara.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.6046670291832407}} {"text": "function sp = esprit_1d(R, n, k, varargin)\n%ESPRIT_1D 1D ESPRIT for ULAs.\n%Syntax:\n% sp = ESPRIT_1D(R, n, design, wavelength, grid_size, ...);\n%Inputs:\n% R - Sample covariance matrix.\n% n - Number of sources.\n% k - 2*pi*inter_element_spacing/wavelength.\n% ... - Options:\n% 'Unit' - Can be 'radian', 'degree', or 'sin'. Default value is\n% 'radian'.\n% 'Displacement' - The displacement between the two overlapping\n% subarrays measured in number of element\n% spacings. Default value is 1.\n% Note: increasing this value will lead to\n% smaller unambiguous range. Make sure your DOAs\n% falls within the unambiguous range.\n% 'Formulation' - Either 'TLS' (Total Lease Squares) or 'LS'\n% (Least Squares). Default value is 'TLS'.\n% 'RowWeights' - Specifies the row weights with a vector or\n% string. Default value is 'Default', which\n% generates the following weight vector:\n% [1 sqrt(2) sqrt(3) ... sqrt(3) sqrt(2) 1]\n% You can disable row weighting by passing in\n% 'Identity' or 'Off'.\n%Output:\n% sp - Spectrum structure with the following fields:\n% x - An 1 x grid_size vector.\n% y - An 1 x grid_size vector. Calling `plot(x, y)` will plot the\n% spectrum.\n% x_est - An 1 x n vector storing the estimated DOAs.\n% x_unit - The same as the unit specified by 'Unit'.\n% resolved - Constant value true.\n% discrete - Constant value true.\n%Reference:\n% [1] H. L. Van Trees, Optimum array processing. New York: Wiley, 2002.\nuse_tls = true;\nds = 1;\nrow_weights = [];\nuse_row_weights = false;\nunit = 'radian';\nfor ii = 1:2:nargin-3\n option_name = varargin{ii};\n option_value = varargin{ii+1};\n switch lower(option_name)\n case 'unit'\n unit = option_value;\n case 'formulation'\n switch lower(option_value)\n case 'ls'\n use_tls = false;\n case 'tls'\n use_tls = true;\n otherwise\n error('Formulation must be either ''LS'' or ''TLS''.');\n end\n case 'displacement'\n if option_value < 1 || mod(option_value, 1) ~= 0\n error('Displacement must be an integer that is greater or equal to one.');\n end\n ds = option_value;\n case 'rowweights'\n if ischar(option_value)\n switch lower(option_value)\n case 'default'\n use_row_weights = true;\n case {'off', 'identity'}\n use_row_weights = false;\n otherwise\n error('Either specify the row weights manually or pass in ''Default'' to use the default weights, or ''Identity'', ''Off'' to disable row weighting.');\n end\n else\n use_row_weights = true;\n row_weights = option_value(:);\n end\n otherwise\n error('Unknow option \"%s\".', option_name);\n end\nend\nm = size(R, 1);\nif n > m - ds\n error('Too many sources.');\nend\nif ~isempty(row_weights) && length(row_weights) ~= m - ds\n error('The dimension of the row weights vector is not equal to (m - displacement).');\nend\n% ESPRIT\n[E, ~] = eig(0.5*(R + R'), 'vector');\nEs = E(:,end - n + 1:end);\n% apply weights if necessary\nif use_row_weights\n if isempty(row_weights)\n % default weights\n if mod(m - ds, 2) == 1\n w_max = (m - ds - 1)/2;\n row_weights = sqrt([1:w_max w_max + 1 w_max:-1:1])';\n else\n w_max = (m - ds)/2;\n row_weights = sqrt([1:w_max w_max:-1:1])';\n end\n end\n Es1 = bsxfun(@times, row_weights, Es(1:end - ds,:));\n Es2 = bsxfun(@times, row_weights, Es(ds + 1:end,:));\nelse\n Es1 = Es(1:end - ds,:);\n Es2 = Es(ds + 1:end,:);\nend\nif use_tls\n % TLS estimate\n C = [Es1 Es2];\n C = C'*C;\n C = 0.5*(C + C');\n [V, l] = eig(C, 'vector');\n [~, idx] = sort(real(l), 'descend');\n V = V(:,idx);\n V12 = V(1:n,n + 1:end);\n V22 = V(n + 1:end,n + 1:end);\n Phi = -V12/V22;\nelse\n % LS estimate\n Phi = (Es1'*Es1)\\(Es1'*Es2);\nend\n% convert z to spectrum\nz = eig(Phi);\nsp = struct();\nsp.x_est = sort(cm2doa(z, k*ds, unit));\nsp.x = sp.x_est;\nsp.x_unit = unit;\nsp.y = ones(1, n);\nsp.resolved = true;\nsp.discrete = true;\nend\n\n", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/estimator/esprit_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6045465129817222}} {"text": "function [F, M, trpy, drpy] = controller(qd, t, qn, params)\n% CONTROLLER quadrotor controller\n% The current states are:\n% qd{qn}.pos, qd{qn}.vel, qd{qn}.euler = [roll;pitch;yaw], qd{qn}.omega\n% The desired states are:\n% qd{qn}.pos_des, qd{qn}.vel_des, qd{qn}.acc_des, qd{qn}.yaw_des, qd{qn}.yawdot_des\n% Using these current and desired states, you have to compute the desired controls\n\n% =================== Your code goes here ===================\n\n% ordinary linear\n% % position controller params\n% Kp = ones(3,1)*30;\n% Kd = ones(3,1)*10;\n% \n% % attitude controller params\n% KpM = ones(3,1)*10000;\n% KdM = ones(3,1)*500;\n\n\n% position controller params\nKp = [15;15;30];\n% Kd = [15;15;10];\nKd = [12;12;10];\n\n% attitude controller params\nKpM = ones(3,1)*3000;\nKdM = ones(3,1)*300;\n\n% t = qd{qn}.vel_des/norm(qd{qn}.vel_des+eps);\n% n = qd{qn}.acc_des/norm(qd{qn}.acc_des+eps);\n% b = cross(t,n);\n% ep = ((qd{qn}.pos_des - qd{qn}.pos).*n).*n + ((qd{qn}.pos_des - qd{qn}.pos).*b).*b;\n% ev = qd{qn}.vel_des - qd{qn}.vel;\n\nacc_des = qd{qn}.acc_des + Kd.*(qd{qn}.vel_des - qd{qn}.vel) + Kp.*(qd{qn}.pos_des - qd{qn}.pos);\n% acc_des = qd{qn}.acc_des + Kd.*ev + Kp.*ep\n\n% Desired roll, pitch and yaw\nphi_des = 1/params.grav * (acc_des(1)*sin(qd{qn}.yaw_des) - acc_des(2)*cos(qd{qn}.yaw_des));\ntheta_des = 1/params.grav * (acc_des(1)*cos(qd{qn}.yaw_des) + acc_des(2)*sin(qd{qn}.yaw_des));\npsi_des = qd{qn}.yaw_des;\n\neuler_des = [phi_des;theta_des;psi_des];\npqr_des = [0;0; qd{qn}.yawdot_des];\n% Thurst\nqd{qn}.acc_des(3);\nF = params.mass*(params.grav + acc_des(3));\n% Moment\nM = params.I*(KdM.*(pqr_des - qd{qn}.omega) + KpM.*(euler_des - qd{qn}.euler));\n% =================== Your code ends here ===================\n\n% Output trpy and drpy as in hardware\ntrpy = [F, phi_des, theta_des, psi_des];\ndrpy = [0, 0, 0, 0];\n\nend\n", "meta": {"author": "yrlu", "repo": "quadrotor", "sha": "a7d951902567d75996d7b30cff7b2bc05e993602", "save_path": "github-repos/MATLAB/yrlu-quadrotor", "path": "github-repos/MATLAB/yrlu-quadrotor/quadrotor-a7d951902567d75996d7b30cff7b2bc05e993602/traj_planning/controller.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6045087865180439}} {"text": "function cplxPot\n% complex potential flow \n% using MATLAB analytical solutions \n%\n% $Ekkehard Holzbecher $Date: 2006/05/31 $\n%--------------------------------------------------------------------------\n% Baseflow\nH = 10; % thickness [L]\nh0 = 5; % reference piezometric head [L] \nK = 5.e-5; % hydraulic conductivity [L/T] \nQx0 = 0; % baseflow in x-direction [L^2/T]\nQy0 = 0; % baseflow in y-direction [L^2/T]\n\n% Wells\nxwell = [150 250]; % x-coordinates well position [L]\nywell = [0 0]; % y-coordinates well position [L]\nQwell = 1.e-4*[1 -1]; % pumping / recharge rates [L^3/T]\nR = [1 1]; % well radius [L]\n\n% Mesh\nxmin = 0; % minimum x-position of mesh [L]\nxmax = 400; % maximum x-position of mesh [L]\nymin = -100; % minimum y-position of mesh [L]\nymax = 100; % maximum y-position of mesh [L]\n\n% Reference point position in mesh\niref = 1; jref = 1;\n\n% Graphical output options\ngsurfh = 0; % piezometric head surface plot\ngcontf = 16; % no. filled contour lines (=0: none)\ngquiv = 0; % arrow field plot\ngflowp_fit = 0; % flowpaths forward in time\ngflowp_bit = 0; % no. flowpaths backward in time (=0: none)\ngflowp_dot = 0; % flowpaths with dots indicating speed\ngstream = 10; % streamfunction plot\n\n%----------------------------------------execution-------------------------------\nxvec = linspace(xmin,xmax,50);\nyvec = linspace(ymin,ymax,50);\n[x,y] = meshgrid (xvec,yvec); % mesh\n\nphi = -Qx0*x - Qy0*y;\npsi = -Qx0*y + Qy0*x;\nfor i = 1:size(xwell,2)\n r = sqrt((x-xwell(i)).*(x-xwell(i))+(y-ywell(i)).*(y-ywell(i))); \n phi = phi + (Qwell(i)/(2*pi))*log(r); % potential\n psi = psi + (Qwell(i)/(2*pi))*atan2((y-ywell(i)),(x-xwell(i)));\nend \nif h0 > H\n phi0 = -phi(iref,jref) + K*H*h0 - 0.5*K*H*H; \nelse\n phi0 = -phi(iref,jref) + 0.5*K*h0*h0; % reference potential \nend \nhc = 0.5*H+(1/K/H)*(phi+phi0); % head confined\nhu = sqrt ((2/K)*(phi+phi0)); % head unconfined\nphicrit = phi0 + 0.5*K*H*H; % transition confined / unconfined\nconfined = (phi>=phicrit); % confined / unconfined indicator\nh = confined.*hc+~confined.*hu; % head\n\n%---------------------------------------display messages-------------------\nif all(all(confined))\n display ('aquifer confined');\nelse\n if all(all(~confined)) \n display ('aquifer unconfined'); \n else\n display ('aquifer partially confined and unconfined'); \n end\nend \nif any(any(h<0)) \n display ('aquifer falls partially dry'); \n h = max(0, h);\nend\n[u,v] = gradient (-phi);\n\n%--------------------------------------graphical output--------------------\nif gsurfh \n figure; surf (x,y,h); % surface \nend \nfigure;\nif gcontf % filled contours \n colormap(winter); \n contourf (x,y,h,linspace(5-max(max(h-5)),5+max(max(h-5)),gcontf),'w'); \n colorbar; hold on;\nend\nif gquiv \n quiver (x,y,u,v,'y'); hold on; % arrow field\nend\nif gflowp_fit % flowpaths \n xstart = []; ystart = [];\n for i = 1:100\n if v(1,i) > 0 xstart = [xstart xvec(i)];...\n ystart = [ystart yvec(1)]; end\n if v(100,i) < 0 xstart = [xstart xvec(i)];...\n ystart = [ystart yvec(100)]; end\n if u(i,1) > 0 xstart = [xstart xvec(1)];...\n ystart = [ystart yvec(i)]; end\n if u(i,100) < 0 xstart = [xstart xvec(100)];...\n ystart = [ystart yvec(i)]; end\n end\n h = streamline (x,y,u,v,xstart,ystart);\n set (h,'Color','r'); \nend\nif gflowp_bit \n xstart = x0 + R*cos(2*pi*[1:1:gflowp_bit]/gflowp_bit); \n ystart = y0 + R*sin(2*pi*[1:1:gflowp_bit]/gflowp_bit);\n h = streamline (x,y,-u,-v,xstart,ystart);\n set (h,'Color','y') \nend\nif gflowp_dot\n [verts averts] = streamslice(x,y,u,v,gflowp_dot);\n sc = 10/mean(mean(sqrt(u.*u+v.*v)));\n iverts = interpstreamspeed(x,y,u,v,verts,sc); \n h = streamline(iverts);\n set (h,'Marker','.','Color','y','MarkerSize',18)\nend\nif gstream\n h = contour (x,y,psi,gstream,'k','LineWidth',1); \nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15646-environmental-modeling/cplxPot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6045087787389299}} {"text": "function cost = computeBoundariesCost(opts, X, theta_x, theta_y, theta_z, T)\n H = eye(4);\n H(1:3,1:3) = rotx(theta_x) * roty(theta_y) * rotz(theta_z);\n H(1:3,4) = T';\n X_transformed = H * X;\n cost_x_pos = sum(X_transformed(1, X_transformed(1,:)>0));\n cost_x_neg = sum(X_transformed(1, X_transformed(1,:)<0));\n \n cost_y_pos = sum(X_transformed(2, X_transformed(2,:)>0));\n cost_y_neg = sum(X_transformed(2, X_transformed(2,:)<0));\n \n cost_z_pos = sum(X_transformed(3, X_transformed(3,:)>0));\n cost_z_neg = sum(X_transformed(3, X_transformed(3,:)<0));\n figure(1)\n hold on\n scatter3(X_transformed(1,:), X_transformed(2,:), X_transformed(3,:), 'r.')\nend", "meta": {"author": "UMich-BipedLab", "repo": "extrinsic_lidar_camera_calibration", "sha": "d423c81e95c6de595e1dff79871385348b1c68f4", "save_path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration", "path": "github-repos/MATLAB/UMich-BipedLab-extrinsic_lidar_camera_calibration/extrinsic_lidar_camera_calibration-d423c81e95c6de595e1dff79871385348b1c68f4/computeBoundariesCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.6045078069831263}} {"text": "% File testLUSOL.m\n%\n% Script for testing various LUSOL factorizations\n% on the merged_S.mat matrix from 5 Dec 2006\n% (S = 62177 x 75644 916437).\n%\n% 25 Jan 2008: First experiments on this particular S.\n% All used options.FactorTol = 2.\n% S is badly scaled, but several options\n% find the rank to be 61833 (rank deficiency 344).\n\nload merged_S\n[m,n] = size(S)\nnnzS = nnz(S)\n\noptions = lusolSet;\noptions.FactorTol = 2.0;\noptions.Pivoting = 'TPP';\n\n%-----------------------------------------------------------------------------\n% Try cheapest method: L*U = S'\n% It returns rank 61833.\ndisp(' ')\ndisp('Factor S(transpose)')\nST = S';\ntic\n[L1,U1,p1,q1,options] = lusolFactor(ST,options);\ntoc\n\n% m 75644 >n 62177 Elems 916437 Amax 8.0E+05 Density 0.02\n% Singular(m>n) rank 61833 n-rank 344 nsing 344\n% Merit 95.3 lenL 306685 L+U 1051242 Cmpressns 0 Incres 14.71\n% Utri 556 lenU 744557 Ltol 2.00E+00 Umax 8.0E+05 Ugrwth 1.0E+00\n% Ltri 3633 dense1 0 Lmax 2.00E+00\n% bump 71455 dense2 0 DUmax 2.5E+03 DUmin 5.0E-01 condU 5.0E+03\n\nrank1 = options.Rank;\nrows1 = q1(1:rank1);\nS1 = S(rows1,:); % These should be independent rows of S.\n\n\n%-----------------------------------------------------------------------------\n% Try Rook Pivoting.\n% S is too badly scaled for this to be efficient.\n% Find column and row scales first.\ndisp(' ')\ndisp('Scale S now')\niprint = 1;\nscltol = 0.9;\ntic\n[cscale,rscale] = gmscal(S,iprint,scltol);\ndisp(' ')\ntoc\n\n% Apply scale factors to S.\nC = spdiags(cscale,0,n,n); Cinv = spdiags(1./cscale,0,n,n);\nR = spdiags(rscale,0,m,m); Rinv = spdiags(1./rscale,0,m,m);\nSS = Rinv*S*Cinv; % Scaled S\n%-----------------------------------------------------------------------------\n\n\n% Factor scaled SS with rook pivoting.\n% It returns rank 61833.\ndisp(' ')\ndisp('Factor scaled S now with rook pivoting')\noptions.Pivoting = 'TRP'; \ntic\n[L2,U2,p2,q2,options] = lusolFactor(SS,options);\ntoc\n\n% m 62177 n 62177 Elems 916437 Amax 1.0E+00 Density 0.02\n% Singular(m>n) rank 61833 n-rank 344 nsing 344\n% Merit 12.7 lenL 571936 L+U 1015445 Cmpressns 0 Incres 10.80\n% Utri 556 lenU 443509 Ltol 2.00E+00 Umax 3.2E+01 Ugrwth 3.2E+01\n% Ltri 2959 dense1 0 Lmax 2.00E+00\n% bump 72129 dense2 0 DUmax 2.0E+01 DUmin 5.4E-05 condU 3.8E+05\n\nrank3 = options.Rank;\nrows3 = q3(1:rank3);\nS3 = S(rows3,:); % These should be independent rows of S.\n\ndisp(' ')\ndisp('rows1, rows2, rows3 are 3 sets of independent rows of S')\ndisp(' S1, S2, S3 are those submatrices of S')\ndisp(' ')\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/base/solvers/lusolMex32bit/testLUSOL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.604454401077276}} {"text": "function [vertex,faces] = compute_saddle_points(Q,D,mask)\n\n% compute_saddle_points - compute saddle points of a Voronoi segmentation\n%\n% [vertex,faces] = compute_saddle_points(Q,D[,mask]);\n%\n% Q is a voronoi index map.\n% D is the distance function associated to the voronoi map.\n%\n% The vertex of the saddle points are first the double points (meeting\n% points of the voronoi diagram along the boundary of the domain) and\n% then the triple points (meeting points of 3 cells).\n%\n% Copyright (c) 2008 Gabriel Peyre\n\nif nargin==3 && not(isempty(mask))\n Q(mask==0) = -1;\nend\n\nQ1 = zeros(size(Q)+2)-1;\nQ1(2:end-1,2:end-1) = Q;\nV = [];\nv = Q1(1:end-1,1:end-1); V = [V v(:)];\nv = Q1(2:end,1:end-1); V = [V v(:)];\nv = Q1(1:end-1,2:end); V = [V v(:)];\nv = Q1(2:end,2:end); V = [V v(:)];\nV = sort(V,2);\nd = (V(:,1)~=V(:,2)) + (V(:,2)~=V(:,3)) + (V(:,3)~=V(:,4));\nV = V';\n\nI = find(d>=2);\n\n[vx,vy] = ind2sub(size(Q)+1, I);\nvx = clamp(vx,1,size(Q,1));\nvy = clamp(vy,1,size(Q,1));\nJ = vx+(vy-1)*size(Q,1);\n\n% sort according to distance\n[tmp,s] = sort(D(J), 1, 'descend');\nI = I(s);\n\n[vx,vy] = ind2sub(size(Q)+1, I);\nvx = clamp(vx,1,size(Q,1));\nvy = clamp(vy,1,size(Q,1));\nvertex = cat(1,vx',vy');\n\nV = sort(V, 1, 'descend');\nfaces = V(1:3, I);\n\nif isempty(vertex)\n % add farthest point\n [tmp,I] = max( D(:) );\n [vx,vy] = ind2sub(size(D), I(1));\n vertex = [vx;vy];\n faces = [-1 -1 -1]';\nend\n\nI = find( faces(1,:)<0 | faces(2,:)<0 | faces(3,:)<0 );\nJ = find( faces(1,:)>0 & faces(2,:)>0 & faces(3,:)>0 );\nfaces = cat(2, faces(:,I), faces(:,J) );\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/toolbox_fast_marching/compute_saddle_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6044543994280085}} {"text": "function [ algam, sgngam ] = r8_lgams ( x )\n\n%*****************************************************************************80\n%\n%% R8_LGAMS evaluates the log of |gamma(x)| and sign, for an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real ALGAM, the logarithm of the absolute value of\n% gamma ( X ).\n%\n% Output, real SGNGAM, the sign (+1 or -1 ) of gamma ( X ).\n%\n algam = r8_lngam ( x );\n sgngam = 1.0;\n\n if ( x <= 0.0 )\n\n k = floor ( mod ( - r8_aint ( x ), 2.0 ) + 0.1 );\n\n if ( k == 0 )\n sgngam = - 1.0;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_lgams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6043910555847744}} {"text": "function M = elliptopefactory(n, k)\n% Manifold of n-by-n psd matrices of rank k with unit diagonal elements.\n%\n% function M = elliptopefactory(n, k)\n%\n% A point X on the manifold is parameterized as YY^T where Y is a matrix of\n% size nxk. As such, X is symmetric, positive semidefinite. We restrict to\n% full-rank Y's, such that X has rank exactly k. The point X is numerically\n% represented by Y (this is more efficient than working with X, which may\n% be big). Tangent vectors are represented as matrices of the same size as\n% Y, call them Ydot, so that Xdot = Y Ydot' + Ydot Y and diag(Xdot) == 0.\n% The metric is the canonical Euclidean metric on Y.\n% \n% The diagonal constraints on X (X(i, i) == 1 for all i) translate to\n% unit-norm constraints on the rows of Y: norm(Y(i, :)) == 1 for all i.\n% The set of such Y's forms the oblique manifold. But because for any\n% orthogonal Q of size k, it holds that (YQ)(YQ)' = YY', we \"group\" all\n% matrices of the form YQ in an equivalence class. The set of equivalence\n% classes is a Riemannian quotient manifold, implemented here.\n%\n% Note that this geometry formally breaks down at rank-deficient Y's.\n% This does not appear to be a major issue in practice when optimization\n% algorithms converge to rank-deficient Y's, but convergence theorems no\n% longer hold. As an alternative, you may use the oblique manifold (it has\n% larger dimension, but does not break down at rank drop.)\n%\n% The geometry is taken from the 2010 paper:\n% M. Journee, P.-A. Absil, F. Bach and R. Sepulchre,\n% \"Low-Rank Optimization on the Cone of Positive Semidefinite Matrices\".\n% Paper link: http://www.di.ens.fr/~fbach/journee2010_sdp.pdf\n% \n% \n% Please cite the Manopt paper as well as the research paper:\n% @Article{journee2010low,\n% Title = {Low-rank optimization on the cone of positive semidefinite matrices},\n% Author = {Journ{\\'e}e, M. and Bach, F. and Absil, P.-A. and Sepulchre, R.},\n% Journal = {SIAM Journal on Optimization},\n% Year = {2010},\n% Number = {5},\n% Pages = {2327--2351},\n% Volume = {20},\n% Doi = {10.1137/080731359}\n% }\n% \n%\n% See also: obliquefactory symfixedrankYYfactory spectrahedronfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Bamdev Mishra, July 12, 2013.\n% Contributors:\n% Change log:\n% July 18, 2013 (NB):\n% Fixed projection operator for rank-deficient Y'Y.\n% \n% Aug. 8, 2013 (NB):\n% No longer using nested functions, to aim at Octave compatibility.\n% Sign error in right hand side of the call to minres corrected.\n% \n% June 24, 2014 (NB):\n% Used code snippets from obliquefactory to speed up projection,\n% retraction, egrad2rgrad and rand: the code now uses bsxfun for this.\n% \n% April 3, 2015 (NB):\n% Replaced trace(A'*B) by A(:)'*B(:) : equivalent but faster.\n\n% TODO: modify normalize_rows and project_rows to work without transposes.\n% TODO: enhance ehess2rhess to also use bsxfun.\n \n\t\n\tif ~exist('lyap', 'file')\n\t\twarning('manopt:elliptopefactory:slowlyap', ...\n\t\t ['The function lyap to solve Lyapunov equations seems not to ' ...\n\t\t\t\t'be available. This may slow down optimization over this ' ...\n\t\t\t\t'manifold significantly. lyap is part of the control system ' ...\n\t\t\t\t'toolbox.']);\n\tend\n \n \n M.name = @() sprintf('YY'' quotient manifold of %dx%d psd matrices of rank %d with diagonal elements being 1', n, k);\n \n M.dim = @() n*(k-1) - k*(k-1)/2; % Extra -1 is because of the diagonal constraint that\n \n % Euclidean metric on the total space\n M.inner = @(Y, eta, zeta) eta(:)'*zeta(:);\n \n M.norm = @(Y, eta) sqrt(M.inner(Y, eta, eta));\n \n M.dist = @(Y, Z) error('elliptopefactory.dist not implemented yet.');\n \n M.typicaldist = @() 10*k;\n \n M.proj = @projection;\n \n M.tangent = M.proj;\n M.tangent2ambient = @(Y, eta) eta;\n \n M.retr = @retraction;\n \n M.egrad2rgrad = @egrad2rgrad;\n \n M.ehess2rhess = @ehess2rhess;\n \n M.exp = @exponential;\n \n % Notice that the hash of two equivalent points will be different...\n M.hash = @(Y) ['z' hashmd5(Y(:))];\n \n M.rand = @() random(n, k);\n \n M.randvec = @randomvec;\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(Y) zeros(n, k);\n \n M.transp = @(Y1, Y2, d) projection(Y2, d);\n \n M.vec = @(Y, u_mat) u_mat(:);\n M.mat = @(Y, u_vec) reshape(u_vec, [n, k]);\n M.vecmatareisometries = @() true;\n \nend\n\n% Given a matrix X, returns the same matrix but with each column scaled so\n% that they have unit 2-norm.\n% See obliquefactory.\nfunction X = normalize_rows(X)\n X = X';\n\tnorms = sqrt(sum(X.^2, 1));\n\tX = bsxfun(@times, X, 1./norms);\n X = X';\nend\n\n% Orthogonal projection of each row of H to the tangent space at the\n% corresponding row of X, seen as a point on a sphere.\n% See obliquefactory.\nfunction PXH = project_rows(X, H)\n X = X';\n H = H';\n % Compute the inner product between each vector H(:, i) with its root\n % point X(:, i), that is, X(:, i).' * H(:, i). Returns a row vector.\n inners = sum(X.*H, 1);\n % Subtract from H the components of the H(:, i)'s that are parallel to\n % the root points X(:, i).\n PXH = H - bsxfun(@times, X, inners);\n PXH = PXH';\nend\n\n\n% Projection onto the tangent space, i.e., on the tangent space of\n% ||Y(i, :)|| = 1\nfunction etaproj = projection(Y, eta)\n [unused, k] = size(Y); %#ok\n eta = project_rows(Y, eta);\n\n % Projection onto the horizontal space\n YtY = Y'*Y;\n SS = YtY;\n AS = Y'*eta - eta'*Y;\n try\n % This is supposed to work and indeed return a skew-symmetric\n % solution Omega.\n Omega = lyap(SS, -AS);\n catch up %#ok\n % It can happen though that SS will be rank deficient. The\n % Lyapunov equation we solve still has a unique skew-symmetric\n % solution, but solutions with a symmetric part now also exist,\n % and the lyap function doesn't like that. So we want to\n % extract the minimum norm solution. This is also useful if lyap is\n\t\t% not available (it is part of the control system toolbox).\n mat = @(x) reshape(x, [k k]);\n vec = @(X) X(:);\n is_octave = exist('OCTAVE_VERSION', 'builtin');\n if ~is_octave\n [vecomega, unused] = minres(@(x) vec(SS*mat(x) + mat(x)*SS), vec(AS)); %#ok\n else\n [vecomega, unused] = gmres(@(x) vec(SS*mat(x) + mat(x)*SS), vec(AS)); %#ok\n end\n Omega = mat(vecomega);\n end\n % % Make sure the result is skew-symmetric (does not seem necessary).\n % Omega = (Omega-Omega')/2;\n etaproj = eta - Y*Omega;\nend\n\n% Retraction\nfunction Ynew = retraction(Y, eta, t)\n if nargin < 3\n t = 1.0;\n end\n Ynew = Y + t*eta;\n Ynew = normalize_rows(Ynew);\nend\n\n% Exponential map\nfunction Ynew = exponential(Y, eta, t)\n if nargin < 3\n t = 1.0;\n end\n\n Ynew = retraction(Y, eta, t);\n warning('manopt:elliptopefactory:exp', ...\n ['Exponential for fixed rank spectrahedron ' ...\n 'manifold not implemented yet. Used retraction instead.\\n' ...\n 'To disable this warning: warning(''off'', ''manopt:elliptopefactory:exp'')']);\nend\n\n% Euclidean gradient to Riemannian gradient conversion.\n% We only need the ambient space projection: the remainder of the\n% projection function is not necessary because the Euclidean gradient must\n% already be orthogonal to the vertical space.\nfunction rgrad = egrad2rgrad(Y, egrad)\n rgrad = project_rows(Y, egrad);\nend\n\n% Euclidean Hessian to Riemannian Hessian conversion.\n% TODO: speed this function up using bsxfun.\nfunction Hess = ehess2rhess(Y, egrad, ehess, eta)\n k = size(Y, 2);\n\n % Directional derivative of the Riemannian gradient\n scaling_grad = sum((egrad.*Y), 2); % column vector of size n\n scaling_grad_repeat = scaling_grad*ones(1, k);\n\n Hess = ehess - scaling_grad_repeat.*eta;\n\n scaling_hess = sum((eta.*egrad) + (Y.*ehess), 2);\n scaling_hess_repeat = scaling_hess*ones(1, k);\n % directional derivative of scaling_grad_repeat\n Hess = Hess - scaling_hess_repeat.*Y;\n\n % Project on the horizontal space\n Hess = projection(Y, Hess);\nend\n\n% Random point generation on the manifold\nfunction Y = random(n, k)\n Y = randn(n, k);\n Y = normalize_rows(Y);\nend\n\n% Random vector generation at Y\nfunction eta = randomvec(Y)\n eta = randn(size(Y));\n eta = projection(Y, eta);\n nrm = norm(eta, 'fro');\n eta = eta / nrm;\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/symfixedrank/elliptopefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6043910473426386}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Compare batch opt of Hawkes with online/stochastic opt of Hawkes\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear\n% data simulation\noptions.N = 50; % the number of sequences\noptions.Nmax = 1000; % the maximum number of events per sequence\noptions.Tmax = 100; % the maximum size of time window\noptions.tstep = 0.2;% the step length for computing sup intensity\noptions.M = 50; % the number of steps\noptions.GenerationNum = 5; % the number of generations\nD = 10; % the dimension of Hawkes processes\n\nnTest = 5;\nNout = 40;\n\ndisp('Fast simulation of Hawkes processes with exponential kernel')\npara.mu = rand(D,1)/D;\npara.A = rand(D, D);\npara.A = 0.65 * para.A./max(abs(eig(para.A)));\npara.A = reshape(para.A, [D, 1, D]);\npara.w = 1;\nSeqs = SimulationFast_Thinning_ExpHP(para, options);\n\nerr1 = zeros(nTest, Nout);\nerr2 = zeros(nTest, Nout);\n\nfor n = 1:nTest\n\n% initialize\nmodel.A = rand(D,1,D)./(D^2);\nmodel.mu = rand(D,1)./D;\nmodel.kernel = 'exp';\nmodel.w = 1;\nmodel.landmark = 0;\n\ndisp('Learning HP by batch opt')\nalg1.LowRank = 0;\nalg1.Sparse = 0;\nalg1.GroupSparse = 0;\nalg1.outer = Nout;\nalg1.rho = 0.1;\nalg1.inner = 1;\nalg1.thres = 1e-5;\nalg1.Tmax = [];\nalg1.storeErr = 1;\nalg1.storeLL = 0;\nalg1.truth = para;\nmodel1 = Learning_MLE_Basis( Seqs, model, alg1 );\n\ndisp('Learning HP by stochastic opt')\nalg2.LowRank = 0;\nalg2.Sparse = 0;\nalg2.GroupSparse = 0;\nalg2.epoch = Nout;\nalg2.rho = 0.1;\nalg2.eventbatch = 20;\nalg2.seqbatch = 10;\nalg2.historyL = 20;\nalg2.thres = 1e-5;\nalg2.Tmax = [];\nalg2.storeErr = 1;\nalg2.storeLL = 0;\nalg2.truth = para;\nmodel2 = Learning_MLE_Basis_Stoc( Seqs, model, alg2 );\n\nerr1(n,:) = model1.err(:,3)';\nerr2(n,:) = model2.err(:,3)';\n\nend\n\nem1 = mean(err1);\nev1 = std(err1);\nem2 = mean(err2);\nev2 = std(err2);\n\nfigure\nhold on\nerrorbar(em1, ev1)\nerrorbar(em2, ev2)\n%plot(1:Nout, model2.err(:,3), 'r-', 1:Nout, model1.err(:,3), 'b-');\nlegend('Batch HP', 'Stochastic HP')", "meta": {"author": "HongtengXu", "repo": "Hawkes-Process-Toolkit", "sha": "2548a41c7418b8edef3261ab4479cee4e8eaf071", "save_path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit", "path": "github-repos/MATLAB/HongtengXu-Hawkes-Process-Toolkit/Hawkes-Process-Toolkit-2548a41c7418b8edef3261ab4479cee4e8eaf071/Test_batchVSonline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6043747712831}} {"text": "function [IDVarNorm,IDVar,IDVarMax]=identVarGauss(w,mu,Sigma,xDim)\n%%IDENTVARGAUSS Given a Gaussian mixture representing uncertain target\n% states, determine the normalized and regular identity (ID)\n% variances, as defined in [1]. The identity variance is a\n% measure of uncertainty in the identities of which target is\n% which given the fact that the exact positions of the\n% targets are uncertain (Gaussian). The identity\n% variance provides a metric of how confident one is in\n% which target is which. This function provides an explicit\n% solution under the assumption that the joint probability\n% distribution function (PDF) of the targets is a Gaussian\n% mixture.\n%\n%INPUTS: w A numHypX1 or 1XnumHyp vector of weights of the hypotheses. Note\n% that w(i)>=0 for all i and sum(w)=1.\n% mu This is an (xDim*numTar)XnumHyp set of stacked state vectors for\n% all of the targets for each hypothesis. Alternatively, if the\n% target states are all uncorrelated, this can be an\n% xDimXnumTarXnumHyp hypermatrix.\n% Sigma This is an (xDim*numTar)XxDim*numTar)XnumHyp set of covariance\n% matrices for all of the stacked mean values in mu for each\n% hypothesis. If all of the target states are uncorrelated, an\n% xDimXxDimXnumTarXnumHyp set of hypermatrices for each target and\n% hypothesis individually can be passed.\n% xDim If the targets are correlated (mu is (xDim*numTar)XnumHyp in\n% size), then the state dimensions size xDim must be explicitly\n% provided.\n%\n%OUTPUTS: IDVarNorm The normalized ID variance. This is a value between 0\n% and 1. Zero means that the identities of the targets are\n% completely unknown, and one means that they are completely\n% certain.\n% IDVar The non-normalized ID variance.\n% IDVarMax The normalizing constant for the ID variance.\n%\n%This implements the algorithm of [1].\n%\n%EXAMPLE:\n%Two targets, two hypotheses, three dimensional states.\n% mu=zeros(3,2,2);\n% mu(:,1,1)=[20;-30;0;];\n% mu(:,1,2)=[-15;20;1];\n% mu(:,2,1)=[-15;20;3];\n% mu(:,2,2)=[-15;20;3];\n% Sigma(:,:,1,1)=4*eye(3);\n% Sigma(:,:,1,2)=Sigma(:,:,1,1);\n% Sigma(:,:,2,1)=[1, 0.5, -0.5;\n% 0.5, 2, 0.5;\n% -0.5,0.5, 3];\n% Sigma(:,:,2,2)=2*Sigma(:,:,2,1);\n% w=[0.5;0.5];\n% IDVarNorm0=identVarGauss(w,mu,Sigma)\n% %One will get an ID variance of about 0.8161. However, if all first target\n% %hypothese are moved far away from the second target, then the ambiguity is\n% %reduced.\n% mu(:,1,1)=mu(:,1,1)+500;\n% mu(:,1,2)=mu(:,1,2)+500;\n% IDVarNorm1=identVarGauss(w,mu,Sigma)\n% %Here, one gets an ID variance of essentially 1, meaning that the\n% %identities are very clear. on the other hand, if the targets are made to\n% %coincide, then the identity variance becomes zero.\n% mu(:,2,1)=mu(:,1,1);\n% mu(:,2,2)=mu(:,1,2);\n% Sigma(:,:,2,1)=Sigma(:,:,1,1);\n% Sigma(:,:,2,2)=Sigma(:,:,1,2);\n% IDVarNorm2=identVarGauss(w,mu,Sigma)\n% %Now, the identity variance is zero.\n%\n%REFERENCES:\n%[1] D. F. Crouse and P. Willett, \"Identity variance for multi-object\n% estimation,\" in Proceedings of SPIE: Signal and Data Processing of\n% Small Targets, vol. 8137, San Diego, CA, 21 Aug. 2011.\n%\n%November 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumHyp=length(w);\n\nif(nargin<4||isempty(xDim))\n xDim=size(mu,1);\nend\n\nif(ndims(mu)==3)\n numTar=size(mu,2);\n totalDim=xDim*numTar;\n mu=reshape(mu,totalDim,numHyp);\n \n SigmaNew=zeros(xDim*numTar,xDim*numTar,numHyp);\n for curHyp=1:numHyp\n span=1:xDim;\n for curTar=1:numTar\n SigmaNew(span,span,curHyp)=Sigma(:,:,curTar,curHyp);\n span=span+xDim;\n end\n end\n Sigma=SigmaNew;\nelse\n totalDim=size(mu,1);\n numTar=totalDim/xDim;\nend\n\n%The sizes of the adjusted inputs:\n%w is numHypX1 or 1XnumHyp\n%mu is xDimXnumTarXnumHyp\n%Sigma is (xDim*numTar)X(xDim*numTar)XnumHyp\n\nw=w(:);\n\n%The total number of permutations.\nnumTarPerm=factorial(numTar);\n\n%Here, we implement Equation 22. Note that the matrix H in Equation 31c is\n%the same if i and j are swapped.\nval1=0;%For the value of the first sum in Equation 22.\nval2=0;%For the value of the second sum in 22 and the value of Equation 23.\nfor curI=1:numTarPerm\n curTerm=w'*calcHTilde(w,mu,Sigma,numTar,xDim,curI,curI)*w;\n val1=val1+curTerm;\n val2=val2+curTerm;\n \n for curJ=curI+1:numTarPerm\n curTerm=w'*calcHTilde(w,mu,Sigma,numTar,xDim,curI,curJ)*w;\n val2=val2+2*curTerm;%The 2 is for the ordering i,j as well as j,i\n end\nend\n\nIDVar=val1/numTarPerm-val2/numTarPerm^2;\nIDVarMax=val2*(numTarPerm-1)/(numTarPerm^2);\nIDVarNorm=IDVar/IDVarMax;\nend\n\nfunction Ht=calcHTilde(w,mu,Sigma,numTar,xDim,i,j)\n%This function implements Equation 31c.\n\n numHyp=length(w);\n Ht=zeros(numHyp,numHyp);\n \n idxI=getPermIndices(i-1,numTar,xDim);\n idxJ=getPermIndices(j-1,numTar,xDim);\n \n for m=1:numHyp\n mumi=mu(idxI,m);\n Sigmami=Sigma(idxI,idxI,m);\n \n for n=m:numHyp\n munj=mu(idxJ,n);\n Sigmanj=Sigma(idxJ,idxJ,n);\n\n SigmamiInv=inv(Sigmami);\n SigmanjInv=inv(Sigmanj);\n \n Sigmamnij=inv(SigmamiInv+SigmanjInv);\n mumnij=Sigmamnij*(SigmamiInv*mumi+SigmanjInv*munj);\n\n val=0;\n for k=1:numHyp\n val=val+w(k)*GaussianD.PDF(mumnij,mu(:,k),Sigmamnij+Sigma(:,:,k));\n end\n val=val*w(m)*w(n)*GaussianD.PDF(mumi,munj,Sigmami+Sigmanj);\n \n Ht(m,n)=val;\n Ht(n,m)=val;\n end\n end\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Performance_Evaluation/identVarGauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6043747505083114}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% EUROPEAN OPTION PRICE COMPARISON (RUN SCRIPT)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Compare Methods For European Options Under Hestons Model\n% Author: Justin Kirkby\n% \n% Methods: 1) Kahl-Jackel-Lord Approach (Fourier, Heston Model)\n% 2) PROJ (Kirkby, 2015), European Levy/Heston \n% 3) CONV (Lord, Fang, Bervoets, Oosterlee, 2008), European Levy/Heston \n% 4) Carr-Madan (2008), European Levy/Heston Pricer \n% 5) Regime Switching Fourier PROJ (Cui, Kirkby, Nguyen, 2017) - Stoch Vol / RS Pricer\n% 6) Time-Changed Markov Chain (Cui, Kirkby, Nguyen, 2019), assumes rho = 0\n% 7) Monte Carlo, Using Lord et al (2010) Low-Bias Schemes\n% ... More to come\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\naddpath('../../PROJ/LEVY/European_Options')\naddpath('../../PROJ/LEVY/RN_CHF')\naddpath('../../PROJ/LEVY/Helper_Functions')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncall = 1; %For call use 1 (2 for put)\nS_0 = 100; %Initial price\nW = 100; %Strike %NOTE: no error handling in place for extreme values of W (increase grid if strike falls outside)\nr = .00; %Interest rate (NOTE: set to zero for comparison with Kahl-Jackel-Lord, based on Forward price)\nq = .00; %dividend yield (NOTE: keep this at zero for now)\nT = 0.5; %Time (in years)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 2) CHOOSE MODEL PARAMETERS (Levy Models)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nparams = {};\n\nparams.v0 = 0.02; % initial variance\nparams.theta = 0.02; % long term variance level\nparams.eta = 1.6; % rate of variance mean reversion\nparams.Sigmav = 0.3; % volatility of variance\nparams.rho = 0; % correlation between Brownian motions (NOTE: methods which assume rho=0 will display in output)\n\nmodelInput = getModelInput(6, T, r, q, params);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Kahl-Jackel-Lord (KJL) Approach\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Fourier/Heston/')\ntic\nprice_KJL = Heston1993KahlJaeckelLordRev3(call, S_0,W,T,0,r,q, params.v0, params.theta, params.rho, params.eta, params.Sigmav);\ntime_KJL = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PROJ (Kirkby, 2015)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nlogN = 12; %Uses N = 2^logN gridpoint \nL1 = 30;\n\n% ----------------------\nN = 2^logN; % grid roughly centered on [c1 - alph, c1 + alph]\nalpha = getTruncationAlpha(T, L1, modelInput, 6);\n\ntic\nprice_PROJ = PROJ_European(3, N, alpha, r, q, T, S_0, W, call, modelInput.rnCHF, modelInput.c1*T);\ntime_PROJ = toc;\n\nref = PROJ_European(3, 2^15, 2*alpha, r, q, T, S_0, W, call, modelInput.rnCHF, modelInput.c1*T);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Time-Changed Markov Chain Approximation (Cui, Kirkby, Nguyen, 2019)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../PROJ/TIME_CHANGED/European/')\naddpath('../../PROJ/STOCHASTIC_VOL/Helper_Functions')\nparams.model = 1;\n\nParamsCtmc.varGridMult = .01;\nParamsCtmc.gamma = 6; % Heston gamma = 3 is good for T ~ 1\nParamsCtmc.Nx = 100; %the number of Markov states\n\nProjParams.order = 3;\nProjParams.alph = 2^2;\nProjParams.N_proj = 2^8;\n\nn = 0; % number of time steps in time disretization... set to 0 to do continuous time version\nhFunc = @(u) u; % tau = int h(X_s) ds\nlevyExponent = @(z) -0.5*1i*z - 0.5*z.^2; \n\ntic\nprice_TCMC = PROJ_TimeChanged_Levy_European(r,q,S_0,T,W,call, levyExponent, hFunc, n, params, ParamsCtmc, ProjParams);\ntime_TCMC = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% SV-PROJ\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../PROJ/STOCHASTIC_VOL/European/')\naddpath('../../PROJ/STOCHASTIC_VOL/Barrier/')\naddpath('../../PROJ/STOCHASTIC_VOL/Helper_Functions/')\n% This version uses the Stoch Vol pricer for Barrier options to price European (More of a multiple purpose method)\nif call == 1\n down = 1; H = S_0 / 8; % TODO: this needs to account for the variance of the underlying.\nelse\n down = 0; H = S_0 * 8;\nend\n\nN = 2^10; %number of points in density expansion... Value grid size is K:=N/2\nm_0 = 40; % number of CTMC grid points\ngamma = 5; % CTMC grid width param\ngridMethod = 4; gridMultParam = 0.2; M = 1; psi_J = @(u)0*[u>0];\nalpha = 5;\n\ntic\nprice_SVP = Barrier_StochasticVol_func(N,alpha,call,down,S_0,W,H,M,r,T,m_0,psi_J,1, params, gridMethod, gamma, gridMultParam);\ntime_SVP = toc;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Carr-Madan Fourier Method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Fourier/CarrMadan/')\nN = 2^15;\ntic\nprice_CM = CarrMadan_European_Price_Strikes(S_0, W, modelInput.rnCHF, N, T, r, q, call);\ntime_CM = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% CONV Fourier Method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Fourier/CONV/')\nN = 2^16;\ntic\nprice_CONV = CONV_European_Price(S_0, W, modelInput.rnCHF, T, r, call, N, alpha);\ntime_CONV = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Monte Carlo\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Monte_Carlo/')\naddpath('../../Monte_Carlo/European/')\n\ntic\nN_sim = 10^5; M = 800; disc = exp(-r*T); scheme = 5;\nSpath = Simulate_Heston_Euler_Schemes( N_sim, M, T, S_0, r, q, params, scheme);\n[price_MC, stdErr] = Price_MC_European_Strikes_func(Spath, disc, call, W );\nprice_MC_L = price_MC - 2*stdErr; price_MC_U = price_MC + 2*stdErr;\ntime_MC = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% COMPARE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfprintf('\\n---------------------------------------------\\n')\nfprintf('Method | Price | Err | CPU \\n')\nfprintf('---------------------------------------------\\n')\nfprintf('PROJ | %.8f | %.2e | %.4f \\n', price_PROJ, abs(price_PROJ-ref), time_PROJ)\nfprintf('KJL | %.8f | %.2e | %.4f \\n', price_KJL, abs(price_KJL-ref), time_KJL)\nfprintf('CONV | %.8f | %.2e | %.4f \\n', price_CONV, abs(price_CONV-ref), time_CONV)\nfprintf('Carr-Madan | %.8f | %.2e | %.4f \\n', price_CM, abs(price_CM-ref), time_CM)\nfprintf('TC-MC (rho=0)| %.8f | %.2e | %.4f \\n', price_TCMC, abs(price_TCMC-ref), time_TCMC)\nfprintf('SV-PROJ | %.8f | %.2e | %.4f \\n', price_SVP, abs(price_SVP-ref), time_SVP)\nfprintf('MC-Euler |[%.3f,%.3f]| %.2e | %.4f \\n', price_MC_L, price_MC_U, abs(price_MC-ref), time_MC)\n\n\n", "meta": {"author": "jkirkby3", "repo": "PROJ_Option_Pricing_Matlab", "sha": "3859a390f395e452ad61440f95a5714dd8fb4d90", "save_path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab", "path": "github-repos/MATLAB/jkirkby3-PROJ_Option_Pricing_Matlab/PROJ_Option_Pricing_Matlab-3859a390f395e452ad61440f95a5714dd8fb4d90/Comparisons/Heston/Script_Compare_European.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6043747428675127}} {"text": "function Frames=calib_towncenter(Frames,namefile)\n\nfid=fopen(namefile);\nC=textscan(fid,'%s');\nc=C{1};\n\nfx=str2double(cell2mat(c(3)));\nfy=str2double(cell2mat(c(6)));\npx=str2double(cell2mat(c(9)));\npy=str2double(cell2mat(c(12)));\nsk=str2double(cell2mat(c(15)));\ntx=str2double(cell2mat(c(18)));\nty=str2double(cell2mat(c(21)));\ntz=str2double(cell2mat(c(24)));\nrx=str2double(cell2mat(c(27)));\nry=str2double(cell2mat(c(30)));\nrz=str2double(cell2mat(c(33)));\nrw=str2double(cell2mat(c(36)));\nk1=str2double(cell2mat(c(39)));\nk2=str2double(cell2mat(c(42)));\np1=str2double(cell2mat(c(45)));\np2=str2double(cell2mat(c(48)));\n\nR=[1-2*ry^2-2*rz^2,2*rx*ry-2*rz*rw,2*rx*rz+2*ry*rw;2*rx*ry+2*rz*rw,1-2*rx^2-2*rz^2,2*ry*rz-2*rx*rw;2*rx*rz-2*ry*rw,2*ry*rz+2*rx*rw,1-2*rx^2-2*ry^2];\n\nR=[R,[tx;ty;tz]];\n\nK=[fx,0,px;0,fy,py;0,0,1];\n\nP=K*R;\nP(:,3)=[];\n\nR(:,3)=[];\n\nfor fr=1:numel(Frames)\n for p=1:numel(Frames(fr).id)\n \n u=double(Frames(fr).ximg(p));\n v=double(Frames(fr).yimg(p));\n \n x2=(u-px)/fx;\n y2=(v-py)/fy;\n \n Pu=undistort(k1,k2,p1,p2,[x2;y2]);\n xu=Pu(1);\n yu=Pu(2);\n\n Pd2=homotrans(inv(R),[Pu;1]);\n \n % Pd=homotrans(inv(P),[u;v;1]);\n \n Frames(fr).x(p)=Pd2(1);\n Frames(fr).y(p)=Pd2(2);\n Frames(fr).z(p)=0;\n Frames(fr).vx(p)=0;\n Frames(fr).vy(p)=0;\n Frames(fr).vz(p)=0;\n Frames(fr).ximg(p)=round(Frames(fr).ximg(p));\n Frames(fr).yimg(p)=round(Frames(fr).yimg(p));\n end\nend\n \n\nend\n\nfunction x=undistort(k1,k2,p1,p2,xd)\n\n xd=double(xd);\n x = xd; % initial guess\n \n for kk=1:20,\n \n r_2 = sum(x.^2);\n k_radial = double(1 + k1 * r_2 + k2 * r_2.^2 );\n delta_x = double([2*p1*x(1,:).*x(2,:) + p2*(r_2 + 2*x(1,:).^2);\n p1 * (r_2 + 2*x(2,:).^2)+2*p2*x(1,:).*x(2,:)]);\n x = (xd - delta_x)./(ones(2,1)*k_radial);\n \n end;\n \nend\n\nfunction t = homotrans(P,v)\n\n[dim,npts] = size(v);\n\nif ~all(size(P)==dim)\n error('Transformation matrix and point dimensions do not match');\nend\n\nt = P*v; % Transform\n\nfor r = 1:dim-1 % Now normalise\n t(r,:) = t(r,:)./t(end,:);\nend\n\nt(end,:) = ones(1,npts);\n\nend\n", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/utils/camera/calib_towncentre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6042244247742069}} {"text": "function rmse_v = navego_rmse (nav, gnss, ref_n, ref_g)\n% navego_rmse: calculates the Root Mean Squared Errors (RMSE) between \n% a INS/GNSS system and a reference data structure, and between GNSS-only \n% solution and a reference data structure.\n%\n% INPUT\n% nav_e, INS/GNSS integration data structure.\n% gnss, GNSS data structure.\n% ref_n, Reference data structure ajusted for INS/GNSS estimations.\n% ref_g, Reference data structure ajusted for GNSS measurements.\n%\n% OUTPUT\n% rmse_v, vector with all RMSE.\n% RMSE_roll; RMSE_pitch; RMSE_yaw; (degrees, degrees, degrees) \n% RMSE_vn; RMSE_ve; RMSE_vd; (m/s, m/s, m/s) \n% RMSE_lat; RMSE_lon; RMSE_h; (m, m, m)\n% RMSE_vn_g; RMSE_ve_g; RMSE_vd_g;(m/s, m/s, m/s)\n% RMSE_lat_g; RMSE_lon_g; RMSE_h_g; (m, m, m)\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n%\n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% Version: 006\n% Date: 2021/03/16\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nD2R = (pi/180); % degrees to radians\nR2D = (180/pi); % radians to degrees\n\n%% INS/GNSS ATTITUDE RMSE\n\nRMSE_roll = rmse (nav.roll , ref_n.roll) .* R2D;\nRMSE_pitch = rmse (nav.pitch, ref_n.pitch) .* R2D;\n\n% Differences greater than 300 deg are avoided when comparing yaw angles.\n% The idea is to avoid to compare values of yaw angles when, for example, the \n% reference yaw is near pi and the nav yaw is near -pi. Both yaw angles, pi\n% and -pi, represent the same heading angle (moving South).\n\nnav.yaw = correct_yaw(nav.yaw);\nref_n.yaw = correct_yaw(ref_n.yaw);\n\nidx = ( abs(nav.yaw - ref_n.yaw) < (300 * D2R) );\nRMSE_yaw = rmse ( nav.yaw(idx), ref_n.yaw(idx) ) .* R2D;\n\n%% INS/GNSS VELOCITY RMSE\n\nif (isfield(nav, 'vel') && isfield(ref_n, 'vel'))\n RMSE_vn = rmse (nav.vel(:,1), ref_n.vel(:,1));\n RMSE_ve = rmse (nav.vel(:,2), ref_n.vel(:,2));\n RMSE_vd = rmse (nav.vel(:,3), ref_n.vel(:,3));\nelse\n RMSE_vn = NaN;\n RMSE_ve = NaN;\n RMSE_vd = NaN;\n warning('navego_rmse: no NED velocity field was found in INS/GNSS data.');\nend\n\n%% INS/GNSS POSITION RMSE\n\n[RM,RN] = radius(ref_n.lat);\nLAT2M = (RM + ref_n.h); % Coefficient for lat, radians to meters\nLON2M = (RN + ref_n.h) .* cos(ref_n.lat); % Coefficient for lon, radians to meters\n\nRMSE_lat = rmse (nav.lat.* LAT2M, ref_n.lat.* LAT2M) ;\nRMSE_lon = rmse (nav.lon.* LON2M, ref_n.lon.* LON2M) ;\nRMSE_h = rmse (nav.h, ref_n.h);\n\n%% GNSS VELOCITY RMSE\n\nif (isfield(gnss, 'vel') && isfield( ref_g, 'vel'))\n RMSE_vn_g = rmse (gnss.vel(:,1), ref_g.vel(:,1));\n RMSE_ve_g = rmse (gnss.vel(:,2), ref_g.vel(:,2));\n RMSE_vd_g = rmse (gnss.vel(:,3), ref_g.vel(:,3));\nelse\n RMSE_vn_g = NaN;\n RMSE_ve_g = NaN;\n RMSE_vd_g = NaN;\n warning('navego_rmse: no NED velocity field was found in GNSS data.');\nend\n\n%% GNSS POSITION RMSE\n\n[RMg,RNg] = radius(ref_g.lat);\nLAT2Mg = (RMg + ref_g.h); % Coefficient for lat, radians to meters\nLON2Mg = (RNg + ref_g.h) .* cos(ref_g.lat); % Coefficient for lon, radians to meters\n\nRMSE_lat_g = rmse (gnss.lat.* LAT2Mg, ref_g.lat.* LAT2Mg) ;\nRMSE_lon_g = rmse (gnss.lon.* LON2Mg, ref_g.lon.* LON2Mg) ;\nRMSE_h_g = rmse (gnss.h, ref_g.h);\n\n%%\n\nrmse_v = [ RMSE_roll; RMSE_pitch; RMSE_yaw; \n RMSE_vn; RMSE_ve; RMSE_vd;\n RMSE_lat; RMSE_lon; RMSE_h;\n RMSE_vn_g; RMSE_ve_g; RMSE_vd_g;\n RMSE_lat_g; RMSE_lon_g; RMSE_h_g; ];\nend\n ", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/performance-analysis/navego_rmse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.6042244137048363}} {"text": "function temp = tempdim(temp,from,to)\n%TEMPDIM Convert temperature units\n%\n% tempOut = TEMPDIM(tempIn, FROM, TO) converts tempIn from the units\n% specified by the string FROM to the units specified by the string\n% TO. FROM and TO are case-insensitive, and may equal any of the\n% following:\n%\n% 'farenheit', 'far', or 'f'\n% 'rankine', 'rank', or 'r'\n% 'celsius', 'cel' or 'c'\n% 'kelvin', 'kel', or 'k'\n%\n% See also FAR2CEL, FAR2KEL, FAR2RANK,\n% CEL2FAR, CEL2KEL, CEL2RANK,\n% KEL2FAR, KEL2CEL, KEL2RANK,\n% RANK2FAR, RANK2CEL, RANK2KEL\n\nerror(nargchk(3, 4, nargin, 'struct'))\n\n% Warn and convert to real if TEMP is complex.\ntemp = ignoreComplex(temp, mfilename, 'TEMP');\n\n% Convert units only if there's something to change.\nif ~strcmp(from, to)\n temp = applyconversion(temp, from, to);\nend\n\nfunction temp = applyconversion(temp, from, to)\n\nfrom = lower(from);\nto = lower(to);\n\ntoIsSupported = true;\nfromIsSupported = true;\n\nswitch from\n case {'farenheit','far','f'}\n switch to\n case {'rankine','rank','r'}\n temp = far2rank(temp);\n case {'celsius','cel','c'}\n temp = far2cel(temp);\n case {'kelvin', 'kel','k'}\n temp = far2kel(temp);\n otherwise\n toIsSupported = false;\n end\n case {'rankine','rank','r'}\n switch to\n case {'farenheit','far','f'}\n temp = rank2far(temp);\n case {'celsius','cel','c'}\n temp = rank2cel(temp);\n case {'kelvin', 'kel','k'}\n temp = rank2kel(temp);\n otherwise\n toIsSupported = false;\n end\n case {'celsius','cel','c'}\n switch to\n case {'rankine','rank','r'}\n temp = cel2rank(temp);\n case {'farenheit','far','f'}\n temp = cel2far(temp);\n case {'kelvin', 'kel','k'}\n temp = cel2kel(temp);\n otherwise\n toIsSupported = false;\n end\n case {'kelvin', 'kel','k'}\n switch to\n case {'farenheit','far','f'}\n temp = kel2far(temp);\n case {'celsius','cel','c'}\n temp = kel2cel(temp);\n case {'rankine','rank','r'}\n temp = kel2rank(temp);\n otherwise\n toIsSupported = false;\n end\n otherwise\n fromIsSupported = false;\nend\n\nassert(toIsSupported, 'map:distdim:UnsupportedToUnits', ...\n 'Unsupported ''TO'' units: %s.', to)\n\nassert(fromIsSupported, 'map:distdim:UnsupportedFromUnits', ...\n 'Unsupported ''FROM'' units: %s.', from)", "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/32218-temperature-conversion-toolbox/Temperature/tempdim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6041950822022568}} {"text": "function [fLogLikelihood] = calc_AkiLikelihood(mCatalog, fBValue, fBinning)\n% function [fLogLikelihood] = calc_AkiLikelihood(mCatalog, fBValue, fBinning)\n% ---------------------------------------------------------------------------\n% Calculates the likelihood of a b-value fit\n%\n% Input parameters:\n% mCatalog Earthquake catalog\n% fBValue b-value\n% fBinning Binning of the earthquake magnitudes (default 0.1)\n%\n% Output parameters:\n% fLogLikelihood Log-likelihood\n%\n%@ARTICLE{Aki1965,\n% author = \"K. Aki\",\n% title = \"Maximum likelihood estimate of $b$ in the formula\n% $\\log N = a-bM$ and its confidence limits\",\n% journal = \"Bull. Earthquake Re. Inst., Tokyo Univ.\",\n% year = \"1965\",\n% volume = \"43\",\n% pages = \"237-239\",\n%}\n%\n% Copyright (C) by Danijel Schorlemmer\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\n% Free Software Foundation, Inc.,\n% 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\nif ~exist('fBinning', 'var')\n fBinning = 0.1\nend\n\nfBPrime = fBValue/(log10(exp(1)));\nfMinMag = min(mCatalog(:,6))-(fBinning/2);\n\nfL = ones(length(mCatalog(:,1)),1)*nan;\n\nfL = log(fBPrime) - (fBPrime * (mCatalog(:,6) - fMinMag));\nfLogLikelihood = sum(fL);\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/danijel/calc/calc_AkiLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.604182281266542}} {"text": "% MPC applied to LOTKA-VOLTERRA system using\n% a SINDYc model for different prediction horizon lengths.\n\n\nclear all, close all, clc\nfigpath = '../FIGURES/';\ndatapath = '../DATA/';\naddpath('../utils');\n\n%% Generate Data\n% Parameters: SINDy\npolyorder = 3;\nusesine = 0;\n\n% True Parameters of Lotka-Volterra model\na = .5;\nb = .025;\nd = .005;\ng = .5;\nn = 2;\nx0=[60; 50];\ndt = .01;\n\n% Choose forcing function to excite system for model identification\n% forcing = @(x,t) [(0.33*(sin(1*t)+sin(.1*t)))];\nforcing = @(x,t) [(2*(sin(1*t)+sin(.1*t))).^2];\n\n% Integrate excited system\ntspan=[0:dt:100];\nu = forcing(0,tspan);\nN = length(tspan);\noptions = odeset('RelTol',1e-10,'AbsTol',1e-10*ones(1,n));\n[t,x]=ode45(@(t,x) lotkacontrol(t,x,forcing(x,t),a,b,d,g),tspan,x0,options);\nplot(t,x,'LineWidth',1.5)\nxlabel('Time')\nylabel('Population size')\nlegend('Prey','Predator')\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', [figpath,'EX_LOTKA_Dynamics.eps']);\n\n%% SINDYc Model Identification\n% Compute Derivative\nxold = x;\nclear dx\nx = xold;\neps = 0.1;\nfor i=1:length(x)\n dx(i,:) = lotkacontrol(0,x(i,:),u(i),a,b,d,g);\nend\nx = [xold u'];\ndx(:,3) = 0*dx(:,2);\ndx = dx + eps*randn(size(dx));\nn = 3;\n\n% Sparse regression\nclear Theta Xi\nTheta = poolData(x,n,polyorder,usesine);\nm = size(Theta,2);\n\nlambda = 0.001; % lambda is our sparsification knob.\nXi = sparsifyDynamics(Theta,dx,lambda,n);\npoolDataLIST({'x','y','u'},Xi,n,polyorder,usesine);\n\n\n%% FIGURE 1: Lotka-Volterra // Validation\nx0 = x(end,1:2);\ntspan = [100 200];\n[tA,xA]=ode45(@(t,x)lotkacontrol(t,x,forcing(x,t),a,b,d,g),tspan,x0,options); % true model\n[tB,xB]=ode45(@(t,x)sparseGalerkinControl(t,x,forcing(x,t),Xi(:,1:2),polyorder,usesine),tspan,x0,options); % approximate\n\nh = figure;\nsubplot(2,1,1), box on\nplot(t,x(:,1),'Color',[.4 .4 .4],'LineWidth',1.5), hold on\nplot(tA,xA(:,1),'k','LineWidth',1.5), hold on\nplot(tB,xB(:,1),'r--','LineWidth',1.5)\ngrid on\nylim([0 110])\n% xlabel('Time','FontSize',13)\nylabel('Prey, x_1','FontSize',13)\nset(gca,'FontSize',13, 'LineWidth',1)\nsubplot(2,1,2), box on\nplot(t,x(:,2),'Color',[.4 .4 .4],'LineWidth',1.5), hold on\nplot(tA,xA(:,2),'k','LineWidth',1.5), hold on\nplot(tB,xB(:,2),'r--','LineWidth',1.5)\nl1=legend('Training','Validation','SINDYc');\nset(l1,'Location','NorthWest')\ngrid on\nylim([0 60])\nylabel('Predator, x_2','FontSize',13)\nset(gca,'FontSize',13, 'LineWidth',1)\nxlabel('Time','FontSize',13)\nset(gca,'FontSize',13)\n\nset(h,'Units','Inches');\nset(gcf,'Position',[1 1 6. 5.5])\npos = get(h,'Position');\nset(h,'PaperPositionMode','Auto','PaperSize',[pos(3), pos(4)])\nprint(h,'-dpdf', [figpath,'EX_LOTKA_ControlValidation.pdf'],'-r0');\nprint(h,'-depsc2', [figpath,'EX_LOTKA_ControlValidation.eps'],'-r0');\n\n\nclear ph\nfigure;hold on, box on,\nccolors = get(gca,'colororder');\nplot([100,100],[0 260],':','Color',[0.4,0.4,0.4],'LineWidth',1)\ntext(5,120,'Training', 'FontSize',12)\ntext(105,120,'Prediction', 'FontSize',12)\nplot(t,x(:,1),'Color',[.4 .4 .4],'LineWidth',1.5); hold on\nplot(t,x(:,2),'Color',[.4 .4 .4],'LineWidth',1.5)\nph(1) = plot(tA,xA(:,1),'k','LineWidth',1.5);\nplot(tA,xA(:,2),'k','LineWidth',1.5)\nph(2) = plot(tB,xB(:,1),'--','Color',ccolors(1,:),'LineWidth',1.5);\nph(3) = plot(tB,xB(:,2),'--','Color',ccolors(2,:),'LineWidth',1.5);\nxlabel('Time')\nylabel('Population size')\nl1=legend(ph,'Validation','SINDYc','SINDYc');\naxis tight\nylim([-15 260])\nset(gca,'xtick',[50,100,150,200])\nset(gca,'LineWidth',1, 'FontSize',14)\nset(gcf,'Position',[100 100 300 200])\nset(gcf,'PaperPositionMode','auto')\nprint('-dpdf', [figpath,'EX_LOTKA_ControlValidation2']);\nprint('-depsc2', [figpath,'EX_LOTKA_ControlValidation2']);\n\n\n%% Apply Model predictive controlto system using SINDYc model\npest.ahat = Xi(:,1:2);\npest.polyorder = polyorder;\npest.usesine = usesine;\np.a = a; % True model parameters\np.b = b;\np.d = d;\np.g = g;\n\n% Choose prediction horizon over which the optimization is performed\n% Nvec = [1,3,5,7,10,15,20,25,30,35,40,45,50];\nNvec = [2,4,6,8,9,11,12,13];\n\nfor i = 1:length(Nvec)\n Ts = 0.1; % Sampling time\n N = Nvec(i); % Control / prediction horizon (number of iterations)\n Duration = 100; % Run control for 100 time units\n Nvar = 2;\n Q = [1 0]; % State weights\n R = 0.5;%0.5; % Control variation du weights\n Ru = 0.5;%0.01; % Control weights\n B = [0; 1]; % Control vector (which state is controlled)\n C = eye(Nvar); % Measurement matrix\n D = 0; % Feedforward (none)\n x0n=x0';%[100; 50]; % Initial condition\n uopt0 = 0; % Set initial control input to zero\n \n % Constraints on control optimization\n LB = [];%-100*ones(N,1); % Lower bound of control input\n UB = [];%100*ones(N,1); % Upper bound of control input\n \n % Reference state, which shall be achieved\n xref1 = [g/d;a/b]; % critical point\n % xref1 = [50;0]; % Reference values\n % xref2 = [50;0];\n % xref_vec = [xref1(1)*ones(size(0:Ts:10)),xref2(1)*ones(size(10+Ts:Ts:Duration));\n % xref1(2)*ones(size(0:Ts:10)),xref2(2)*ones(size(10+Ts:Ts:Duration))];\n \n % Options for optimization routine\n options = optimoptions('fmincon','Algorithm','sqp','Display','none');\n \n % Start simulation\n fprintf('Simulation started. It might take a while...\\n')\n x = x0n;\n Ton = 30; % Time when control starts\n uopt = uopt0.*ones(N,1);\n xHistory = x; % Stores state history\n uHistory = uopt(1); % Stores control history\n tHistory = 0; % Stores time history\n rHistory = xref1; % Stores reference (could be trajectory and vary with time)\n tic\n for ct = 1:(Duration/Ts) % For each iteration: take measurements & optimize control input & apply control input\n if ct*Ts>30 % Turn control on\n if ct*Ts==Ton+Ts\n disp('Start control.')\n end\n \n % Set references\n xref = xref1;\n \n % NMPC with full-state feedback\n COSTFUN = @(u) lotkaObjectiveFCN(u,x,Ts,N,xref,uopt(1),pest,diag(Q),R,Ru);\n CONSFUN = @(u) lotkaConstraintFCN(u,x,Ts,N,pest);\n uopt = fmincon(COSTFUN,uopt,[],[],[],[],LB,UB,CONSFUN,options);\n % uopt = fmincon(COSTFUN,uopt,[],[],[],[],LB,UB,[],options);\n % %use this without constraint functions CONSFUN\n \n else % If control is off\n uopt = uopt0.*ones(N,1);\n xref = [nan; nan];\n end\n \n % Integrate system: Apply control & Step one timestep forward\n x = rk4u(@lotkacontrol_discrete,x,uopt(1),Ts/1,1,[],p); %10, 2\n xHistory = [xHistory x];\n uHistory = [uHistory uopt(1)];\n tHistory = [tHistory tHistory(end)+Ts/1];\n rHistory = [rHistory xref];\n \n end\n fprintf('Simulation finished!\\n')\n toc\n \n %% Show results\n clear ph\n \n figure;hold on, box on,\n ccolors = get(gca,'colororder');\n plot([Ton+tspan(1),Ton+tspan(1)],[-15 260],':','Color',[0.4,0.4,0.4],'LineWidth',1)\n text(31+tspan(1),210,'Control', 'FontSize',12)\n text(31+tspan(1),190,'turned on', 'FontSize',12)\n plot(tHistory+tspan(1),zeros(length(tHistory),1),'-k','LineWidth',0.5)\n plot(tHistory+tspan(1),xref1(1)*ones(length(tHistory),1),'--','Color',ccolors(1,:),'LineWidth',1)\n plot(tHistory+tspan(1),xref1(2)*ones(length(tHistory),1),'--','Color',ccolors(2,:),'LineWidth',1)\n ph(1) = plot(tHistory+tspan(1),xHistory(1,:),'-','Color',ccolors(1,:),'LineWidth',1.5);\n ph(2) = plot(tHistory+tspan(1),xHistory(2,:),'-','Color',ccolors(2,:),'LineWidth',1.5);\n ph(3) = plot(tHistory+tspan(1),uHistory,'-k','LineWidth',1.5);\n xlabel('Time')\n ylabel('Population size')\n legend(ph,'Prey','Predator','Control')\n axis tight\n ylim([-15 260])\n xlim([100,200.0001])\n %ylim([min(uHistory)-5 260])\n set(gca,'xtick',[50,100,150,200])\n set(gca,'LineWidth',1, 'FontSize',14)\n set(gcf,'Position',[100 100 300 200])\n set(gcf,'PaperPositionMode','auto')\n print('-depsc2', [figpath,'EX_LOTKA_DynamicsControlled_cnstrnd_N',num2str(N),'.eps']);\n \n %% Save Results\n Results.t = tHistory;\n Results.x = xHistory;\n Results.u = uHistory;\n Results.J = evalObjectiveFCN(uHistory,xHistory,rHistory,diag(Q),R,Ru);\n \n save(fullfile(datapath,['EX_LOTKA_MPC_SINDYc_N',num2str(N),'.mat']),'Results')\n \nend\nreturn\n", "meta": {"author": "eurika-kaiser", "repo": "SINDY-MPC", "sha": "e1dfd9908b2b56af303ee9fb30a133aced4fd757", "save_path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC", "path": "github-repos/MATLAB/eurika-kaiser-SINDY-MPC/SINDY-MPC-e1dfd9908b2b56af303ee9fb30a133aced4fd757/EX_LOTKA_VOLTERRA/MPC_LOTKA_SINDYc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7745833945721305, "lm_q1q2_score": 0.6041695563437313}} {"text": "function asa076_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 demonstrates the use of THA.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02:\\n' );\n fprintf ( 1, ' THA evaluates Owen''s T function.\\n' );\n fprintf ( 1, ' Compare to tabulated values.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' H A ' );\n fprintf ( 1, 'T T\\n' );\n fprintf ( 1, ' ' );\n fprintf ( 1, '(Tabulated) (THA) DIFF\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, h, a, t1 ] = owen_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n t2 = tha ( h, 1.0, a, 1.0 );\n\n fprintf ( 1, ' %12.8f %12.8f %24.16e %24.16e %10.4e\\n', ...\n h, a, t1, t2, abs ( t1 - t2 ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/asa076/asa076_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6041695522849573}} {"text": "function a = schur_block_inverse ( n, x, y )\n\n%*****************************************************************************80\n%\n%% SCHUR_BLOCK_INVERSE returns the inverse of the SCHUR_BLOCK matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real X( (N+1)/2 ), specifies the diagonal elements\n% of A.\n%\n% Input, real Y( N/2 ), specifies the off-diagonal elements \n% of the Schur blocks.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n k = floor ( ( i + 1 ) / 2 );\n\n if ( i == j )\n\n if ( i == n & mod ( n, 2 ) == 1 )\n a(i,j) = 1.0 / x(k);\n else\n a(i,j) = x(k) / ( x(k)^2 + y(k)^2 );\n end\n\n elseif ( mod ( i, 2 ) == 1 & j == i + 1 )\n\n a(i,j) = - y(k) / ( x(k)^2 + y(k)^2 );\n\n elseif ( mod ( i, 2 ) == 0 & j == i - 1 )\n\n a(i,j) = y(k) / ( x(k)^2 + y(k)^2 );\n\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/schur_block_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042765, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6040969972254749}} {"text": "function [ r, s, area ] = node_reference_q8 ( )\n\n%*****************************************************************************80\n%\n%% NODE_REFERENCE_Q8 returns the basis nodes for an 8 node quadrilateral.\n%\n% Discussion:\n%\n% This element is known as the quadratic \"serendipity\" element.\n%\n% Reference Element Q8:\n%\n% |\n% 1 4--7--3\n% | | |\n% | | |\n% S 8 6\n% | | |\n% | | |\n% 0 1--5--2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real R(8), S(8), the coordinates of the basis nodes.\n%\n% Output, real AREA, the area of the element.\n%\n r(1:8) = [ 0.0, 1.0, 1.0, 0.0, 0.5, 1.0, 0.5, 0.0 ];\n s(1:8) = [ 0.0, 0.0, 1.0, 1.0, 0.0, 0.5, 1.0, 0.5 ];\n\n area = 1.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/node_reference_q8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.604096995111264}} {"text": "classdef RMMEDA_F8 < PROBLEM\n% \n% Benchmark MOP for testing RM-MEDA\n\n%------------------------------- Reference --------------------------------\n% Q. Zhang, A. Zhou, and Y. Jin, RM-MEDA: A regularity model-based\n% multiobjective estimation of distribution algorithm, IEEE Transactions on\n% Evolutionary Computation, 2008, 12(1): 41-63.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 3;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n g = sum((X(:,3:end).^2-repmat(X(:,1),1,size(X,2)-2)).^2,2);\n PopObj(:,1) = cos(pi/2*X(:,1)).*cos(pi/2*X(:,2)).*(1+g);\n PopObj(:,2) = cos(pi/2*X(:,1)).*sin(pi/2*X(:,2)).*(1+g);\n PopObj(:,3) = sin(pi/2*X(:,1)).*(1+g);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R = UniformPoint(N,3);\n R = R./repmat(sqrt(sum(R.^2,2)),1,3);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n a = linspace(0,pi/2,10)';\n R = {sin(a)*cos(a'),sin(a)*sin(a'),cos(a)*ones(size(a'))};\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/RMMEDA_F8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6040969732467302}} {"text": "function [pv, pstd, cv, cstd, kv, kstd, loopout] = bruteboot(time_as)\n % function [pv, pstd, cv, cstd, kv, kstd, loopout] = bruteboot(time_as);\n % ----------------------------------------------------------------------\n % bootstrap analysis of Omori parameters calculated by bruteforce.m\n %\n % Input parameters:\n % time_as Delay times [days]\n %\n % Output parameters:\n % pv / pstd p value / standard deviation\n % cv / cstd c value / standard deviation\n % kv / kstd k value / standard deviation\n % loopout contains all results\n %\n % Samuel Neukomm\n % July 30, 2002\n\n time_as = sort(time_as);\n bootloops = 50; % number of bootstrap samples\n n = length(time_as);\n loopout = [];\n for j = 1:bootloops\n clear newtas\n randnr = ceil(rand(n,1)*n);\n i = (1:n)';\n newtas(i,:) = time_as(randnr(i),:); % bootstrap sample\n [pval, cval, kval] = bruteforce(sort(newtas)); % bruteforce.m is called\n loopout = [loopout; pval cval kval];\n end\n\n pv = round(100*mean(loopout(:,1)))/100; \n pstd = round(100*std(loopout(:,1)))/100;\n \n cv = round(100*mean(loopout(:,2)))/100; \n cstd = round(100*std(loopout(:,2)))/100;\n \n kv = round(10*mean(loopout(:,3)))/10; \n kstd = round(10*std(loopout(:,3)))/10;\n\n % unreasonable parameter values -> no result\n if pv < 0.6 | pv > 2.3 | cv < 0.01 | cv > 3 | cv < cstd | pv < pstd | kv < kstd\n pv = nan; pstd = nan;\n cv = nan; cstd = nan;\n kv = nan; kstd = nan;\n end\nend\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/bruteboot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6040508481538981}} {"text": "classdef FCP3 < PROBLEM\n% \n% Benchmark constrained MOP proposed by Jiawei Yuan\n\n%------------------------------- Reference --------------------------------\n% J. Yuan, H. Liu, Y. Ong, and Z. He, Indicator-based evolutionary\n% algorithm for solving constrained multi-objective optimization problems,\n% IEEE Transactions on Evolutionary Computation, 2022, 26(2): 379-391.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n% This function is written by Jiawei Yuan\n\n methods\n %% Initialization\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D)\n obj.D = 30;\n end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,PopDec)\n g = 1 + 9*mean(PopDec(:,2:end),2);\n t = mod(floor(100*g),2);\n g = g + t.*(g-9).^2;\n PopObj(:,1) = cos(0.5*pi*PopDec(:,1)).*g;\n PopObj(:,2) = sin(0.5*pi*PopDec(:,1)).*g;\n end\n %% Calculate constraint violations\n function PopCon = CalCon(obj,PopDec)\n g = 1 + 9*mean(PopDec(:,2:end),2);\n t = mod(floor(100*g),2);\n g = g + t.*(g-9).^2;\n Dis = abs(9-g);\n %%%%% Type-II constraints\n y1 = Dis.^2-0.25;\n y2 = 1./(Dis+1e-6).*(1.2+sin(Dis*pi));\n PopCon = min([y1,y2],[],2);\n end\n %% Sample reference points on Pareto front\n function P = GetOptimum(obj,N)\n t = 0.5*pi*(0:1/N:1)';\n P=8.5*[cos(t),sin(t)];\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/FCP/FCP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6040508377694087}} {"text": "function [Cl, Cd] = a2clcd(alfa)\n\n% [Cl, Cd] = a2clcd(alfa) computes hydrodynamic coefficients Cl and Cd\n% for the fins\n\n% Costants\nCLa = 2.865; % CLalfa [rad^-1]\nCDmin = 0.0115; % CDmin\nK = 0.1309; % K\nALFA1 = 0.419; % alfa_stall [rad]\nALFA2 = 0.7854; % alfa45 [rad]\n\nC1 = -1.0572; % interpolating coefficients\nC2 = 1.6434; % between zone 1 and 3 \nC3 = 1.6759;\nC4 = -0.5021;\n\nCT = 1.15; \n\n% sign correction\nmod_alfa=abs(alfa-sign(alfa)*(abs(alfa)>pi/2)*pi);\n\nif mod_alfa < ALFA1\n % zone 1\n Cl = CLa * mod_alfa ;\n Cd = CDmin + K * Cl^2 ;\nelseif mod_alfa < ALFA2\n % zone2 \n Cl = C1 * mod_alfa + C2;\n Cd = C3 * mod_alfa + C4;\nelse\n % zone 3 , piastra\n Cl = CT*cos(mod_alfa);\n Cd = CT*sin(mod_alfa);\nend;\n\n% sign correction\nCl = Cl*sign(sin(2*alfa));\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1207-shark/source/a2clcd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.6040425913170391}} {"text": "function Es = PQspreadCB (E, Ver)\n% Spread an excitation vector (pitch pattern) - FFT model\n% Both E and Es are powers\n\n% P. Kabal $Revision: 1.1 $ $Date: 2003/12/07 13:32:58 $\n\npersistent Bs Version\n\nif (~ strcmp (Ver, Version))\n Version = Ver;\n Nc = length (E);\n Bs = PQ_SpreadCB (ones(1,Nc), ones(1,Nc), Version);\nend\n\nEs = PQ_SpreadCB (E, Bs, Version);\n\n%-------------------------\nfunction Es = PQ_SpreadCB (E, Bs, Ver);\n\npersistent Nc dz fc aL aUC Version\n\n% Power law for addition of spreading\ne = 0.4;\n\nif (~ strcmp (Ver, Version))\n Version = Ver;\n [Nc, fc, fl, fu, dz] = PQCB (Version);\nend\n\n% Allocate storage\naUCEe = zeros (1, Nc);\nEne = zeros (1, Nc);\nEs = zeros (1, Nc);\n\n% Calculate energy dependent terms\naL = 10^(-2.7 * dz);\nfor (m = 0:Nc-1)\n aUC = 10^((-2.4 - 23 / fc(m+1)) * dz);\n aUCE = aUC * E(m+1)^(0.2 * dz);\n gIL = (1 - aL^(m+1)) / (1 - aL);\n gIU = (1 - aUCE^(Nc-m)) / (1 - aUCE);\n En = E(m+1) / (gIL + gIU - 1);\n aUCEe(m+1) = aUCE^e;\n Ene(m+1) = En^e;\nend\n\n% Lower spreading\nEs(Nc-1+1) = Ene(Nc-1+1);\naLe = aL^e;\nfor (m = Nc-2:-1:0)\n Es(m+1) = aLe * Es(m+1+1) + Ene(m+1);\nend\n\n% Upper spreading i > m\nfor (m = 0:Nc-2)\n r = Ene(m+1);\n a = aUCEe(m+1);\n for (i = m+1:Nc-1)\n r = r * a;\n Es(i+1) = Es(i+1) + r;\n end\nend\n\nfor (i = 0:Nc-1)\n Es(i+1) = (Es(i+1))^(1/e) / Bs(i+1);\nend\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/PEAQPython/PQevalAudioMATLAB/PQevalAudio/CB/PQspreadCB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6039499390727717}} {"text": "function [cc] = yd32cc(yd3)\n% Convert volume from cubic yards to cubic centimeters*. \n% Chad Greene 2012\ncc = yd3*764554.85798;\n\n\n% *Not to be confused with ancient Egyptian cubic cubits. ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/yd32cc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6039499338932071}} {"text": "% Philipp Berens\n% CircStat: A Matlab Toolbox for Circular Statistics\n% Submitted to Journal of Statistical Software\n%\n% Example 2\n% An Application to Neuroscience\n%\n%\n% In this example, we assess the orientation tuning properties of three\n% neurons recorded from the primary visual cortex of awake macaques. the \n% number of action potentials such neurons fire is modulated by the\n% orientation of a visual stimulus such as an oriented grating.\n%\n% We thus consider two variables: The stimulus orientations ori spaced 22.5\n% deg apart and the number of spikes w fired in response to each \n% orientation of the stimulus. \n\n\n%% part 1: load and plot data\nclear\nload neurodata\n\n% orientation of bins -> convert two directions\nori = circ_axial(circ_ang2rad(ori),2);\n\n% spacing of bins\ndori = diff(ori(1:2));\n\n% summed spikes per orientation \nw;\n\n% plot the activity of the three neurons\nfigure\nfor j = 1:3\n subplot(1,3,j)\n \n % compute and plot mean resultant vector length and direction\n mw = max(w(j,:));\n r = circ_r(ori,w(j,:),dori) * mw;\n phi = circ_mean(ori,w(j,:));\n hold on;\n zm = r*exp(i*phi');\n plot([0 real(zm)], [0, imag(zm)],'r','linewidth',1.5)\n \n % plot the tuning function of the three neurons \n polar([ori ori(1)], [w(j,:) w(j,1)],'k')\n \n % draw a unit circle\n zz = exp(i*linspace(0, 2*pi, 101)) * mw;\n plot(real(zz),imag(zz),'k:')\n plot([-mw mw], [0 0], 'k:', [0 0], [-mw mw], 'k:')\n\n formatSubplot(gca,'ax','square','box','off','lim',[-mw mw -mw mw])\n set(gca,'xtick',[])\n set(gca,'ytick',[])\n\nend\n\n%% part 2: descriptive statistics\n\nstats = zeros(3,10);\nfor i=1:3\n \n spk = w(i,:);\n \n % circular mean angle\n stats(i,1) = circ_mean(ori,spk,2);\n \n % circular variance\n stats(i,2) = circ_var(ori,spk,dori,2);\n \n % circular standard deviation\n [stats(i,3) stats(i,4)] = circ_std(ori,spk,dori,2);\n \n % circular skewness\n [stats(i,5) stats(i,6)] = circ_skewness(ori,spk,2); \n \n % circular skewness\n [stats(i,7) stats(i,8)] = circ_kurtosis(ori,spk,2);\n \n % confidence limits on mean angle\n t = circ_confmean(ori,[],spk,dori,2);\n stats(i,9) = stats(i,1) + t;\n stats(i,10) = stats(i,1) - t;\nend\n\n% stats contains all data reported in table 1\n\n%% part 3: inferential statistics\n\n% A: tests for uniformity of distribution around the circle\n% rejecting the null hypothesis allows us to assert that the neurons are\n% indeed tuned to the orientation of the stimulus and fire preferentially\n% at a particular orientation\n\nuniform = zeros(3,2);\nfor i=1:3\n \n spk = w(i,:);\n \n % rayleigh test\n uniform(i,1) = circ_rtest(ori,spk,dori);\n \n % omnibus test\n uniform(i,2) = circ_otest(ori,[],spk);\n \n % rao's spacing test is not possible with binned data\nend\n\n% B: test for differences in preferred orientation between neurons\n\n% differences between all groups\nalpha = [ori ori ori];\nidx = [ones(1,length(ori)) 2* ones(1,length(ori)) 3* ones(1,length(ori))];\nspk = reshape(w',1,numel(w));\n\nfprintf('TESTING FOR DIFFERENCES BETWEEN ANY CELLS\\n')\ncirc_wwtest(alpha,idx,spk);\n\n% all pairwise differences\nfor i=1:3\n for j=(i+1):3\n % differences between cells i and cell j\n alpha = [ori ori];\n idx = [i* ones(1,length(ori)) j* ones(1,length(ori))];\n spk = reshape(w([i j],:)',1,numel(w([i j],:)));\n \n fprintf('TESTING FOR DIFFERENCES BETWEEN CELLS %d AND %d\\n',i,j)\n watson(i,j) = circ_wwtest(alpha,idx,spk); %#ok\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", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/CircularStats/examples/example2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6039396293404122}} {"text": "function [cc] = cdtbal2(pp,ee,tt)\n%CDTBAL2 compute the modified circumballs associated with a\n%constrained 2-simplex Delaunay triangulation in R^2.\n% [CC] = CDTBAL2(PP,EE,TT) returns the smallest enclosing\n% balls associated with the triangles in [PP,TT], such th-\n% at CC = [XC,YC,RC.^2]. Such balls never lie outside the\n% boundaries of the associated CDT. See TRICON2 for info-\n% mation regarding the edge array EE.\n\n% Darren Engwirda : 2017 --\n% Email : de2363@columbia.edu\n% Last updated : 01/10/2017\n\n%---------------------------------------------- basic checks\n if (~isnumeric(pp) || ~isnumeric(ee) || ...\n ~isnumeric(tt) )\n error('cdtbal2:incorrectInputClass' , ...\n 'Incorrect input class.') ;\n end\n\n%---------------------------------------------- basic checks\n if (ndims(pp) ~= +2 || ndims(ee) ~= +2 || ...\n ndims(tt) ~= +2 )\n error('cdtbal2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n if (size(pp,2)~= +2 || size(ee,2) < +5 || ...\n size(tt,2) < +6 )\n error('cdtbal2:incorrectDimensions' , ...\n 'Incorrect input dimensions.');\n end\n\n%----------------------------------------- calc. circumballs\n cc = tribal2(pp,tt);\n\n%------------------------ replace with face-balls if smaller\n cc = minfac2(cc,pp,ee,tt,1,2,3) ;\n cc = minfac2(cc,pp,ee,tt,2,3,1) ;\n cc = minfac2(cc,pp,ee,tt,3,1,2) ;\n\nend\n\nfunction [cc] = minfac2(cc,pp,ee,tt,ni,nj,nk)\n%MINFAC2 modify the set of circumballs to constrain centres\n%to the boundaries of the CDT.\n% [CM] = MINFAC2(CC,PP,EE,TT,NI,NJ,NK) returns the set of\n% modified circmballs CM, where any ball CC lying outside\n% the boundaries of the CDT [PP,EE,TT] is replaced by the\n% edge-centred diametric ball. [NI,NJ] are the local inde-\n% xes associated with an edge to test. NK is the local in-\n% dex of the opposite vertex.\n\n%------------------------------------------------ outer edge\n EF = ee(tt(:,ni+3),5) > +0 ;\n\n%------------------------------------------------ edge balls\n bc = (pp(tt(EF,ni),:)+pp(tt(EF,nj),:))*.50;\n\n%------------------------------------------------ edge radii\n br = sum((bc(:,1:2)-pp(tt(EF,ni),:)).^2,2)...\n + sum((bc(:,1:2)-pp(tt(EF,nj),:)).^2,2);\n br = br * +0.5 ;\n\n%------------------------------------------- enclosing radii\n ll = sum((bc(:,1:2)-pp(tt(EF,nk),:)).^2,2);\n\n%------------------------------------------- replace if min.\n bi = br >= ll ...\n & br <= cc(EF,3) ;\n ei = find(EF) ;\n ti = ei (bi) ;\n\n%------------------------------------------- replace is min.\n cc(ti,1:2) = bc(bi,:) ;\n cc(ti, 3) = br(bi,:) ;\n\nend\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/GEOM_UTIL/mesh-ball/cdtbal2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6039396239863093}} {"text": "function f = eightPoint(points1homo, points2homo)\n% Normalize the points\nnum = size(points1homo, 2);\n[points1homo, t1] = vision.internal.normalizePoints(points1homo, 2, 'double');\n[points2homo, t2] = vision.internal.normalizePoints(points2homo, 2, 'double');\n% unravel\nm = coder.nullcopy(zeros(num, 9, 'double'));\nm(:,1)=(points1homo(1,:).*points2homo(1,:))';\nm(:,2)=(points1homo(2,:).*points2homo(1,:))';\nm(:,3)=points2homo(1,:)';\nm(:,4)=(points1homo(1,:).*points2homo(2,:))';\nm(:,5)=(points1homo(2,:).*points2homo(2,:))';\nm(:,6)=points2homo(2,:)';\nm(:,7)=points1homo(1,:)';\nm(:,8)=points1homo(2,:)';\nm(:,9)=1;\n% last eigen vector\n[~, ~, vm] = svd(m, 0);\nf = reshape(vm(:, end), 3, 3)';\n[u, s, v] = svd(f);\ns(end) = 0;\nf = u * s * v';\n% denormalize\nf = t2' * f * t1;\nf = f / norm(f);\nif f(end) < 0\n f = -f;\nend", "meta": {"author": "yihui-he", "repo": "3D-reconstruction", "sha": "6a5c98d71ab2f5eaf3e1b9c5cbc9b07d9677a57f", "save_path": "github-repos/MATLAB/yihui-he-3D-reconstruction", "path": "github-repos/MATLAB/yihui-he-3D-reconstruction/3D-reconstruction-6a5c98d71ab2f5eaf3e1b9c5cbc9b07d9677a57f/eightPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.6037617620646692}} {"text": "% This source code is part of the graph optimization package\n% deveoped for the lectures of robotics2 at the University of Freiburg.\n%\n% Copyright (c) 2007 Giorgio Grisetti, Gian Diego Tipaldi\n%\n% It is licences under the Common Creative License,\n% Attribution-NonCommercial-ShareAlike 3.0\n%\n% You are free:\n% - to Share - to copy, distribute and transmit the work\n% - to Remix - to adapt the work\n%\n% Under the following conditions:\n%\n% - Attribution. You must attribute the work in the manner specified\n% by the author or licensor (but not in any way that suggests that\n% they endorse you or your use of the work).\n%\n% - Noncommercial. You may not use this work for commercial purposes.\n%\n% - Share Alike. If you alter, transform, or build upon this work,\n% you may distribute the resulting work only under the same or\n% similar license to this one.\n%\n% Any of the above conditions can be waived if you get permission\n% from the copyright holder. Nothing in this license impairs or\n% restricts the author's moral rights.\n%\n% This software is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied\n% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n% PURPOSE.\n\n\n%ls-slam.m\n%this file is released under the creative common license\n\n%solves a graph-based slam problem via least squares\n%vmeans: matrix containing the column vectors of the poses of the vertices\n%\t the vertices are odrered such that vmeans[i] corresponds to the ith id\n%eids:\t matrix containing the column vectors [idFrom, idTo]' of the ids of the vertices\n%\t eids[k] corresponds to emeans[k] and einfs[k].\n%emeans: matrix containing the column vectors of the poses of the edges\n%einfs: 3d matrix containing the information matrices of the edges\n%\t einfs(:,:,k) refers to the information matrix of the k-th edge.\n%n:\t number of iterations\n%newmeans: matrix containing the column vectors of the updated vertices positions\n\nfunction newmeans = ls_slam(vmeans, eids, emeans, einfs, n)\n\nfor i = 1:n\n vmeans = linearize_and_solve(vmeans, eids, emeans, einfs);\nend\n\nnewmeans = vmeans;\n\nend\n\n\n%computes the taylor expansion of the error function of the k_th edge\n%vmeans: vertices positions\n%eids: edge ids\n%emeans: edge means\n%k:\t edge number\n%e:\t e_k(x)\n%A:\t d e_k(x) / d(x_i)\n%B:\t d e_k(x) / d(x_j)\nfunction [e, A, B] = linear_factors(vmeans, eids, emeans, k)\n%extract the ids of the vertices connected by the kth edge\nid_i = eids(1,k);\nid_j = eids(2,k);\n%extract the poses of the vertices and the mean of the edge\nv_i = vmeans(:,id_i);\nv_j = vmeans(:,id_j);\nz_ij = emeans(:,k);\n\n%compute the homoeneous transforms of the previous solutions\nzt_ij = v2t(z_ij);\nvt_i = v2t(v_i);\nvt_j = v2t(v_j);\n\n%compute the displacement between x_i and x_j\nf_ij=(inv(vt_i) * vt_j);\n\n%this below is too long to explain, to understand it derive it by hand\ntheta_i = v_i(3);\nti = v_i(1:2,1);\ntj = v_j(1:2,1);\ndt_ij = tj-ti;\n\nsi = sin(theta_i);\nci = cos(theta_i);\n\nA= [-ci, -si, [-si, ci]*dt_ij; si, -ci, [-ci, -si]*dt_ij; 0, 0, -1 ];\nB =[ ci, si, 0 ; -si, ci, 0 ; 0, 0, 1 ];\n\nztinv = inv(zt_ij);\ne = t2v(ztinv * f_ij);\nztinv(1:2,3) = 0;\nA = ztinv*A;\nB = ztinv*B;\nend\n\n\n%linearizes and solves one time the ls-slam problem specified by the input\n%vmeans: vertices positions at the linearization point\n%eids: edge ids\n%emeans: edge means\n%einfs: edge information matrices\n%newmeans: new solution computed from the initial guess in vmeans\nfunction newmeans = linearize_and_solve(vmeans, eids, emeans, einfs)\ndisp('allocating workspace...');\n% H and b are respectively the system matrix and the system vector\nH = zeros(size(vmeans,2)*3);\nb = zeros(size(vmeans,2)*3,1);\n\ndisp('linearizing');\n% this loop constructs the global system by accumulating in H and b the contributions\n% of all edges (see lecture)\nfor k = 1:size(eids,2),\n id_i = eids(1,k);\n id_j = eids(2,k);\n [e, A, B] = linear_factors(vmeans, eids, emeans, k);\n omega = einfs(:,:,k);\n %compute the blocks of H^k\n b_i = -A' * omega * e;\n b_j = -B' * omega * e;\n H_ii= A' * omega * A;\n H_ij= A' * omega * B;\n H_jj= B' * omega * B;\n \n %accumulate the blocks in H and b\n H((id_i-1)*3+1:id_i*3,(id_i-1)*3+1:id_i*3) = ...\n H((id_i-1)*3+1:id_i*3,(id_i-1)*3+1:id_i*3)+ H_ii;\n H((id_j-1)*3+1:id_j*3,(id_j-1)*3+1:id_j*3) = ...\n H((id_j-1)*3+1:id_j*3,(id_j-1)*3+1:id_j*3) + H_jj;\n H((id_i-1)*3+1:id_i*3,(id_j-1)*3+1:id_j*3) = ...\n H((id_i-1)*3+1:id_i*3,(id_j-1)*3+1:id_j*3) + H_ij;\n H((id_j-1)*3+1:id_j*3,(id_i-1)*3+1:id_i*3) = ...\n H((id_j-1)*3+1:id_j*3,(id_i-1)*3+1:id_i*3) + H_ij';\n b((id_i-1)*3+1:id_i*3,1) = ...\n b((id_i-1)*3+1:id_i*3,1) + b_i;\n b((id_j-1)*3+1:id_j*3,1) = ...\n b((id_j-1)*3+1:id_j*3,1) + b_j;\n \n %NOTE on Matlab compatibility: note that we use the += operator which is octave specific\n %using H=H+.... results in a tremendous overhead since the matrix would be entirely copied every time\n %and the matrix is huge\nend;\ndisp('Done');\n%note that the system (H b) is obtained only from\n%relative constraints. H is not full rank.\n%we solve the problem by anchoring the position of\n%the the first vertex.\n%this can be expressed by adding the equation\n% deltax(1:3,1)=0;\n%which is equivalent to the following\nH(1:3,1:3) = H(1:3,1:3) + eye(3);\n\nSH = sparse(H);\ndisp('System size: '),disp(size(H));\ndisp('solving (may take some time) ...');\ndeltax = SH\\b;\ndisp('Done! ');\n\n%split the increments in nice 3x1 vectors and sum them up to the original matrix\nnewmeans = vmeans + reshape(deltax, 3, size(vmeans,2));\n\ndisp('Normalizing the angles');\n%normalize the angles between -PI and PI\nfor i = 1:size(newmeans,2)\n s = sin(newmeans(3,i));\n c = cos(newmeans(3,i));\n newmeans(3,i) = atan2(s,c);\nend\ndisp('Done');\nend\n", "meta": {"author": "versatran01", "repo": "graphslam", "sha": "c09bb80285e7356897b5cb39f236f84731bc976f", "save_path": "github-repos/MATLAB/versatran01-graphslam", "path": "github-repos/MATLAB/versatran01-graphslam/graphslam-c09bb80285e7356897b5cb39f236f84731bc976f/lsslam/ls_slam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6037428057944616}} {"text": "function parcel_clusters(clpos_data, clneg_data)\n% :Usage:\n% ::\n%\n% parcel_clusters(clpos_data, clneg_data)\n%\n% No outputs. Saves all output in separate directory.\n%\n% First, get eigenvectors for each subject.\n%\n% We're interested obtaining PARCELS of voxels that tend to co-activate, \n% or have the same activation profile.\n%\n% We can find these by using clustering algorithms to group voxels with\n% similar profiles.\n%\n% Because we have a many voxel x many voxel covariance matrix for each\n% subject (lots of data!), it's important to reduce the dimensionality of\n% the problem and peform clustering on a REDUCED_DIMENSIONAL space. \n%\n% We use PCA to do this. Instead of clustering activation profiles (e.g.,\n% time-courses) directly, we cluster eigenvector loadings for each voxel on\n% a reduced set of components that explains most of the variance in the\n% data.\n%\n% Similar voxels will have similar loadings across the set of \n% eigenvectors. e.g., two voxels may load high on components [1 3 and 5],\n% and low on components [10 and 13]. If they have the same pattern of\n% loadings, they should be considered part of the same CLASS. Groups\n% of voxels that are contiguous in space and are members of the same CLASS \n% are called parcels.\n%\n% Images and outputs are saved in their own subdirectory called\n% Parcellation_info\n%\n% The main outputs are: \n% parcel_cl % parcels, one cell per subject, one parcel per\n% element within cells. same format as clpos_data\n%\n% parcel_cl_avgs % parcels, one parcel per element within cells. \n% same format as clpos_data2\n%\n% parcel_cl_avgs(x).timeseries contains one cell per subject, with data\n% averaged across voxels within that parcel for that subject\n% This kind of output is useful, because you can input it directly into\n% other mediation analyses.\n% [paths, stats2] = mediation(SETUP.data.X, SETUP.data.Y, parcel_cl_avgs(1).timeseries, 'plots', 'verbose', 'names', {'Hi-Low Cue' 'Pain Report' 'Parcel'}, 'boot');\n% cluster_orthviews(parcel_cl_avgs(1), {[0 1 0]}, 'add');\n% ::\n%\n% cd('/Volumes/SCNAlpha/Data_and_Tools/SpeechTask/analysis/wb_multisubject_correl_HR_corrected/mediation_Xprepvsb_Mbrain_Yhr')\n% load cl_b_fdr05_002_01_k3_1_1_prune\n%\n% then run\n%\n% There are 2 dimension-reduction steps:\n% 1. within-subjects\n% 2. is on eigenvectors concatenated across subjects\n\ninitial_eigval_limit = 15; % Number of eigenvalues to save initially for each subject\n % Need this to reduce computational burden\n \nn_eigs = 7; % Number of eigenvectors to use per subject in the clustering algorithm. \n\n% We form a matrix of [voxels x subjects*eigenvectors] (called group_eigenvectors)\n% For example, 7 eigenvectors x 10 subjects means clustering will be done\n% in a 70 dimensional space.\n% This matrix is subjected to a second step of PCA data reduction. A\n% smaller number of scores are saved, and these scores represent sets of\n% eigenvector loadings in the original 70 dimensional space.\n\n\nn_eigs_across = 12; % Number of dimensions to save out of the original subjects*eigenvectors set\n % Clustering is done on component scores.\n % These are canonical eigenvector patterns\n % that capture regular variations across\n % subjects. Think of them as compressed\n % eigenvectors.\n \n% More n_eigs_across means that clustering will be done in a more complex space.\n% Increasing this will tend to split the voxels into smaller parcels, and\n% decreasing it will tend to lump them into larger parcels.\n\nn_class_range = [2:20]; % test solutions from this many to this many CLASSES\n\nnclasses = 20;\n\n% The final number of classes you want to use in clustering.\n% Increasing this will tend to split the voxels into smaller parcels, and\n% decreasing it will tend to lump them into larger parcels.\n\ndo_nclasses_search = 0; % search over n_class_range?\n\ndoprune = 1; % prune voxels and parcels that are too small or whose voxels don't inter-correlate\n\nmysavedir = 'Parcellation_info';\nif ~exist(mysavedir, 'dir'), mkdir(mysavedir), end\n\n\ncreate_figure('eigenvalues');\n\nnsubjects = length(clpos_data);\nfprintf('Subjects: %3.0f\\n', nsubjects);\n\nif ~isempty(clneg_data)\n test_subj_dat = [cat(2, clpos_data{1}(:).all_data) cat(2, clneg_data{1}(:).all_data)];\nelse\n test_subj_dat = [cat(2, clpos_data{1}(:).all_data)];\nend\n\nnvox = size(test_subj_dat, 2);\nfprintf('Voxels in mask area: %3.0f\\n', nvox);\n\n\ngroup_eigenvalues = zeros(nsubjects, initial_eigval_limit);\n\ngroup_scores = cell(1, nsubjects);\n\n\nfprintf('PCA: Subject ')\n\n%Clustering of multivariate data is most stable when the data is not sparse, \n% i.e., the dimensionality is low relative to the number of observations. \n% To limit the dimensionality of the data, a spatio-temporal dimension-reduction \n% step is first performed on the [n x v x N] data matrix of AUC data for \n% n trials x v voxels x N participants. A temporal data reduction is first performed \n% to identify components with correlated AUC trial time series within each participant, \n% followed by a spatial reduction to identify components with correlated spatial patterns \n% across subjects. First, the [n x v] matrix of AUC data for each participant was \n% subjected to PCA, using the [v x v] correlation matrices. Based on the scree plots \n% across subjects, we saved the first [n_eigs] eigenvectors. \n% These eigenvectors explained xxx +- xxx% (st. dev. across subjects) of the variance \n% in the full dataset. These eigenvectors were scaled by their variances (eigenvalues) \n% and concatenated across subjects to form an [v x N*7] matrix of eigenvectors, \n% where N=27 subjects. This matrix was subjected to another (spatial) PCA step to \n% identify components with similar spatial maps across participants. \n% We retained [n_eigs_across] eigenvectors based on the scree plot, which explained xx% of the \n% variance across individuals. This is a data reduction step, and the results are not \n% expected to depend strongly on the number of eigenvectors retained at either step, \n% as long as most of the variance in the data is explained.\n\n% Temporal reduction\n% -------------------------------------------------------------------------\nfor s = 1:nsubjects\n\n fprintf('%3.0f', s)\n\n if ~isempty(clneg_data)\n subj_dat = [cat(2, clpos_data{s}(:).all_data) cat(2, clneg_data{s}(:).all_data)];\n else\n subj_dat = [cat(2, clpos_data{s}(:).all_data)];\n end\n\n nanvec = any(isnan(subj_dat)) | all(subj_dat == 0);\n wh_bad = find(nanvec);\n if any(wh_bad)\n fprintf('Warning! Subject %3.0f s has missing data (0 or NaN) for these voxels: ', s)\n fprintf('%3.0f ', wh_bad);\n fprintf('\\n')\n\n subj_dat(:, wh_bad) = [];\n end\n\n % to do PCA on correlation matrix rather than cov\n subj_dat = zscore(subj_dat);\n\n %[U, eigenvalues, eigenvectors] = svd(subj_dat, 'econ'); % almost, but\n %scaling isn't right, so just use princomp, which does it all\n\n [eigenvectors, score, eigenvalues] = princomp(subj_dat, 'econ');\n\n clear subj_dat\n\n % insert bad voxels back in\n if any(wh_bad)\n for i = 1:size(eigenvectors, 2)\n ev(:, i) = naninsert(nanvec, eigenvectors(:, i));\n end\n \n ev(isnan(ev)) = 0;\n eigenvectors = ev;\n end\n\n % The first [initial_eigval_limit] \n group_eigenvalues(s, :) = eigenvalues(1:initial_eigval_limit)';\n\n % we want to scale the eigenvectors by their variances (eigenvalues),\n % so that components that account for more variation in the data are weighted more heavily.\n eigenvectors = eigenvectors(:, 1:initial_eigval_limit) * diag(eigenvalues(1:initial_eigval_limit));\n\n group_eigenvectors{s} = eigenvectors;\n\n plot(group_eigenvalues(s, :), 'ko-');\n drawnow\n \n % Calculate variance explained for first [initial_eigval_limit]\n % eigenvalues.\n ev = cumsum(group_eigenvalues');\n ev = ev ./ repmat(sum(group_eigenvalues', 1), size(ev, 1), 1);\n evn = ev(n_eigs, :); % explained variance for these eigs; approximate as it is only proportion of first n eigs\n fprintf('Temporal reduction: Eigenvectors explain %3.2f%% +- %3.2f%% of variance.', 100*mean(evn), 100*std(evn));\n \nend\n\nclear eigenvalues eigenvectors\n\n\n%%\n\n%n_eigs = input('Enter number of eigenvectors to save: ');\n\nplot_vertical_line(n_eigs);\ndrawnow\n\nif ~exist(mysavedir, 'dir'), mkdir(mysavedir); end\n\nsaveas(gcf, fullfile(mysavedir, 'Eigenvalues'), 'png');\n\n\nfor i = 1:nsubjects\n group_eigenvectors{s}(:, n_eigs + 1 : end) = [];\nend\n\ngroup_eigenvectors = cat(2, group_eigenvectors{:});\n\n%%\n\n%input('Enter range of clusters: ');\n%niter = 100;\n\nnames = [];\n\n% c = nmdsfig_tools('cluster_solution', [], group_eigenvectors, n_class_range, niter, names);\n\n%% 2nd Dimension redution step : to get scores in lower-dim space for\n% clustering\n\n% Spatial reduction\n% -------------------------------------------------------------------------\n\n[across_eigenvectors, across_scores, across_eigenvalues] = princomp(group_eigenvectors, 'econ');\n\ncreate_figure('group_eigenvalues', 1, 3);\nplot(across_eigenvalues(1:initial_eigval_limit), 'ko-');\ntitle('Across subjects eigenvalues');\n\n% Calculate variance explained for first [n_eigs_across] eigenvalues.\nev = cumsum(across_eigenvalues);\nev = ev ./ sum(across_eigenvalues);\nevn = ev(n_eigs_across, :); % explained variance for these eigs; approximate as it is only proportion of first n eigs\nfprintf('Spatial reduction: Eigenvectors explain %3.2f%% of variance.', 100*evn);\n\n%n_eigs_across = input('Enter number of eigenvectors to save: ');\n\nscores_to_cluster = across_scores(:, 1:n_eigs_across);\n\nplot_vertical_line(n_eigs_across);\n\nsubplot(1, 3, 2)\nimagesc(scores_to_cluster);\n\ndrawnow\n%% CLUSTER voxels\n\nclasses = [];\nsil_vals = {};\nmean_sil = [];\n\nif do_nclasses_search\n\n fprintf('Clustering : ')\n\n % problem with silhouette is that it really finds natural break-point in\n % data; so looks good for 2 clusters with pos/neg groups in data usually.\n\n clear s\n\n for i = n_class_range\n\n fprintf('%3.0f ', i);\n\n classes = clusterdata(scores_to_cluster, 'linkage', 'average', 'maxclust', i);\n sil_vals{i} = silhouette(scores_to_cluster, classes);\n mean_sil(i) = mean(sil_vals{i});\n\n end\n\n fprintf('\\n');\n\n subplot(1, 3, 3)\n plot(n_class_range, mean_sil(n_class_range), 'ko-', 'MarkerFaceColor', [.2 .6 1], 'LineWidth', 2);\n\n saveas(gcf, fullfile(mysavedir, 'Group_eigs_and_clustering'), 'png');\n\nend\n\n\ncl = [clpos_data clneg_data];\n\ndisp(['Saving data file: ' mysavedir filesep 'parcellation.mat'])\nsave(fullfile(mysavedir, 'parcellation'), 'cl', 'n*', '*eig*', '*score*', 'classes', '*sil*')\n\n\n%% % Get parcels of contiguous regions\n% Save averages over voxels for each subject, within each region\n\nfprintf('Getting parcels and associated data: Clustering with %3.0f classes\\n', nclasses)\n\nclasses = clusterdata(scores_to_cluster, 'linkage', 'average', 'maxclust', nclasses);\n\nclear parcel_cl\ndisp('Getting contiguous regions: These become parcels');\n\nfprintf('Subject ');\nfor s = 1:nsubjects\n\n fprintf('%3.0f', s)\n\n if ~isempty(clneg_data)\n cl = [clpos_data{s} clneg_data{s}];\n else\n cl = clpos_data{s};\n end\n\n CLU = clusters2CLU(cl);\n\n for i = 1:max(classes)\n\n my_cl = CLU;\n my_cl.XYZmm = my_cl.XYZmm(:, classes == i);\n my_cl.XYZ = my_cl.XYZ(:, classes == i);\n my_cl.Z = my_cl.Z(:, classes == i);\n\n my_cl.all_data = my_cl.all_data(:, classes == i);\n\n class_clusters{i} = tor_extract_rois([], my_cl, my_cl);\n\n [class_clusters{i}.from_class] = deal(i);\n end\n\n parcel_cl{s} = cat(2, class_clusters{:});\n\nend\nfprintf('\\n')\n\n% Prune parcels here\nif doprune\n [parcel_cl, meanpval, meancor] = prune_parcels(parcel_cl);\n \n disp('Saving meanpval and meancor for pruned parcels in parcellation.mat')\n save(fullfile(mysavedir, 'parcellation.mat'), '-append', 'meanpval', 'meancor')\nend\n\n\nparcel_cl_avgs = parcel_cl{1};\n\n% another convenient format\nfor i = 1:length(parcel_cl_avgs)\n parcel_cl_avgs(i).all_data = cell(1, nsubjects);\n parcel_cl_avgs(i).timeseries = cell(1, nsubjects);\n for s = 1:nsubjects\n parcel_cl_avgs(i).all_data{s} = parcel_cl{s}(i).all_data;\n parcel_cl_avgs(i).timeseries{s} = parcel_cl{s}(i).timeseries;\n end\nend\n \nfprintf('\\n')\n\ndisp('Saving parcel_cl and parcel_cl_avgs in parcellation.mat')\nsave(fullfile(mysavedir, 'parcellation.mat'), '-append', 'class_clusters', 'parcel*')\n\n%volInfo = iimg_read_img('mask.img', 2);\n\n%% RE-do networks on these parcels\n% re-define class clusters\n% refine class (network) membership\n% ---------------------------\n[parcel_cl_avgs, NMDS, class_clusters] = parcel_cl_nmds(parcel_cl_avgs);\n\ndisp('Saving NMDS structure and final class clusters in parcellation.mat')\nsave(fullfile(mysavedir, 'parcellation.mat'), '-append', 'NMDS', 'class_clusters')\n\n%% Plots\n% ---------------------------\n% Plot: data panel\n% Orthviews of parcels\n% Montages of parcels\nparcel_cl_nmds_plots(parcel_cl_avgs, NMDS, 'save', 'savedir', 'Parcellation_info')\n\nend\n\n\n\n%% Sub-functions\n\n\nfunction [parcel_cl, meanpval, meancor] = prune_parcels(parcel_cl)\n\n nsubjects = length(parcel_cl);\n \n %% remove parcels with too few voxels\n vcutoff = 3;\n p_cutoff = .002;\n\n whomit = false(size(parcel_cl{1}));\n nvox = cat(1, parcel_cl{1}.numVox);\n whomit(nvox < vcutoff) = 1;\n fprintf('Eliminated %3.0f parcels smaller than %3.0f voxels\\n', sum(whomit), vcutoff)\n fprintf('Keeping %3.0f parcels\\n', sum(~whomit))\n for s = 1:nsubjects\n parcel_cl{s}(whomit) = [];\n end\n\n nparcels = length(parcel_cl{s});\n [meancor, meanpval, vox_removed] = deal(zeros(nparcels, 1));\n omit_parcels = false(nparcels, 1);\n\n %\n % Get data across subjects for one parcel\n for p = 1:nparcels\n\n fprintf('Parcel %3.0f ', p);\n\n % Get data across subjects for one parcel (p)\n % ---------------------------------------------\n dat = cell(nsubjects, 1);\n for s = 1:nsubjects\n dat{s} = parcel_cl{s}(p).all_data;\n end\n %dat = cat(1, dat{:});\n\n % Correlate, and get stats\n % ---------------------------------------------\n %[c, pvals] = corrcoef(dat);\n clear c\n for i = 1:nsubjects\n c(:, :, i) = corrcoef(dat{i});\n end\n\n % Note: p vals will not be correct if there are NaNs!\n \n mc = nanmean(c, 3);\n se = nanstd(c, 0, 3) ./ sqrt(nsubjects);\n\n mc = mc .* (1 - eye(size(mc)));\n mc = squareform(mc);\n\n se = se .* (1 - eye(size(se)));\n se = squareform(se);\n\n t = mc ./ se;\n pvals = 2 .* (1 - tcdf(abs(t), nsubjects - 1));\n\n meanpval(p) = mean(pvals);\n meancor(p) = mean(mc);\n\n pvals = squareform(pvals);\n\n % Omit the bad (unrelated) voxels\n % ---------------------------------------------\n pv = mean(pvals, 2);\n\n wh = pv > p_cutoff;\n\n vox_removed(p) = sum(wh);\n\n if sum(wh) > length(wh) - vcutoff + 1 \n % we have zero or 1 valid voxels left; omit the whole parcel\n omit_parcels(p) = 1;\n elseif any(wh)\n % omit bad voxels\n\n for s = 1:nsubjects\n parcel_cl{s}(p).XYZmm(:, wh) = [];\n parcel_cl{s}(p).XYZ(:, wh) = [];\n parcel_cl{s}(p).all_data(:, wh) = [];\n\n parcel_cl{s}(p).timeseries = nanmean(parcel_cl{s}(p).all_data, 2);\n parcel_cl{s}(p).numVox = sum(~wh);\n\n end\n\n pvals(wh, :) = [];\n pvals(:, wh) = [];\n mc = squareform(mc);\n mc(wh, :) = [];\n mc(:, wh) = [];\n\n meanpval(p) = mean(squareform(pvals));\n meancor(p) = mean(squareform(mc));\n end\n\n\n\n fprintf(' mean inter-voxel corr: %3.2f, mean p = %3.4f, vox excluded = %3.0f', meancor(p), meanpval(p), vox_removed(p))\n if omit_parcels(p), fprintf(' OMITTED'); end\n fprintf('\\n')\n\n end\n\n % remove whole bad parcels\n for s = 1:nsubjects\n parcel_cl{s}(omit_parcels) = [];\n end\n\n meanpval(omit_parcels) = [];\n meancor(omit_parcels) = [];\n \n % remove parcels that are now too small\n whomit = false(size(parcel_cl{1}));\n nvox = cat(1, parcel_cl{1}.numVox);\n whomit(nvox < vcutoff) = 1;\n fprintf('Eliminated %3.0f parcels smaller than %3.0f voxels\\n', sum(whomit), vcutoff)\n fprintf('Keeping %3.0f parcels\\n', sum(~whomit))\n for s = 1:nsubjects\n parcel_cl{s}(whomit) = [];\n end\n\n nvox = cat(1, parcel_cl{1}.numVox);\n create_figure('Pruned parcels', 2, 1);\n plot(nvox, 'ko', 'MarkerSize', 8, 'MarkerFaceColor', [.5 .5 1]);\n title('Number of voxels in each parcel');\n xlabel('Parcel index number')\n plot_horizontal_line(vcutoff)\n\n subplot(2, 1, 2)\n plot(meancor, 'ko', 'MarkerSize', 8, 'MarkerFaceColor', [.5 .5 1]);\n title('Mean within-subject correlation value with other voxels in parcel')\n drawnow\n\nend\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Parcellation_tools/parcel_clusters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.6037351261532152}} {"text": "function line_data = sphere_cubed_lines ( n, line_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_CUBED_LINES computes the lines on a cubed sphere grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of sections into which each face of\n% the cube is to be divided.\n%\n% Input, integer LINE_NUM, the number of lines.\n%\n% Output, real LINE_DATA(3,2,LINE_NUM), distinct points on the unit sphere\n% generated by a cubed sphere grid.\n%\n line_data = zeros ( 3, 2, line_num );\n\n l = 0;\n%\n% If N = 1, the corners form 12 lines.\n%\n if ( n == 1 )\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n return\n%\n% If 1 < N, each of 8 corners connects to three neighboring edges.\n%\n else\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 1, 0, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 1, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, 1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-1, 0, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 1, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, 1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-1, n, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n-1, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, 1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 1, n, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-1, 0 );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, 1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 1, 0, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 1, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, n-1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-1, 0, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 1, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, n-1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-1, n, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n-1, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, n-1 );\n\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 1, n, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-1, n );\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, n-1 );\n end\n%\n% If 2 < N, then each of the 12 edges includes lines.\n%\n if ( 2 < n )\n\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, 0, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, 0, 0 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, i, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, i+1, 0 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n-i, n, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-i-1, n, 0 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-i, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-i-1, 0 );\n end\n\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, 0, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, 0, n );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, i, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, i+1, n );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n-i, n, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n-i-1, n, n );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-i, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n-i-1, n );\n end\n\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, i );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, 0, i+1 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, i );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, 0, i+1 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, n, i );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, n, i+1 );\n end\n for i = 1 : n - 2\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, i );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, n, i+1 );\n end\n\n end\n%\n% Lines that belong to one of the six faces.\n%\n if ( 1 < n )\n%% 000 : nn0\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, j, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i, j+1, 0 );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, j, 0 );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, j, 0 );\n end\n end\n%% 00n : nnn\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, j, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i, j+1, n );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, j, n );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, j, n );\n end\n end\n%% 000:n0n\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, 0, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i, 0, j+1 );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, 0, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, 0, j );\n end\n end\n%% 0n0:nnn\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, n, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i, n, j+1 );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, i, n, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, i+1, n, j );\n end\n end\n%% 000:0nn\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, i, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, i, j+1 );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, 0, i, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, 0, i+1, j );\n end\n end\n%% n00:nnn\n for i = 1 : n - 1\n for j = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, i, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, i, j+1 );\n end\n end\n for j = 1 : n - 1\n for i = 0 : n - 1\n l = l + 1;\n line_data(1:3,1,l) = sphere_cubed_ijk_to_xyz ( n, n, i, j );\n line_data(1:3,2,l) = sphere_cubed_ijk_to_xyz ( n, n, i+1, j );\n end\n end\n\n end\n\n if ( l ~= line_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_CUBED_LINES - Fatal error!\\n' );\n fprintf ( 1, ' LINE_NUM = %d\\n', line_num );\n fprintf ( 1, ' L = %d\\n', l );\n error ( 'SPHERE_CUBED_LINES - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_grid/sphere_cubed_lines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6037303959586471}} {"text": "function [bler, ber] = Simulation(max_iter, max_err, max_runs, resolution, ebno_vec, N, K)\nR = K/N;\nn = log2(N);\nnum_block_err_bp = zeros(length(ebno_vec), 1);\nnum_bit_err_bp = zeros(length(ebno_vec), 1);\nnum_runs = zeros(length(ebno_vec), 1);\n\n%Indices for enc/decoding\n[M_up, M_down] = index_Matrix(N);\nlambda_offset = 2.^(0 : n);\nllr_layer_vec = get_llr_layer(N);\n\n%code construction\ndesign_snr = 2.5;\nsigma_cc = 1/sqrt(2 * R) * 10^(-design_snr/20);\n[channels, ~] = GA(sigma_cc, N);\n[~, channel_ordered] = sort(channels, 'descend');\ninfo_bits = sort(channel_ordered(1 : K), 'ascend');\nfrozen_bits = ones(N , 1);\nfrozen_bits(info_bits) = 0;\n\ntic\nfor i_run = 1 : max_runs \n if mod(i_run, ceil(max_runs/resolution)) == 1\n disp(['Sim iteration running = ', num2str(i_run)]);\n disp(['N = ' num2str(N) ' K = ' num2str(K) ' GA construction SNR = ' num2str(design_snr) 'dB' ' Max Iter Number = ' num2str(max_iter)])\n disp('BP BLER')\n disp(num2str([ebno_vec' num_block_err_bp./num_runs]));\n disp(' ')\n end\n u = zeros(N, 1);\n info = rand(K, 1) < 0.5 ;\n u(info_bits) = info;\n x = polar_encoder(u, lambda_offset, llr_layer_vec);\n bpsk = 1 - 2 * x;\n noise = randn(N, 1); \n for i_ebno = 1 : length(ebno_vec) \n if num_block_err_bp(i_ebno) > max_err\n continue;\n end\n num_runs(i_ebno) = num_runs(i_ebno) + 1;\n sigma = 1 / sqrt(2 * R) * 10^(-ebno_vec(i_ebno)/20);\n y = bpsk + sigma * noise;\n llr = 2/sigma^2 * y;\n [info_esti_bp, ~, ~, ~] = BP_Decoder_LLR(info_bits, frozen_bits, llr, max_iter, M_up, M_down);\n if any(info_esti_bp ~= info)\n num_block_err_bp(i_ebno) = num_block_err_bp(i_ebno) + 1;\n num_bit_err_bp(i_ebno) = num_bit_err_bp(i_ebno) + sum(info ~= info_esti_bp);\n end\n\n end\nend\ntoc\nbler = num_block_err_bp./num_runs;\nber = num_bit_err_bp./num_runs/K;\nend\n", "meta": {"author": "YuYongRun", "repo": "PolarCodeDecodersInMatlab", "sha": "f1b512d10bf057e83f18685ea012d242bdaaf6ac", "save_path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab", "path": "github-repos/MATLAB/YuYongRun-PolarCodeDecodersInMatlab/PolarCodeDecodersInMatlab-f1b512d10bf057e83f18685ea012d242bdaaf6ac/PolarCodeBPdecoder/Simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6036848980403265}} {"text": "% 自由增长模型演示程序\n\nts = 0 : 20; % 时间天数\nlambda = 0.3; % 每个病人每天感染人数\nx0 = 1; % 初始病人数\ninfective = x0 * exp(lambda * ts); % 病人数指数增长\nplot(ts, infective);\ntitle('自由增长模型');\ngrid;", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/NovelCoronaVirus/free_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6036848779218191}} {"text": "function [Z,L,obj,err,iter] = latlrr(X,lambda,opts)\n\n% Solve the Latent Low-Rank Representation by M-ADMM\n%\n% min_{Z,L,E} ||Z||_*+||L||_*+lambda*loss(E),\n% s.t., XZ+LX-X=E.\n% loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1}\n% ---------------------------------------------\n% Input:\n% X - d*n matrix\n% lambda - >0, parameter\n% opts - Structure value in Matlab. The fields are\n% opts.loss - 'l1' (default): loss(E) = ||E||_1 \n% 'l2': loss(E) = 0.5*||E||_F^2\n% 'l21': loss(E) = ||E||_{2,1}\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% Z - n*n matrix\n% L - d*d matrix\n% E - d*n matrix\n% obj - objective function value\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 19/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\nloss = 'l1';\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'loss'); loss = opts.loss; end\nif isfield(opts, 'tol'); tol = opts.tol; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\neta1 = 1.02*2*norm(X,2)^2; % for Z\neta2 = eta1; % for L\neta3 = 1.02*2; % for E\n\n[d,n] = size(X);\nE = zeros(d,n);\nZ = zeros(n,n);\nL = zeros(d,d);\nY = E;\n\nXtX = X'*X;\nXXt = X*X';\n\niter = 0;\nfor iter = 1 : max_iter\n Lk = L;\n Ek = E;\n Zk = Z;\n % first super block {Z}\n [Z,nuclearnormZ] = prox_nuclear(Zk-(X'*(Y/mu+L*X-X-E)+XtX*Z)/eta1,1/(mu*eta1));\n % second super block {L,E}\n temp = Lk-((Y/mu+X*Z-Ek)*X'+Lk*XXt-XXt)/eta2;\n [L,nuclearnormL] = prox_nuclear(temp,1/(mu*eta2)); \n if strcmp(loss,'l1')\n E = prox_l1(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3));\n elseif strcmp(loss,'l21')\n E = prox_l21(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3));\n elseif strcmp(loss,'l2')\n E = (Y+mu*(X*Z+Lk*X-X+(eta3-1)*Ek))/(lambda+mu*eta3);\n else\n error('not supported loss function');\n end\n \n dY = X*Z+L*X-X-E;\n chgL = max(max(abs(Lk-L)));\n chgE = max(max(abs(Ek-E)));\n chgZ = max(max(abs(Zk-Z)));\n chg = max([chgL chgE chgZ max(abs(dY(:)))]);\n if DEBUG \n if iter == 1 || mod(iter, 10) == 0\n obj = nuclearnormZ+nuclearnormL+lambda*comp_loss(E,loss);\n err = norm(dY,'fro')^2;\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', obj=' num2str(obj) ', err=' num2str(err)]); \n end\n end\n \n if chg < tol\n break;\n end \n Y = Y + mu*dY;\n mu = min(rho*mu,max_mu); \nend\nobj = nuclearnormZ+nuclearnormZ+lambda*comp_loss(E,loss);\nerr = norm(dY,'fro')^2;\n\nfunction out = comp_loss(E,loss)\n\nswitch loss\n case 'l1'\n out = norm(E(:),1);\n case 'l21'\n out = 0;\n for i = 1 : size(E,2)\n out = out + norm(E(:,i));\n end\n case 'l2'\n out = 0.5*norm(E,'fro')^2;\nend\n\n ", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/latlrr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6893056040203136, "lm_q1q2_score": 0.603684876801536}} {"text": "function [ o, x, w ] = en_r2_07_2 ( n )\n\n%*****************************************************************************80\n%\n%% EN_R2_07_2 implements the Stroud rule 7.2 for region EN_R2.\n%\n% Discussion:\n%\n% The rule has order O = 2^(N+1) + 4 * N^2.\n%\n% The rule has precision P = 7.\n%\n% EN_R2 is the entire N-dimensional space with weight function\n%\n% w(x) = exp ( - x1^2 - x2^2 ... - xn^2 ) \n%\n% The rule requires 3 <= N.\n%\n% The reference has a typographical error in the description of this rule.\n% The formula:\n%\n% (t,t,t,...,t)FS\n%\n% should read\n%\n% (t,t,0,...,0)FS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n% 3 <= N.\n%\n% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EN_R2_07_2 - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= N is required.\\n' );\n error ( 'EN_R2_07_2 - Fatal error!' );\n end\n\n o = 2^(n+1) + 4 * n^2;\n volume = sqrt ( pi^n );\n\n rho1 = sqrt ( ( n + 2 - sqrt ( 2 * ( n + 2 ) ) ) / 2 );\n rho2 = sqrt ( ( n + 2 + sqrt ( 2 * ( n + 2 ) ) ) / 2 );\n a1 = ( n + 2 + sqrt ( 2 * ( n + 2 ) ) ) / 2 / ( n + 2 );\n a2 = ( n + 2 - sqrt ( 2 * ( n + 2 ) ) ) / 2 / ( n + 2 );\n\n r = 1.0;\n s = sqrt ( 1 / n );\n t = sqrt ( 1 / 2 );\n b = ( 8 - n ) * volume / n / ( n + 2 ) / ( n + 4 );\n c = n^3 * volume / 2^n / n / ( n + 2 ) / ( n + 4 );\n d = 4 * volume / n / ( n + 2 ) / ( n + 4 );\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n k = 0;\n%\n% 2 * 2 * N points.\n%\n for i = 1 : n\n k = k + 1;\n x(i,k) = - rho1 * r;\n w(k) = a1 * b;\n k = k + 1;\n x(i,k) = - rho2 * r;\n w(k) = a2 * b;\n k = k + 1;\n x(i,k) = + rho1 * r;\n w(k) = a1 * b;\n k = k + 1;\n x(i,k) = + rho2 * r;\n w(k) = a2 * b;\n end\n%\n% 2 * 2^N points.\n%\n k = k + 1;\n x(1:n,k) = - rho1 * s;\n w(k) = a1 * c;\n k = k + 1;\n x(1:n,k) = - rho2 * s;\n w(k) = a2 * c;\n more = 1;\n while ( more )\n more = 0;\n for i = n : -1 : 1\n if ( x(i,k) < 0.0 )\n k = k + 1;\n x(1:n,k) = x(1:n,k-2);\n x(i,k) = abs ( x(i,k) );\n x(i+1:n,k) = - abs ( x(i+1:n,k) );\n w(k) = a1 * c;\n k = k + 1;\n x(1:n,k) = x(1:n,k-2);\n x(i,k) = abs ( x(i,k) );\n x(i+1:n,k) = - abs ( x(i+1:n,k) );\n w(k) = a2 * c;\n more = 1;\n break;\n end\n end\n end\n%\n% 2 * 4 * ( N * ( N - 1 ) / 2 ) points.\n%\n for i = 1 : n - 1\n for j = i + 1 : n\n k = k + 1;\n x(i,k) = - rho1 * t;\n x(j,k) = - rho1 * t;\n w(k) = a1 * d;\n k = k + 1;\n x(i,k) = - rho1 * t;\n x(j,k) = + rho1 * t;\n w(k) = a1 * d;\n k = k + 1;\n x(i,k) = + rho1 * t;\n x(j,k) = - rho1 * t;\n w(k) = a1 * d;\n k = k + 1;\n x(i,k) = + rho1 * t;\n x(j,k) = + rho1 * t;\n w(k) = a1 * d;\n k = k + 1;\n x(i,k) = - rho2 * t;\n x(j,k) = - rho2 * t;\n w(k) = a2 * d;\n k = k + 1;\n x(i,k) = - rho2 * t;\n x(j,k) = + rho2 * t;\n w(k) = a2 * d;\n k = k + 1;\n x(i,k) = + rho2 * t;\n x(j,k) = - rho2 * t;\n w(k) = a2 * d;\n k = k + 1;\n x(i,k) = + rho2 * t;\n x(j,k) = + rho2 * t;\n w(k) = a2 * d;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/en_r2_07_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.6036848723320507}} {"text": "%% Mean-Shift Video Tracking\n% by Sylvain Bernhardt\n% July 2008\n%% Description\n% Measures the similarity between two\n% density estimations q and p done with\n% a kernel which profile is k.\n% q is the estimation of a reference patch\n% and p the estimation of a candidate one 'T2'\n% which size is H,W.\n% The outputs are the similarity value f\n% and the weight mask w for the gradient ascent\n% in the extended Mean-Shift algorithm.\n%\n% [f,w] = Simil_func(q,p,T2,k,H,W)\n\nfunction [f,w] = Simil_func(q,p,T2,k,H,W)\n\nw = zeros(H,W);\nf = 0;\nfor i=1:H\n for j=1:W\n w(i,j) = sqrt(q(T2(i,j)+1)/p(T2(i,j)+1));\n f = f+w(i,j)*k(i,j);\n end\nend\n% Normalization of f\nf = f/(H*W);", "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/35520-mean-shift-video-tracking/MeanShift_Code/Simil_func.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6036668763632214}} {"text": "function [varargout] = slick(coords)\n % turned into MATLAB from C by Celso G Reyes\n % accepts input of [DipDir, Dip, Rake]\n % returns different items, based on varargout.\n \n % answer is CLOSE to original, but does not match. Sig Figs? Technique?\n \n TORADS = 57.29577951;\n \n % COORDINATES ARE EAST,NORTH,UP\n % this version does no statistics\n % and therefore makes no plot\n \n assert(size(coords,2) == 3); % [ ddir, dip, rake ] as ENU\n \n % ddir = zeros(MAXDATA,1); % dip direction for data\n % dip = zeros(MAXDATA,1); % dip of data\n % rake = zeros(MAXDATA,1); % rake of data\n % amat = zeros(MAX3,5); % coefficient matrix for normal equation\n % stress = zeros(6,1); % stress tensor in vector form, element order is:\n % xx,xy,xz,yy,yz,zz\n % slick_vec_el_vec slickenside vector elements vector\n % norm % storage of n1,n2,n3\n char name(20); % output file name\n %FILE *fpin; % input file pointer\n %FILE *fpout; % output file pointer\n %FILE *fplot; % plot file pointer\n % sigma = 0; % for use with leasq subr\n % a2i = zeros(5,5); % to get covariance mtrix\n line=''; % character line\n t = zeros(3,1); % shear stress vector\n % iso = 0; % isotropic stress mag\n %angavg = 0; angstd = 0; % average and standard deviation of fit angle\n %isoavg = 0; isostd = 0; % same for isotropic stress size\n magavg = 0; magstd = 0; % same for tangential stress size\n % tf = zeros(3,1), tnorm; % full traction vector\n % and normal traction\n \n % get file pointers\n %{\n -- argc;\n ++argv;\n if argc == 0\n printf(\"usage: slick data_file\\n\");\n return;\n end\n fpin = fopen(argv,\"r\");\n if fpin==NULL\n printf(\"unable to open %s.\\n\",argv);\n return;\n end\n fprintf(name,\"%s.oput\",argv);\n %}\n % read and write comment line from data file to output file\n % fgets(line,80,fpin);\n line = 'Inversion data';\n fpout = string(line);\n ddir = coords(:,1);\n dip = coords(:,2);\n rake = coords(:,3);\n % loop to get data and make up equation\n for i=1:size(coords,1)\n %ddir = coords(i,1); dip = coords(i,2); rake = coords(i,3);\n j = 3*i;%?\n \n z = ddir(i)/TORADS;\n z2 = dip(i)/TORADS;\n z3 = rake(i)/TORADS;\n \n %n1 to n3 are normal vector elements\n n1 = sin(z)*sin(z2); % normal vector to fault plane\n n2 = cos(z)*sin(z2);\n n3 = cos(z2);\n \n norm(i,1:3) = [n1 n2 n3];\n \n % slickenside vector calculation\n slick_vec_el_vec(j,1)= -cos(z3)*cos(z) - sin(z3)*sin(z)*cos(z2);\n slick_vec_el_vec(j+1,1)= cos(z3)*sin(z) - sin(z3)*cos(z)*cos(z2);\n slick_vec_el_vec(j+2,1)= sin(z3)*sin(z2);\n \n % find the matrix elements\n amat(j:j+2, 1:5) = [...\n n1-n1*n1*n1+n1*n3*n3, n2-2.*n1*n1*n2, n3-2.*n1*n1*n3, -n1*n2*n2+n1*n3*n3, -2.*n1*n2*n3 ;...\n -n2*n1*n1+n2*n3*n3, n1-2.*n1*n2*n2, -2.*n1*n2*n3, n2-n2*n2*n2+n2*n3*n3, n3-2.*n2*n2*n3;...\n -n3*n1*n1-n3+n3*n3*n3, -2.*n1*n2*n3, n1-2.*n1*n3*n3, -n3*n2*n2-n3+n3*n3*n3, n2-2.*n2*n3*n3];\n \n % check to see if all possible data has been read\n end % end of data read loop\n\n\t% solve equations via linear least squares\n\t[stress, sigma]=leasq(amat,slick_vec_el_vec);\n\t% correct zz element by using trace = 0\n\tstress(6)= -(stress(1)+stress(4));\n\n\t% put stress tensor into tensor form\n strten = [ stress(1), stress(2), stress(3) ; \n stress(2), stress(4), stress(5) ; \n stress(3), stress(5), stress(6)];\n\n %fpout(end+1)=sprintf(\"\\nCOORDINATES ARE EAST,NORTH,UP.\");\n %fpout(end+1)=sprintf(\"stress tensor is:\");\n for i=1:3\n % fpout(end+1)=sprintf(\"%g %g %g \",strten(i,:));\n end\n\n\t% find eigenvalues and eigenvectors\n [vecs,lam] = eig(strten,\"vector\"); %LAM is eigenvalues, VECS is eigenvectors\n % eigen(strten,lam,vecs);\n %fpout(end+1)=sprintf(\"eigenvalue vector: E,N,UP,direction,plunge\");\n for i = 3:-1:1\n [v_direction(i), v_plunge(i)] = dirplg(vecs(1,i),vecs(2,i),vecs(3,i));\n %[z, z2] = dirplg(vecs(1,i),vecs(2,i),vecs(3,i));\n %fpout(end+1)=sprintf(\"%g \",lam(i)) +...\n % sprintf(\"%g %g %g \",vecs(:,i)) +...\n % sprintf(\"%f %f\",z,z2);\n end\n %fpout(end+1)=sprintf(\"variance= %g\",sigma);\n \n\t% order eigenvalues and compute phi\n %lam=sort(lam,'descend');\n \n if lam(1) ~= lam(3)\n phi = (lam(2)-lam(3)) / (lam(1)-lam(3));\n %fpout(end+1)=sprintf(\"phi value= %g\",phi);\n else\n phi=nan;\n end\n\t% output data and fit angle\n\n\tangavg = 0.;\n\tangstd = 0.;\n\tisoavg = 0.;\n\tisostd = 0.;\n\tiso = 0.;\n\t%fpout(end+1)=sprintf(\"\\ndip direction, dip, rake, fit angle, mag tau\");\n nobs=size(coords,1);\n for i=1:nobs %from 0\n \n for j= 1 : 3 %from 0 % compute shear traction\n t(j)=0;\n tf(j)=0;\n myt(j) = sum(amat(3*(i-1)+j) * stress(1:5));\n for k=1:5\n t(j) = t(j)+ amat(3*(i-1)+j,k) * stress(k);\n end\n for k=1:3\n tf(j) = tf(j) + strten(j,k) * norm(i,k);\n end\n end\n tnorm = 0;\n for k=1:3\n tnorm = tnorm + tf(k) * norm(i,k);\n end\n % find angle between t and slickenside\n z = 0.;\n for j=1:3\n z = z + t(j)*slick_vec_el_vec(3*(i-1)+j);\n end\n z2 = 0.;\n for j=1:3\n z2 = z2 + t(j)*t(j);\n end\n z2 = sqrt(z2);\n z3 = 0.;\n for j=1:3\n z3 = z3 + slick_vec_el_vec(3*(i-1)+j)*slick_vec_el_vec(3*(i-1)+j);\n end\n z3 = sqrt(z3);\n z = z/(z2*z3);\n z = acos(z)*TORADS;\n angavg = angavg + z;\n angstd = angstd + z*z;\n z3= (z2/(-0.8)) - tnorm;\n iso = iso + abs(tnorm);\n isoavg = isoavg +z3;\n isostd = isostd + z3*z3;\n magavg = magavg +z2;\n magstd = magstd + z2*z2;\n %fpout(end+1)=sprintf(\"%7.1f %7.1f %7.1f %7.1f %7.2f\", ddir(i),dip(i),rake(i),z,z2);\n end\n z3 = nobs-1;\n angstd = angstd-(angavg*angavg/nobs);\n angstd = angstd/z3;\n angstd = sqrt(angstd);\n angavg = angavg/nobs;\n \n isostd = isostd-(isoavg*isoavg/nobs);\n isostd = isostd/z3;\n isostd = sqrt(isostd);\n isoavg = isoavg/nobs;\n iso = iso / nobs;\n isoavg = isoavg / iso;\n isostd = isostd / iso;\n \n magstd = magstd-(magavg*magavg/nobs);\n magstd = magstd/z3;\n magstd = sqrt(magstd);\n magavg = magavg/nobs;\n \n %fpout(end+1)=sprintf(\"fit angle mean= %f standard deviation= %f\",angavg,angstd);\n %fpout(end+1)=sprintf(\"for f=0.8 I= %f , std. dev.= %f D norm= %f\", isoavg,isostd,iso);\n %fpout(end+1)=sprintf(\"avg tau= %f , std. dev.= %f\",magavg,magstd);\n \n if nargout==1\n fpout(end+1)=sprintf(\"fit angle mean= %f standard deviation= %f\",angavg,angstd);\n fpout(end+1)=sprintf(\"for f=0.8 I= %f , std. dev.= %f D norm= %f\", isoavg,isostd,iso);\n fpout(end+1)=sprintf(\"avg tau= %f , std. dev.= %f\",magavg,magstd);\n \n varargout = {strjoin(fpout,newline)};\n elseif nargout == 5\n varargout={angavg, angstd, magstd/magavg, magavg, magstd}; %[fBeta2, fStdBeta2, fTauFit2, fAvgTau2, fStdTau2]\n elseif nargout == 9\n varargout=fastoutput();\n end\n \n function output = fastoutput()\n %%line 1\n % variance\n output = {... line 1 of output file\n sigma,... variance\n stress,... stress tensor upper triangle\n ... line 2 of output file\n phi,...\n round(v_direction(1),1),...\n round(v_plunge(1),1),...\n round(v_direction(2),1),...\n round(v_plunge(2),1),...\n round(v_direction(3),1),...\n round(v_plunge(3),1)...\n };\n end\n \n \nend\n\nfunction [pdir, pplg] = dirplg(e,n,u)\n % dirplb to find direction and plunge of a vector\n % double e,n,u; /* the vector in east,north,up coordinates\n % double *pdir,*pplg are pointers to the direction in east of north\n % and the plunge down the direction\n \n TORADS = 57.29577951;\n \n z=e*e+n*n;\n z=sqrt(z);\n pplg=atan2(-u,z) * TORADS;\n if pplg<0\n pplg= -pplg;\n e= -e;\n n= -n;\n end\n pdir=atan2(e,n) * TORADS;\nend\n\nfunction [x, psis] = leasq(a,b)\n% /* finds the least squares solution of ax=b */\n%{\ndouble a[]; /* the coefficients matrix with n rows and m columns */\ndouble x[]; /* the solution vector of length m */\ndouble b[]; /* the constant vector of length n */\ndouble a2[]; /* a square matrix of size m for internal use */\ndouble c[]; /* vector of length m for internal use */\ndouble *psis; /*pointer to the variance */\n\n/* steps 1 a2= a transpose a */\n/* 2 c= a transpose b */\n/* 3 solve a2x=c by gaussian elimination */\n%}\n\n\t% a2=atransa(a,a2); % computes b=a transpose*a \n a2 = a' * a;\n c = a' * b;\n x = a2 \\ c;\n\t% x = gaus(a2, c); % solves ax=b for x by gaussian elimination\n\tpsis = sigsq(a,x,b);\nend\n%{\nfunction x = gaus(a,b)\n % /* solves ax=b for x by gaussian elimination */\n\n\n%double a[]; /* a square matrix of size m */\n%double b[]; /* a vector of length m */\n%double x[]; /* a vector of length m */\n \n m=length(a);\n % take care of special cases */\n if m<2\n x=0;\n if m==1\n x=b/a;\n end\n return\n end\n \n\n\tfor i=1:m % (i=0;i pivot flop rows */\n\t\t\tif(abs(a(i2,i))>abs(a(i,i)))\n\t\t\t\thold=b[i];\n\t\t\t\tb[i]=b[i2];\n\t\t\t\tb[i2]=hold;\n\t\t\t\tfor(i3=i;i3 -1;--i){\n\t\td=b[i];\n\t\tfor(i2=i+1;i21), error('Euler axis must be x,y or z'); end\nfor i=1:length(m)\n x=y(m(i),:);\n b=0.5*t(i);\n c=cos(b);\n s=sin(b);\n r=zeros(4,1);\n r(x(1:2))=q(x(3:4));\n r(x(5:6))=-q(x(7:8));\n q=c*q+s*r;\nend\nf=find(q~=0);\nif (q(f(1))<0), q=-q; end", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/roteu2qr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6035850971355341}} {"text": "function [xopt,fval,exitflag,output] = spcgsearch(z, xbox, options)\n% SPCGSEARCH Optimizes the sparse grid interpolant using the CG \n% method.\n% X = SPCGSEARCH(Z) Starts search at the best available\n% sparse grid point and attempts to find a local minimizer of the\n% sparse grid interpolant Z. The entire range of the sparse\n% grid interpolant is searched.\n%\n% X = SPCGSEARCH(Z,XBOX) Uses the search box XBOX = [a1,\n% b1; a2, b2; ...]. The size of search box XBOX must be smaller \n% than or equal to the range of the interpolant.\n%\n% X = SPCGSEARCH(Z,XBOX,OPTIONS) Minimizes with the default\n% optimization parameters replaced by values in the structure\n% OPTIONS, created with the SPOPTIMSET function. See SPOPTIMSET\n% for details.\n%\n% [X,FVAL] = SPCGSEARCH(...) Returns the value of the \n% sparse grid interpolant at X.\n%\n% [X,FVAL,EXITFLAG] = SPCGSEARCH(...) Returns an EXITFLAG \n% that describes the exit condition of SPCGSEARCH. Possible\n% values of EXITFLAG and the corresponding exit conditions are\n%\n% 1 SPCGSEARCH converged to a solution X.\n% 0 Maximum number of function evaluations or iterations\n% reached.\n%\n% [X,FVAL,EXITFLAG,OUTPUT] = SPCGSEARCH(...) Returns a \n% structure OUTPUT with the number of function evaluations in \n% OUTPUT.nFEvals, the number of gradients in .nGradEvals,\n% and the computing time in .time.\n%\n% Example: (minimizing the three-hump camel-back function)\n% f = inline('12*x.^2-6.3*x.^4+x.^6+6*y*(y-x)');\n% range = [-3 3; -3 3];\n% options = spset('keepFunctionValues','on', ...\n% 'GridType', 'Chebyshev', ...\n% 'DimensionAdaptive', 'on', ...\n% 'DimAdaptDegree', 1, ...\n% 'MinPoints', 10);\n% z = spvals(f, 2, range, options)\n% [xopt, fval] = spcgsearch(z)\n%\n% See also SPOPTIMSET.\n\t\n% Author : Andreas Klimke\n% Version: 1.0\n% Date : September 1, 2007\n\n% Change log:\n% V1.0 : September 1, 2007\n% Initial version.\n\t\n% ------------------------------------------------------------\n% Sparse Grid Interpolation Toolbox\n% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart \n% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.\n% See LICENSE.txt for license. \n% email: klimkeas@ians.uni-stuttgart.de\n% web : http://www.ians.uni-stuttgart.de/spinterp\n% ------------------------------------------------------------\n\nt0 = clock;\n\nif nargin < 2, xbox = []; end\nif nargin < 3, options = []; end\n\nd = z.d;\n\n% In case that no range has been provided to spvals -> set it to\n% [0,1]^d. \nrange = z.range;\nif isempty(range)\n\trange = [zeros(d,1) ones(d,1)];\nend\nif isempty(xbox)\n\txbox = range;\nend\n\n% Break if maximize is set; not yet supported.\nmaximize = spoptimget(options, 'Maximize', 'off');\nminimize = spoptimget(options, 'Minimize', 'on');\nif strcmpi(maximize, 'on')\n warning('MATLAB:spinterp:unsupported',['spcgsearch ' ...\n\t 'does currently not support searching for maxima. ' ...\n\t\t'Search for local maximum is skipped.']);\n\toptions = spoptimset(options, 'Maximize', 'off');\n if strcmpi(minimize, 'off')\n xopt = NaN;\n\t fval = NaN;\n\t exitflag = 0;\n\t if nargout == 4\n\t\t output.nFEvals = 0;\n\t\t output.nGradEvals = 0;\n\t\t output.time = etime(clock, t0);\n\t end\n\t return;\n end\nend\n\n% Determine optimization start point\n[x, fval] = spgetstartpoint(z, xbox, options);\nfprev = fval;\n\nmaxiter = spoptimget(options, 'MaxIter', 100);\ntolfun = spoptimget(options, 'TolFun', 1e-6);\ndispopt = spoptimget(options, 'Display', 'off');\n[isdispiter, iterstr] = initoptidisp(dispopt);\n\nif isfield(z,'selectOutput')\n\tnumout = z.selectOutout;\nelse\n\tnumout = 1;\nend\t\nabstol = (z.fevalRange(numout,2) - z.fevalRange(numout,1)).*100*eps;\n\n% Default tolx is computed from range times floating point accuracy.\ntolxvec = eps * (range(:,2) - range(:,1));\n\n% Define step size variable; initial value will be computed by\n% spminbracket.\nstepsize = [];\n\n% Do a maximum of 50 inner iterations\nbrentopt = spoptimset('MaxIter',50,'TolFun',tolfun);\n\n[dummy, gf] = spsurfun(x,z);\n\nnfevals = 1; ngradevals = 1;\nif isdispiter, disp(sprintf(iterstr, 0, 1, 1, fprev, 'start point')); end\nneggf = -gf;\nxi = neggf;\nh = neggf;\n\nexitflag = 0;\nfor k = 1:maxiter\n\t% Check if gradient is zero\n\tgg = dot(neggf,neggf);\n\tif gg == 0.0\n\t\texitflag = 1;\n\t\tbreak;\n\tend\n\t% Check if new search direction is all-zero vector\n\tif dot(xi,xi) == 0.0\n\t\texitflag = 1;\n\t\tbreak;\n\tend\n\t[xbrac,fxbrac,bflag,p,fp,gfp,addfevals] = ...\n\t spminbracket(z,x,fval,-neggf,xi,xbox,[],stepsize);\n\tnfevals = nfevals + addfevals;\n\n\tif bflag == 0 || bflag == 2\n\t\t% Compute tolx along the search line\n\t\tbrentopt.TolX = abs(dot(xi / norm(xi), tolxvec));\n\t\tbrentopt.gf = -neggf;\n\t\t[u,fnext,flag,tempoutput] = spbrent(z,x,xi,xbrac,fxbrac,brentopt);\n\t\t\n\t\t% Next line intentionally commented out (AK)\n\t\t% if 2.0*(fnext-fprev) <= tolfun * (abs(fnext)+abs(fprev)+eps);\n\t\t\n\t\t% Security check that fval has not increased beyond\n\t\t% allowed tolerance for break condition\n\t\tfval = fnext;\n\t\tstepsize = norm(xi * u);\n\t\tx = x + xi * u;\n\t\t\n\t\t% Next line intentionally commented out (AK)\n\t\t% end\n\t\t\n\t\tnfevals = nfevals + tempoutput.nFEvals;\n\t\tif isdispiter, disp(sprintf(iterstr, k, nfevals, ...\n\t\t\t\t\t\t\t\t\t\t\t\tngradevals, fval, 'line search')); end\n\telse\n\t\tif isdispiter, disp(sprintf(iterstr, k, nfevals, ...\n\t\t\t\t\t\t\t\t\t\t\t\tngradevals, fval, 'boundary hit')); end\n\t\tstepsize = norm(x-p);\n\t\tx = p;\n\t\tfval = fp;\n\t\txi = gfp;\n\t\tngradevals = ngradevals + 1;\n\tend\n\t\n\tif 2.0*abs(fval-fprev) <= max(tolfun * (abs(fval)+abs(fprev)),abstol)\n\t exitflag = 1;\n\t break;\n\tend\n\n\tfprev = fval;\n\tif bflag == 0 || bflag == 2\n\t [dummy, xi] = spsurfun(x,z);\n\t\tnfevals = nfevals + 1;\n\t\tngradevals = ngradevals + 1;\n\tend\n\tdgg = dot((xi + neggf),xi);\n\tneggf = -xi;\n\txi = neggf + dgg / gg * h;\n\t% Adjust search direction for boundary\n\tfor l = 1:d\n\t\tif x(l) <= xbox(l,1) + 100*eps*(range(l,2)-range(l,1))\n\t\t\tif neggf(l) < 0\n\t\t\t xi(l) = 0;\n\t\t\telseif sign(xi(l)) < 0\n\t\t\t xi(l) = neggf(l);\n\t\t end\n\t end\n\t\tif x(l) >= xbox(l,2) - 100*eps*(range(l,2)-range(l,2))\n\t\t if neggf(l) > 0 \n\t\t\t xi(l) = 0;\n\t\t elseif sign(xi(l)) > 0\n\t\t\t xi(l) = neggf(l);\n\t\t\tend\n\t\tend\n\tend\n\th = xi;\nend\n\nxopt = x;\n\n% Return stats\nif nargout == 4\n output.nFEvals = nfevals;\n output.nGradEvals = ngradevals;\n\toutput.time = etime(clock, t0);\nend\n\nif strcmpi(maximize, 'on')\n xopt = [xopt NaN.*ones(size(xopt))];\n\tfval = [fval NaN];\n\texitflag = [exitflag 0];\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spinterp/spcgsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6035850843415176}} {"text": "function [] = showSuperquadrics(x, varargin)\n\nR = eul2rotm(x(6 : 8));\nt = x(9 : 11);\n\n% with tapering or not\ntaper = false;\ncolor = 'r';\nViewAxis = [0 0];\nCamRoll = 0;\nShowAxis = 0;\narclength = 0.02;\nFaceAlpha = 1;\nFaceLighting = 'flat';\nlighting = false;\n\nfor k = 1 : size(varargin, 2)\n if strcmp(varargin{k}, 'Taper')\n taper = varargin{k + 1};\n end\n if strcmp(varargin{k}, 'Color')\n color = varargin{k + 1};\n end\n if strcmp(varargin{k}, 'ViewAxis')\n ViewAxis = varargin{k + 1};\n end\n if strcmp(varargin{k}, 'CamRoll')\n CamRoll = varargin{k + 1};\n end\n if strcmp(varargin{k}, 'ShowAxis')\n ShowAxis= varargin{k + 1};\n end\n if strcmp(varargin{k}, 'Arclength')\n arclength= varargin{k + 1};\n end\n if strcmp(varargin{k}, 'FaceAlpha')\n FaceAlpha= varargin{k + 1};\n end\n if strcmp(varargin{k}, 'FaceLighting')\n FaceLighting= varargin{k + 1};\n end\n if strcmp(varargin{k}, 'Light')\n lighting= varargin{k + 1};\n end\nend\n\n% validate dimensionality\nif taper == true\n if size(x, 2) ~= 13\n error('Input parameters should have dimension (:, 13) for taperred SQ.')\n end\nelse\n if size(x, 2) ~= 11\n error('Input parameters should have dimension (:, 11) for taperred SQ.')\n end\nend\n\n% avoiding numerical instability of points sampling on superquadrics\nif x(1) < 0.01 %0.007\n x(1) = 0.01;\nend\nif x(2) < 0.01\n x(2) = 0.01;\nend\n\n[point_eta] = uniformSampledSuperellipse(x(1), [1, x(5)], arclength);\n[point_omega] = uniformSampledSuperellipse(x(2), [x(3), x(4)], arclength);\n\nx_mesh = ones(size(point_omega, 2), size(point_eta, 2));\ny_mesh = ones(size(point_omega, 2), size(point_eta, 2));\nz_mesh = ones(size(point_omega, 2), size(point_eta, 2));\n\nfor m = 1 : size(point_omega, 2)\n for n = 1 : size(point_eta, 2)\n point_temp = [point_omega(:, m) * point_eta(1, n); point_eta(2, n)];\n \n if taper == true\n fx = x(12) * point_temp(3) / x(5) + 1;\n fy = x(13) * point_temp(3) / x(5) + 1;\n fz = 1;\n \n point_temp(1) = point_temp(1) * fx;\n point_temp(2) = point_temp(2) * fy;\n point_temp(3) = point_temp(3) * fz;\n end\n \n point_temp = R * point_temp + t';\n \n x_mesh(m, n) = point_temp(1);\n y_mesh(m, n) = point_temp(2);\n z_mesh(m, n) = point_temp(3);\n end\nend\n\nmesh(x_mesh, y_mesh, z_mesh, 'FaceAlpha', FaceAlpha, 'facecolor', color, ...\n 'LineStyle', 'none', 'FaceLighting', FaceLighting)\nif lighting == 1\n light\n material dull\nend\n\naxis equal\nview(ViewAxis)\ncamroll(CamRoll)\n\nif ShowAxis == 0\n axis off\nend\n\nhold off\n% ---------------------------------utility functions ----------------------\n function [point, theta] = uniformSampledSuperellipse(epsilon, scale, arclength)\n threshold = 1e-2;\n num_limit = 10000;\n theta = zeros(1, num_limit);\n theta(1) = 0;\n \n for i = 2 : num_limit\n dt = dtheta(theta(i - 1), arclength, threshold, scale, epsilon);\n theta_temp = theta(i - 1) + dt;\n \n if theta_temp > pi/4\n break\n else\n if i < num_limit\n theta(i) = theta_temp;\n else\n error(['The number of the sampled points exceeds the limit of ', ...\n num2str(num_limit * 4),...\n '. Please increase the arclength or raise the limit'])\n end\n end\n end\n critical = i;\n \n for j = critical + 1 : num_limit\n dt = dtheta(theta(j - 1), arclength, threshold, flip(scale), epsilon);\n theta_temp = theta(j - 1) + dt;\n \n if theta_temp > pi/4\n break\n else\n if j < num_limit\n theta(j) = theta_temp;\n else\n error(['The number of the sampled points exceeds the limit of ', ...\n num2str(num_limit * 4),...\n '. Please increase the arclength or raise the limit'])\n end\n end\n end\n \n num_pt = j - 1;\n theta = theta(1 : num_pt);\n \n points_fw = angle2points(theta(1 : critical - 1), scale, epsilon);\n points_bw = flip(angle2points(theta(critical : end), flip(scale), epsilon), 2);\n point = [points_fw, [points_bw(2, :); points_bw(1, :)]];\n \n point = [point, flip([-point(1, 1 : num_pt - 1); point(2, 1 : num_pt - 1)], 2), ...\n [-point(1, 2 : end); -point(2, 2 : end)], flip([point(1, 1 : num_pt - 1); ...\n -point(2, 1 : num_pt - 1)], 2)];\n \n end\n\n function [dt] = dtheta(theta, arclength, threshold, scale, sigma)\n if theta < threshold\n dt = abs((arclength / scale(2) + (theta)^(sigma))^(1 / sigma) ...\n - (theta));\n else\n dt = arclength / sigma * ((cos(theta) ^ 2 * sin(theta) ^ 2) / ...\n (scale(1) ^ 2 * cos(theta) ^ (2 * sigma) * sin(theta) ^ 4 + ...\n scale(2) ^ 2 * sin(theta) ^ (2 * sigma) * cos(theta) ^ 4))^(1 / 2);\n end\n end\n\n function [point] = angle2points(theta, scale, sigma)\n point = zeros(2, size(theta, 2));\n point(1, :) = scale(1) .* sign(cos(theta)) .* abs(cos(theta)).^sigma;\n point(2, :) = scale(2) .* sign(sin(theta)) .* abs(sin(theta)).^sigma;\n end\n\nend", "meta": {"author": "ChirikjianLab", "repo": "Marching-Primitives", "sha": "717d1085c11b311d13c9ca40cf71e79088f094b3", "save_path": "github-repos/MATLAB/ChirikjianLab-Marching-Primitives", "path": "github-repos/MATLAB/ChirikjianLab-Marching-Primitives/Marching-Primitives-717d1085c11b311d13c9ca40cf71e79088f094b3/MATLAB/src/utility/showSuperquadrics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6035850795587964}} {"text": "function tparameters=scalar_vt_vech_transform(parameters,p,o,q,kappa)\n% SCALAR_VT_VECH(P,Q) parameter transformation. Used to map parameters\n% from a scalar MVGARCH process to the real line. Used in the estimation of SCALAR_VT_VECH.\n%\n% USAGE:\n% [TPARAMETERS]=scalar_vt_vech_transform(PARAMETERS,P,O,Q,KAPPA)\n%\n% INPUTS:\n% PARAMETERS - Column parameter vector\n% P - Positive, scalar integer representing the number of symmetric innovations\n% Q - Non-negative, scalar integer representing the number of lags of conditional variance \n%\n% OUTPUTS:\n% TPARAMETERS - A 1+p+q column vector of transformed parameters corresponding to\n% [alpha(1),...,alpha(p), beta1 ... beta(q)]'\n%\n% COMMENTS:\n% Input parameters must satisfy:\n% (1) alpha(i) >= 0 for i = 1,2,...,p\n% (2) beta(i) >= 0 for i = 1,2,...,q\n% (3) sum(alpha) + sum(beta) < 1\n%\n% See also SCALAR_VT_VECH\n\n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\n\nif size(parameters,2)>size(parameters,1)\n parameters = parameters';\nend\n%Upper bound to keep it a bit away from 1\nUB=.999998;\n\nalpha=parameters(1:p);\ngamma = parameters(p+1:p+o);\nbeta=parameters(p+o+1:p+o+q);\n%Check that the parameters satisfy the necessary constraints\nif any(alpha<0) || any(beta<0) || any(gamma<0) || (sum(alpha)+sum(gamma)/kappa+sum(beta))>=UB\n error('These do not conform to the necessary set of restrictions to be transformed.')\nend\n\n%Alpha, beta cannot be exactly zero or there will be problems with log()\nalpha(alpha<1e-8)=1e-8;\ngamma(gamma<1e-8)=1e-8;\nbeta(beta<1e-8)=1e-8;\n%Up the upper bound a small amount to make sure it is satisfied\nUB=UB+1e-8*(p+o+q);\n\n%Set the scale\nscale=UB;\n%Initialize the transformed parameters\nparameters=[alpha;gamma;beta];\ntparameters=[alpha;gamma;beta];\nfor i=1:(p)\n %Scale the parameters\n tparameters(i)=tparameters(i)/scale;\n %Use an inverse logistic\n tparameters(i)=log(tparameters(i)/(1-tparameters(i)));\n %Update the scale\n scale=scale-parameters(i);\nend\nfor i=p+1:p+o\n %Scale the parameters\n tparameters(i)=tparameters(i)/scale/kappa;\n %Use an inverse logistic\n tparameters(i)=log(tparameters(i)/(1-tparameters(i)));\n %Update the scale\n scale=scale-parameters(i)/kappa;\nend\n\nfor i=p+o+1:p+o+q\n %Scale the parameters\n tparameters(i)=tparameters(i)/scale;\n %Use an inverse logistic\n tparameters(i)=log(tparameters(i)/(1-tparameters(i)));\n %Update the scale\n scale=scale-parameters(i);\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/multivariate/scalar_vt_vech_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.603585077944509}} {"text": "function fem2d_pack_test16 ( )\n\n%*****************************************************************************80\n%\n%% TEST16 tests REFERENCE_TO_PHYSICAL_T6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n n = 16;\n\n ref = [ ...\n 0.00, 0.00; ...\n 1.00, 0.00; ...\n 0.00, 1.00; ...\n 0.50, 0.00; ...\n 0.50, 0.50; ...\n 0.00, 0.50; ...\n 0.25, 0.75; ...\n 0.75, 0.25; ...\n 0.40, 0.10; ...\n 0.30, 0.20; ...\n 0.20, 0.30; ...\n 0.10, 0.40; ...\n 0.10, 0.10; ...\n 0.20, 0.20; ...\n 0.30, 0.30; ...\n 0.40, 0.40 ]';\n t = [ ...\n 0.0, 0.0; ...\n 2.0, 0.0; ...\n 0.0, 4.0; ...\n 1.0, 0.0; ...\n 1.0, 1.0; ...\n 0.0, 2.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST16\\n' );\n fprintf ( 1, ' For an order 6 triangle,\\n' );\n fprintf ( 1, ' REFERENCE_TO_PHYSICAL_T6 maps a reference point to\\n' );\n fprintf ( 1, ' a physical point.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' XSI ETA ==> X\tY\\n' );\n fprintf ( 1, '\\n' );\n\n phy = reference_to_physical_t6 ( t, n, ref );\n\n for j = 1 : n\n fprintf ( 1, ' %8f %8f %8f %8f\\n', ref(1:2,j), phy(1:2,j) );\n end \n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/fem2d_pack_test16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6035570746916408}} {"text": "function denoise_PRL_2010_main\n%\n% This is a demo program of the paper J. Tian, W. Yu, and L. Ma, \"AntShrink: Ant\n% colony optimization for image shrinkage,\" Pattern Recognition Letters,\n% Vol. 31, Oct. 2010, pp. 1751-1758.\n%\n% Contact: eejtian@gmail.com\n%\n% Note that the PSNR values could be slightly different with that reported \n% in paper due to the random number generator used to generate noisy image.\n%\n% The input image should have a square size.\n%\n% Acknowledgement: This program needs Wavelet transform toolbox, which is \n% downloaded from http://www-stat.stanford.edu/~wavelab/.\n\nclear all; close all; clc;\n\n% Load the ground truth image\nimg_truth = double(imread('barbara_truth.bmp'));\n[nRow, nColumn] = size(img_truth); \n\n% Use the ground truth image to generate the noisy image\nnoise_sig_truth = 10; % sigma_n used in the paper. This parameter is adjusted by the user.\nnoise_mu = 0;\nimg_noisy = img_truth + randn(size(img_truth)) .* noise_sig_truth + noise_mu;\n\n% wavelet parameters\nwbase = 'Daubechies';\nmom = 8;\ndwt_level = 5; %note that here, dwt_scale means the decomposition level of the DWT\n[n,J] = func_quadlength(img_truth);\nL = J-dwt_level;%here, L means the size of the coarsest level, 2^L \n\n\nwin_size = 2;\nimg_denoised = zeros(size(img_noisy)); \n\n% Since this is time consuming approach, divide the image into four parts, then \n% conduct denoising for each part\nfor ii=1:4 \n win_size=2; \n\n switch ii\n case 1\n img_denoised(1:end/2,1:end/2) = func_ACOShrink(img_noisy(1:end/2,1:end/2), wbase, mom, dwt_level, win_size); \n case 2\n img_denoised(end/2+1:end,1:end/2) = func_ACOShrink(img_noisy(end/2+1:end,1:end/2), wbase, mom, dwt_level, win_size); \n case 3\n img_denoised(1:end/2,end/2+1:end) = func_ACOShrink(img_noisy(1:end/2,end/2+1:end), wbase, mom, dwt_level, win_size); \n case 4\n img_denoised(end/2+1:end,end/2+1:end) = func_ACOShrink(img_noisy(end/2+1:end,end/2+1:end), wbase, mom, dwt_level, win_size); \n end\n\nend\n\n% Calculate the PSNR performance\nfprintf('PSNR=%.2fdB\\n', func_psnr_gray(img_truth, img_denoised));\n\n% Write the output image\nimwrite(uint8(img_denoised), 'barbara_denoised.bmp','bmp');\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\n% Main algorithm of proposed AntShrink algorithm\nfunction x_out= func_ACOShrink(x_in, wbase, mom, dwt_level, win_size)\n\n[nrow, ncol] = size(x_in);\nL = log2(size(x_in,2))-dwt_level;\n\n% Estimate the noise_sigma from the noisy signal\nqmf = func_MakeONFilter(wbase,mom);\n[temp, coef] = func_NormNoise_2d(x_in, qmf);\nnoise_sigma = 1/coef;\n\nwx = func_FWT2_PO(x_in, L, qmf);\n[n,J] = func_dyadlength(wx);\nws = wx;\n\nrr = (meshgrid(1:nrow))'; cc = meshgrid(1:ncol);\n\nant_search_range_row_min = rr;\nant_search_range_row_max = rr;\nant_search_range_col_min = cc;\nant_search_range_col_max = cc;\n\nfor j=(J-1):-1:L\n [t1,t2] = func_dyad2HH(j);\n ant_search_range_row_min(t1,t2) = min2(t1);\n ant_search_range_row_max(t1,t2) = max2(t1);\n ant_search_range_col_min(t1,t2) = min2(t2);\n ant_search_range_col_max(t1,t2) = max2(t2); \n [t1,t2] = func_dyad2HL(j);\n ant_search_range_row_min(t1,t2) = min2(t1);\n ant_search_range_row_max(t1,t2) = max2(t1);\n ant_search_range_col_min(t1,t2) = min2(t2);\n ant_search_range_col_max(t1,t2) = max2(t2);\n [t1,t2] = func_dyad2LH(j);\n ant_search_range_row_min(t1,t2) = min2(t1);\n ant_search_range_row_max(t1,t2) = max2(t1);\n ant_search_range_col_min(t1,t2) = min2(t2);\n ant_search_range_col_max(t1,t2) = max2(t2);\nend \n\ndata_var = func_signal_variance_estimation(wx, noise_sigma, win_size,ant_search_range_row_min,ant_search_range_row_max,ant_search_range_col_min,ant_search_range_col_max,J,L);\n \nfor j=(J-1):-1:L\n [t1,t2] = func_dyad2HH(j);\n ws(t1,t2) = wx(t1,t2) .* data_var(t1,t2) ./ (data_var(t1,t2) + noise_sigma.^2);\n [t1,t2] = func_dyad2HL(j);\n ws(t1,t2) = wx(t1,t2) .* data_var(t1,t2) ./ (data_var(t1,t2) + noise_sigma.^2);\n [t1,t2] = func_dyad2LH(j);\n ws(t1,t2) = wx(t1,t2) .* data_var(t1,t2) ./ (data_var(t1,t2) + noise_sigma.^2);\nend \n\nx_out = func_IWT2_PO(ws, L, qmf);\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\n% Estimate the signal variance value, which will be used for shrinkage\nfunction result = func_signal_variance_estimation(wx, noise_sigma, win_size,ant_search_range_row_min,ant_search_range_row_max,ant_search_range_col_min,ant_search_range_col_max,J,L)\n\n% System setup\nant_move_step_within_iteration = 5; % the numbe of iterations?\ntotal_iteration_num = 5;\nsearch_clique_mode = 8; \n\nwx = abs(wx);\n[nrow, ncol] = size(wx);\nwx_1D = func_2D_LexicoOrder(wx);\n\n% initialization\nh = zeros(size(wx));\nh_1D = func_2D_LexicoOrder(h);\np = 1./(wx.*(wx~=0)+1.*(wx==0)).*(wx~=0)+(wx==0);\np_1D = func_2D_LexicoOrder(p);\n\n%paramete setting\nalpha = 1; \nbeta = 2; \nrho = 0.1; \nw = 0.6; \nA = 5000; \nB = 10; \n\n%use one ant for each pixel position\nant_total_num = nrow*ncol;\nant_current_row = zeros(ant_total_num, 1); % record the location of ant\nant_current_col = zeros(ant_total_num, 1); % record the location of ant\nant_current_val = zeros(ant_total_num, 1); % record the location of ant\nrr = (meshgrid(1:nrow))'; cc = meshgrid(1:ncol);\nant_current_row = rr(:);\nant_current_col = cc(:);\nant_current_val = wx_1D((ant_current_row-1).*ncol+ant_current_col);\n\nant_search_range_row_min = ant_search_range_row_min(:);\nant_search_range_row_min = padarray(ant_search_range_row_min, [0 search_clique_mode-1],'replicate','post');\nant_search_range_row_max = ant_search_range_row_max(:);\nant_search_range_row_max = padarray(ant_search_range_row_max, [0 search_clique_mode-1],'replicate','post');\nant_search_range_col_min = ant_search_range_col_min(:);\nant_search_range_col_min = padarray(ant_search_range_col_min, [0 search_clique_mode-1],'replicate','post');\nant_search_range_col_max = ant_search_range_col_max(:);\nant_search_range_col_max = padarray(ant_search_range_col_max, [0 search_clique_mode-1],'replicate','post'); \n\n \nfor nIteration = 1: total_iteration_num \n\n ant_current_path_val_mean = zeros(ant_total_num,1);\n ant_current_path_val_mean = ant_current_val; \n\n for nMoveStep = 1: ant_move_step_within_iteration-1 \n\n if search_clique_mode == 4\n ant_search_range_row = [ant_current_row-1, ant_current_row, ant_current_row+1, ant_current_row];\n ant_search_range_col = [ant_current_col, ant_current_col+1, ant_current_col, ant_current_col-1]; \n elseif search_clique_mode == 8\n ant_search_range_row = [ant_current_row-1, ant_current_row-1, ant_current_row-1, ant_current_row, ant_current_row,ant_current_row+1, ant_current_row+1, ant_current_row+1];\n ant_search_range_col = [ant_current_col-1, ant_current_col, ant_current_col+1, ant_current_col-1, ant_current_col+1, ant_current_col-1, ant_current_col, ant_current_col+1];\n end\n\n ant_current_row_extend = padarray(ant_current_row, [0 search_clique_mode-1],'replicate','post');\n ant_current_col_extend = padarray(ant_current_col, [0 search_clique_mode-1],'replicate','post');\n ant_search_range_val = zeros(ant_total_num,search_clique_mode);\n\n %replace the positions our of the image's range \n temp = (ant_search_range_row>=ant_search_range_row_min) & (ant_search_range_row<=ant_search_range_row_max) & (ant_search_range_col>=ant_search_range_col_min) & (ant_search_range_col<=ant_search_range_col_max);\n ant_search_range_row = temp.*ant_search_range_row + (~temp).*ant_current_row_extend;\n ant_search_range_col = temp.*ant_search_range_col + (~temp).*ant_current_col_extend;\n\n ant_search_range_transit_prob_h = zeros(size(ant_search_range_val));\n ant_search_range_transit_prob_p = zeros(size(ant_search_range_val)); \n\n for ii=1:search_clique_mode\n ant_search_range_val(:,ii) = wx_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii));\n\n temp = ant_search_range_val(:,ii);\n temp = abs(temp - ant_current_path_val_mean); \n temp = 1./(temp.*(temp~=0)+1.*(temp==0)) .* (temp~=0)+(temp==0);\n\n ant_search_range_transit_prob_h(:,ii) = temp;\n ant_search_range_transit_prob_p(:,ii) = p_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii));\n\n end\n temp = (ant_search_range_transit_prob_h.^alpha) .* (ant_search_range_transit_prob_p.^beta);\n\n temp_sum = sum(temp,2);\n temp_sum = padarray(temp_sum, [0 search_clique_mode-1],'replicate','post');\n\n ant_search_range_transit_prob = temp ./ temp_sum;\n\n % generate a random number to determine the next position.\n rand('state', sum(100*clock));\n temp = rand(ant_total_num,1);\n temp = padarray(temp, [0 search_clique_mode-1],'replicate','post');\n temp = cumsum(ant_search_range_transit_prob,2)>=temp;\n temp = padarray(temp, [0 1],'pre');\n temp = (diff(temp,1,2)==1);\n\n temp_row = (ant_search_range_row .* temp)';\n [ii, jj, vv] = find(temp_row);\n ant_next_row = vv;\n temp_col = (ant_search_range_col .* temp)';\n [ii, jj, vv] = find(temp_col);\n ant_next_col = vv;\n\n ant_current_row = ant_next_row;\n ant_current_col = ant_next_col; \n ant_current_val = wx_1D((ant_current_row-1).*ncol+ant_current_col);\n ant_current_path_val_mean = (ant_current_path_val_mean.*nMoveStep + ant_current_val)/(nMoveStep+1);\n\n %update p;\n rr = ant_current_row;\n cc = ant_current_col;\n p_1D((rr-1).*ncol+cc,1) = w*p_1D((rr-1).*ncol+cc,1) + 1./(A+B.*ant_current_path_val_mean);\n p = func_LexicoOrder_2D(p_1D, nrow, ncol);\n\n end % end of nMoveStep\n\n p = (1-rho).*p;\n p_1D = func_2D_LexicoOrder(p);\n\nend % end of nIteration\n\nclear h h_1D temp\nclear ant_current_row ant_current_col ant_current_val\nclear ant_current_path_val_mean\nclear ant_search_range_row search_range_path_col ant_search_range_val\nclear ant_search_range_transit_prob_h ant_search_range_transit_prob_v ant_search_range_transit_prob\nclear ant_search_range_row_min ant_search_range_row_max ant_search_range_col_min ant_search_range_col_max\n\nresult = wx.^2;\n\nfor j=(J-1):-1:L\n [t1,t2] = func_dyad2HH(j);\n result(t1,t2) = func_determine_class_fcm(wx(t1,t2), p(t1,t2), win_size, noise_sigma);\n [t1,t2] = func_dyad2HL(j);\n result(t1,t2) = func_determine_class_fcm(wx(t1,t2), p(t1,t2), win_size, noise_sigma);\n [t1,t2] = func_dyad2LH(j);\n result(t1,t2) = func_determine_class_fcm(wx(t1,t2), p(t1,t2), win_size, noise_sigma);\nend \n\n% ******************************************************************************\n% **************************Inner Function *************************************\n% ******************************************************************************\n% Bi-class classification algorithm using Fuzzy C-means\nfunction result = func_determine_class_fcm(wx, p, win_size, noise_sigma)\n\np_1D = func_2D_LexicoOrder(p);\nwx_1D = func_2D_LexicoOrder(wx);\n[nrow, ncol] = size(wx);\n\nnFeature = p_1D(:)./(max(max(p_1D)));\n[center,U,obj_fcn] = fcm(nFeature, 2,[2.0 100 1e-5 0]);\n\nidx = zeros(nrow:ncol,1); \nif sum(sum(wx_1D(U(1,:) >= U(2,:)))) >= sum(sum(wx_1D(U(1,:) < U(2,:))))\n idx = U(1,:) >= U(2,:);\nelse\n idx = U(1,:) < U(2,:);\nend\nidx = func_LexicoOrder_2D(idx, nrow, ncol); \n\ncenter_class = idx(:);\npadnum = win_size;\nA = padarray(wx, [padnum padnum], 'replicate', 'bot');\nB = padarray(idx, [padnum padnum], 'replicate', 'bot');\n\nA = im2col(A, [win_size*2+1 win_size*2+1],'sliding');\nA = A.^2;\nB = im2col(B, [win_size*2+1 win_size*2+1],'sliding');\n\nC = padarray(center_class', [size(A,1)-1, 0], 'replicate', 'post');\n\nresult = sum(A,1) ./ (win_size*2+1)./(win_size*2+1);\nresult = reshape(result, [nrow, ncol]);\nresult = (result>=noise_sigma^2).*(result-noise_sigma^2);\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\n% Convert data from 2D format to 1D format\nfunction result = func_2D_LexicoOrder(x)\ntemp = x';\nresult = temp(:);\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\n% Convert data from 1D format to 2D format\nfunction result = func_LexicoOrder_2D(x, nRow, nColumn)\nresult = reshape(x, nColumn, nRow)';\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\nfunction result=min2(f)\n%calculate minimum of 2D matrix\nresult=min(min(f));\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\nfunction result=max2(f)\n%calculate maximum of 2D matrix\nresult=max(max(f));\n\n%-------------------------------------------------------------------------\n%------------------------------Inner Function ----------------------------\n%-------------------------------------------------------------------------\n% Calculate the PSNR performance to two images\nfunction result = func_psnr_gray(f, g)\n\nf = double(f);\ng = double(g);\nQ=255; MSE=0;\n[M,N]=size(f);\nh = f - g;\nMSE = sum(sum(h.*h));\nMSE=MSE/M/N;\nresult=10*log10(Q*Q/MSE);", "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/29927-antshrink-ant-colony-optimization-for-image-shrinkage/denoise_PRL_2010_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.6035489893001326}} {"text": "function im=mat2im(mat,cmap,limits)\n% mat2im - convert to rgb image\n%\n% function im=mat2im(mat,cmap,maxVal)\n%\n% PURPOSE\n% Uses vectorized code to convert matrix \"mat\" to an m-by-n-by-3\n% image matrix which can be handled by the Mathworks image-processing\n% functions. The the image is created using a specified color-map\n% and, optionally, a specified maximum value. Note that it discards\n% negative values!\n%\n% INPUTS\n% mat - an m-by-n matrix \n% cmap - an m-by-3 color-map matrix. e.g. hot(100). If the colormap has \n% few rows (e.g. less than 20 or so) then the image will appear \n% contour-like.\n% limits - by default the image is normalised to it's max and min values\n% so as to use the full dynamic range of the\n% colormap. Alternatively, it may be normalised to between\n% limits(1) and limits(2). Nan values in limits are ignored. So\n% to clip the max alone you would do, for example, [nan, 2]\n% \n%\n% OUTPUTS\n% im - an m-by-n-by-3 image matrix \n%\n%\n% Example 1 - combine multiple color maps on one figure \n% clf, colormap jet, r=rand(40);\n% subplot(1,3,1),imagesc(r), axis equal off , title('jet')\n% subplot(1,3,2),imshow(mat2im(r,hot(100))) , title('hot')\n% subplot(1,3,3),imshow(mat2im(r,summer(100))), title('summer')\n% colormap winter %changes colormap in only the first panel\n%\n% Example 2 - clipping\n% p=peaks(128); J=jet(100);\n% subplot(2,2,1), imshow(mat2im(p,J)); title('Unclipped')\n% subplot(2,2,2), imshow(mat2im(p,J,[0,nan])); title('Remove pixels <0')\n% subplot(2,2,3), imshow(mat2im(p,J,[nan,0])); title('Remove pixels >0')\n% subplot(2,2,4), imshow(mat2im(p,J,[-1,3])); title('Plot narrow pixel range')\n%\n% Rob Campbell - April 2009\n%\n% See Also: ind2rgb, imadjust\n\n\n%Check input arguments\nerror(nargchk(2,3,nargin));\n\nif ~isa(mat, 'double')\n mat = double(mat)+1; % Switch to one based indexing\n limits = limits + 1;\nend\n\nif ~isnumeric(cmap)\n error('cmap must be a colormap, such as jet(100)')\nend\n\n\n%Clip if desired\nL=length(cmap);\nif nargin==3 && length(limits)==1\n warning('limits should be vector of length of 2. Assuming a max value was specified.')\n limits=[nan,limits];\nend\n\n\nif nargin==3\n minVal=limits(1);\n if isnan(minVal), minVal=min(mat(:)); end \n mat(matmaxVal)=maxVal; \nelse\nminVal=min(mat(:));\nmaxVal=max(mat(:));\nend\n\n\n%Normalise \nmat=mat-minVal;\nmat=(mat/(maxVal-minVal))*(L-1);\nmat=mat+1;\n\n\n%convert to indecies \nmat=round(mat); \n\n\n%Vectorised way of making the image matrix \nim=reshape(cmap(mat(:),:),[size(mat),3]);\n\n", "meta": {"author": "geopavlakos", "repo": "object3d", "sha": "44033b2b4fe15d41a411cba0bbff906c23e8a802", "save_path": "github-repos/MATLAB/geopavlakos-object3d", "path": "github-repos/MATLAB/geopavlakos-object3d/object3d-44033b2b4fe15d41a411cba0bbff906c23e8a802/code/utils/mat2im.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.603447105995492}} {"text": "%This Matlab script can be used to reproduce Figure 7.20 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%% Define parameters\nM = 64; %Number of antennas\nMprime = 30; %Number of \nbeta = [0,10^(-5/10),1];\nIT = 10000;\n\n%Derived parameters\nbetad = (M-beta*Mprime)/(M-Mprime);\n\n\n%% Simulate channels\ncorrelationAA = zeros(numel(beta),IT);\ncorrelationAB = zeros(numel(beta),IT);\n\n%Go through all beta values\nfor b = 1:numel(beta)\n R_A = diag([beta(b)*ones(1,Mprime), betad(b)*ones(1,M-Mprime)]);\n R_B = diag([betad(b)*ones(1,M-Mprime), beta(b)*ones(1,Mprime)]);\n R_A2 = sqrt(R_A);\n R_B2 = sqrt(R_B);\n \n %Compute UE correlation metric in (7.22)\n for it = 1:IT\n \n hA1 = R_A2*1/sqrt(2)*(randn(M,1) + 1i*randn(M,1));\n hA2 = R_A2*1/sqrt(2)*(randn(M,1) + 1i*randn(M,1));\n hB1 = R_B2*1/sqrt(2)*(randn(M,1) + 1i*randn(M,1));\n correlationAA(b,it) = 10*log10((abs(hA1'*hA2)/(norm(hA1)*norm(hA2)))^2);\n correlationAB(b,it) = 10*log10((abs(hA1'*hB1)/(norm(hA1)*norm(hB1)))^2);\n \n end\nend\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\nnth = 1000;\nColors = {'r','b'};\nMarkers = {'square', 'o'};\n\nplot(-100,-100,'Color', 'k', 'LineStyle', '-');\nplot(-100,-100,'Color', 'k', 'LineStyle', '--');\nplot(-100,-100,'Color','k', 'LineStyle', 'none', 'Marker', '*');\nplot(-100,-100,'Color', Colors{2}, 'LineStyle', 'none', 'Marker', Markers{2});\nplot(-100,-100,'Color', Colors{1}, 'LineStyle', 'none', 'Marker', Markers{1});\n\n[y,x] = ecdf(correlationAA(end,:));\nplot(x,y,'Color','k', 'LineWidth', 1);\nplot(x(1:nth:end),y(1:nth:end),'Color','k', 'LineStyle', 'none', 'Marker', '*');\n\nfor b = 1:numel(beta)-1\n [y,x] = ecdf(correlationAA(b,:));\n plot(x,y,'Color', Colors{b}, 'LineWidth', 1);\nend\n\nfor b = 1:numel(beta)-1\n [y,x] = ecdf(correlationAB(b,:));\n plot(x,y,'--','Color', Colors{b}, 'LineWidth', 1)\nend\n\n\nfor b = 1:numel(beta)-1\n [y,x] = ecdf(correlationAA(b,:));\n plot(x(1:nth:end),y(1:nth:end),'LineStyle', 'none','Color', Colors{b}, 'LineWidth', 1, 'Marker', Markers{b});\nend\n\nfor b = 1:numel(beta)-1\n [y,x] = ecdf(correlationAB(b,:));\n plot(x(1:nth:end),y(1:nth:end),'LineStyle', 'none','Color', Colors{b}, 'LineWidth', 1, 'Marker', Markers{b})\nend\n\nxlim([-40,-10])\nlegend('Same region', 'Different regions','\\beta=1', '\\beta=-5 dB', '\\beta=0','Location','NorthWest')\nxlabel('Average UE correlation [dB]')\nylabel('CDF')\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section7_figure20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6034470887978246}} {"text": "function [out] = evap_1(S,Ep,dt)\n%evap_1 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Evaporation at the potential rate\n% Constraints: f <= S/dt\n% @(Inputs): S - current storage [mm]\n% Ep - potential evaporation rate [mm/d]\n% dt - time step size\n\nout = min(S/dt,Ep);\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/evap_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.6034281305418966}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Inverse dynamics for the 1dof planar robot\n%\n% tau = inversedynamics_1dofplanar(robot, q, qd, qdd, fext)\n% \n% Where robot stores the kinematic and dynamic parameters for this robot.\n% q: joint positions.\n% qd: joint velocities.\n% qdd: joint accelerations.\n% fext: vector of external forces. Defined in the last reference system.\n%\n% This function just executes the inverse dynamic model for this robot.\n% The equations to compute this dynamic model can be found in:\n% \"ROBOT ANALYSIS. The mechanics of Serial and Parallel\n% manipulators\". Lung Weng Tsai. John Wiley and Sons, inc. ISBN:\n% 0-471-32593-7. page 405.\n% \n% \n% Author: Arturo Gil Aparicio arturo.gil@umh.es\n% Date: 23/11/2016\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction tau = exercise_inv_dynamics_1dofplanar(robot, q, qd, qdd, g, fext)\na = eval(robot.DH.a);\na1=a(1);\n\ng=abs(g);\nm=robot.dynamics.masses(1);\n\n%In this case we must define the Inertia with respect to the rotating axis.\nJ = (1/3)*m*a1^2;\ntau = J*qdd + m*g*a1*cos(q(1))/2;\n\n\n\n\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/exercises/dynamics/solution/exercise_inv_dynamics_1dofplanar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6034281139526069}} {"text": "% pet_transmission_example.m\n% Example of reconstructing a PET attenuation map via penalized-likelihood\n% estimation from real 2D PET transmission data.\n%\n% Copyright 2002-12-19, Jeff Fessler, University of Michigan\n\n% read raw data\nif ~isvar('yi'), printm 'raw data'\n yi = ir_get_data(fullfile('pet_trans_2d_sino','phan_trans.mat'));\n bi = ir_get_data(fullfile('pet_trans_2d_sino','phan_blank.mat'));\n\tim plc 2 2, im(1, yi, 'yi: transmission scan')\n\tim(2, bi, 'bi: blank scan')\n\n\t% system model for ecat921 PET scanner geometry\n\tig = image_geom('nx', 128, 'dx', 0.421875, 'dy', 0.421875); % cm\n%\t\t'center_x', 0.5, 'center_y', -0.5, ...\n\tsg = sino_geom('par', 'nb', size(yi,1), 'na', size(yi,2), ...\n\t\t'dr', 0.3375, 'offset_r', 0.5, 'strip_width', 'dr', ...\n\t\t'orbit_start', -15);\nprompt\nend\n\n\n% FBP image\nif ~isvar('xfbp'), printm 'do FBP'\n\tkernel = gaussian_kernel(3);\n%\tkernel = [1];\n\txfbp = tr_fbp(sg, ig, max(yi,1), bi, 0*bi, 'kernel', kernel);\n% fix: correct for backproject scaling problem; probably incorrect!\n%\txfbp = xfbp * na/pi * f.pixel_size / f.ray_spacing;\n\txfbp = max(xfbp,0);\n\tim(3, xfbp, 'fbp'), cbar\n\n\tig.mask = ig.circ(26, 21, 0, 3) > 0;\n\tim(4, ig.mask+6*xfbp, 'mask check')\nprompt\nend\n\n\n% strip integral system matrix with mask for iterative reconstruction.\nif ~isvar('A2'), printm 'A2'\n\tif 0 && has_mex_jf\n\t\tA2 = Gtomo2_wtmex(sg, ig); % preferable for speed\n\telse\n\t\tA2 = Gtomo2_strip(sg, ig, 'strip_width', sg.dr); % slower but universal\n\tend\nend\n\n\nif ~isvar('Ab'), printm 'make Ab' % block system object for ordered-subsets\n\tf.nblock = 5;\n\tAb = Gblock(A2, f.nblock);\nend\n\n\nif ~isvar('R'), printm 'make R' % regularizer object\n\tf.l2b = 10.5;\n\tf.delta = 0.03;\n%\tf.pot = 'huber';\n\tf.pot = 'hyper3';\n\tR = Reg1(ig.mask, 'type_denom', 'matlab', ...\n\t\t'beta', 2^f.l2b, 'pot_arg', {f.pot, f.delta});\nend\n\n\n% matlab iterations\nif ~isvar('xmat'), printm 'matlab T-PL-OS-SPS'\n\tf.niter = 8+1;\n\tf.niter = 16+1;\n\tf.pixmax = 0.4;\n\txinit = max(xfbp,0);\n\n\txmat = tpl_os_sps(xinit(ig.mask), Ab, yi, bi, [], R, ...\n\t\tf.niter, f.pixmax, 'pc');\n\txmat = ig.embed(xmat);\n\n\tim clf, im(xmat, 'T-PL-OSPS iterations (0th is FBP)')\nprompt\nend\n\n\n% nice figure for book\nif 1\n\tim clf\n\tim(211, yi, 'sinogram yi')\n\tclim = [0 0.2];\n\tim(223, xfbp, 'FBP', clim), cbar\n\tim(224, xmat(:,:,end), 'Statistical', clim), cbar\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/pet_transmission_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6034207701682746}} {"text": "function [R, G, B] = Lab2RGB(L, a, b)\n%LAB2RGB Convert an image from CIELAB to RGB\n%\n% function [R, G, B] = Lab2RGB(L, a, b)\n% function [R, G, B] = Lab2RGB(I)\n% function I = Lab2RGB(...)\n%\n% Lab2RGB takes L, a, and b double matrices, or an M x N x 3 double\n% image, and returns an image in the RGB color space. Values for L are in\n% the range [0,100] while a* and b* are roughly in the range [-110,110].\n% If 3 outputs are specified, the values will be returned as doubles in the\n% range [0,1], otherwise the values will be uint8s in the range [0,255].\n%\n% This transform is based on ITU-R Recommendation BT.709 using the D65\n% white point reference. The error in transforming RGB -> Lab -> RGB is\n% approximately 10^-5. \n%\n% See also RGB2LAB. \n\n% By Mark Ruzon from C code by Yossi Rubner, 23 September 1997.\n% Updated for MATLAB 5 28 January 1998.\n% Fixed a bug in conversion back to uint8 9 September 1999.\n% Updated for MATLAB 7 30 March 2009.\n\nif nargin == 1\n b = L(:,:,3);\n a = L(:,:,2);\n L = L(:,:,1);\nend\n\nif max(max(L)) < 1.1 || max(max(a)) < 1.1 || max(max(b)) < 1.1\n L = double(L) * 100;\n a = double(a) * 220;\n a = a - 110;\n b = double(b) * 220;\n b = b - 110;\nend\n\n% Thresholds\nT1 = 0.008856;\nT2 = 0.206893;\n\n[M, N] = size(L);\ns = M * N;\nL = reshape(L, 1, s);\na = reshape(a, 1, s);\nb = reshape(b, 1, s);\n\n% Compute Y\nfY = ((L + 16) / 116) .^ 3;\nYT = fY > T1;\nfY = (~YT) .* (L / 903.3) + YT .* fY;\nY = fY;\n\n% Alter fY slightly for further calculations\nfY = YT .* (fY .^ (1/3)) + (~YT) .* (7.787 .* fY + 16/116);\n\n% Compute X\nfX = a / 500 + fY;\nXT = fX > T2;\nX = (XT .* (fX .^ 3) + (~XT) .* ((fX - 16/116) / 7.787));\n\n% Compute Z\nfZ = fY - b / 200;\nZT = fZ > T2;\nZ = (ZT .* (fZ .^ 3) + (~ZT) .* ((fZ - 16/116) / 7.787));\n\n% Normalize for D65 white point\nX = X * 0.950456;\nZ = Z * 1.088754;\n\n% XYZ to RGB\nMAT = [ 3.240479 -1.537150 -0.498535;\n -0.969256 1.875992 0.041556;\n 0.055648 -0.204043 1.057311];\n\nRGB = max(min(MAT * [X; Y; Z], 1), 0);\n\nR = reshape(RGB(1,:), M, N);\nG = reshape(RGB(2,:), M, N);\nB = reshape(RGB(3,:), M, N); \n\nif nargout < 2\n R = uint8(round(cat(3,R,G,B) * 255));\nend", "meta": {"author": "happynear", "repo": "DeepVisualization", "sha": "6e39593b1b4bd3087e0486da97733c1228ca7420", "save_path": "github-repos/MATLAB/happynear-DeepVisualization", "path": "github-repos/MATLAB/happynear-DeepVisualization/DeepVisualization-6e39593b1b4bd3087e0486da97733c1228ca7420/NNComplexity/Lab2RGB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6034207606037104}} {"text": "function UNew = diffusionNeumann2D(varargin);\n% diffusionNeumann2D: solve diffusion registraion in 2D with Neumann\n% boundary conditions\n%\n%\n% author: Nathan D. Cahill\n% email: nathan.cahill@rit.edu\n% affiliation: Rochester Institute of Technology\n% date: January 2014\n% licence: GNU GPL v3\n%\n% Copyright Nathan D. Cahill\n% Code available from https://github.com/tomdoel/npReg\n%\n%\n\n% parse input arguments\n[U,F,PixSize,NumPix,RegularizerFactor] = parse_inputs(varargin{:});\n\n% divide by regularizer factor\nFnew = F/RegularizerFactor;\n\n% compute dct of new force field\nFnewF1 = real(fft(real(fft(Fnew(:,:,1),2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nFnewF2 = real(fft(real(fft(Fnew(:,:,2),2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nFnewF1 = FnewF1(1:NumPix(1),1:NumPix(2));\nFnewF2 = FnewF2(1:NumPix(1),1:NumPix(2));\n\n% construct images of coordinates scaled by pi/(N or M)\n[alpha,beta] = ndgrid(pi*(0:(NumPix(1)-1))/(NumPix(1)-1),pi*(0:(NumPix(2)-1))/(NumPix(2)-1));\n\n% construct LHS factor\nLHSfactor = 2*cos(alpha) + 2*cos(beta) - 4;\n\n% set origin term to 1, as DC term does not matter\nLHSfactor(1,1) = 1;\n\n% solve for FFT of U\nUF1 = FnewF1./LHSfactor;\nUF2 = FnewF2./LHSfactor;\n\n% if gamma is zero, set DC term to 0\nUF1(1,1) = 0;\nUF2(1,1) = 0;\n\n% perform inverse dct\nU1 = real(ifft(real(ifft(UF1,2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\nU2 = real(ifft(real(ifft(UF2,2*NumPix(1)-2,1)),2*NumPix(2)-2,2));\n\n% crop and concatenate\nUNew = cat(3,U1(1:NumPix(1),1:NumPix(2)),U2(1:NumPix(1),1:NumPix(2)));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [U,F,PixSize,NumPix,RegularizerFactor] = parse_inputs(varargin);\n\n% get displacement field and check size\nU = varargin{1};\nF = varargin{2};\nPixSize = varargin{4}(1:2);\nNumPix = [varargin{5} varargin{6}];\nRegularizerFactor = varargin{10};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/npReg/npRegLib/diffusionNeumann2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6034207544506229}} {"text": "function [CC, rhs, bb, gg, Px, Py, xsplit, ysplit] = discretize(N, f, m, n, flag)\n%DISCRETIZE Given a CHEBOP2, this function converts the problem to one of the form\n%\n% sum_i kron(A_i,B_i)\n%\n% and computes the discretisation as a cell array: \n%\n% {{\n%\n% A_1 , B_1\n% A_2 , B_2\n% . , .\n% . , .\n% . , .\n% A_k , B_k\n%\n% }}\n%\n% INPUTS: \n% N = PDE (CHEBOP2). \n% f = forcing term (CHEBFUN2).\n% m = discretization size in 1st variable.\n% n = discretization size in 2nd variable.\n% flag = 0 (default) means assigned boundary conditions, flag = 1\n% means do not assign boundary conditions. \n%\n% OUTPUTS:\n% CC = cell array of matrices storing the terms in the matrix\n% equation.\n% rhs = matrix discretizing forcing term. \n% bb = cell array storing the discretized linear constraints. \n% gg = cell array storing the discretized nonhomogeneous part of the \n% constraints. \n% Px, Py = store permutation matrix to ensure bcs are linear\n% dependent.\n% XSPLIT, YSPLIT = 0 if subproblems cannot be formed. XSPLIT = 1 if\n% even and odd modes decouple in 1st variable. YSPLIT = 1 if even and\n% odd modes decouple in 2nd variable. \n%\n% Returns RHS with degrees of freedom removed and bb which stores\n% elminated boundary conditions, gg eliminated boundary rows.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse inputs.\nif nargin < 5\n flag = 0;\nend\n\n%%\n% Get information of PDE and pref.\nA = N.coeffs;\nrect = N.domain;\npref = chebfunpref();\ntol = pref.cheb2Prefs.chebfun2eps;\nxorder = N.xorder;\nyorder = N.yorder;\n\n%%\n% Check if the PDO was given as a variable coefficient PDO with the notation\n% @(x,y,u), but is actually a constant coefficient PDO. \nif ( iscell( A ) ) \n doesNotDependOnXorY = all(all(cellfun(@isnumeric, N.coeffs))); \n if ( doesNotDependOnXorY ) \n A = cell2mat( A ).'; \n end\nend\n\n%%\n% Convert matrix of coefficients to a discretization for the PDE using the\n% singular value decomposition. We find the rank of the PDE operator and\n% then use the optimal low rank expansion of the operator as a way to\n% discretise the PDE.\nif ( isempty(N.V) || isempty(N.U) )\n if ( iscell(A) )\n counter = 1;\n U = cell(size(A, 1), 1); \n V = cell(size(A, 2), 1);\n for jj = 1:size(A, 1)\n for kk = 1:size(A, 2)\n a = A{jj,kk};\n if ( isa(a, 'chebfun2') )\n if ( abs(vscale(a)) > tol )\n [C, D, R] = cdr(a);\n for col = 1:size(C, 2)\n U{jj,counter} = C(:,col)*D(col,col);\n V{kk,counter} = R(:,col);\n counter = counter + 1;\n end\n end\n elseif ( isa(a,'double') && ( isempty(a) || abs(a) > tol ) )\n U{jj,counter} = a; \n V{kk,counter} = 1;\n counter = counter + 1;\n end\n end\n end\n rk = size(U, 2);\n S = diag(ones(rk, 1));\n na = size(U, 1);\n nb = size(V, 1);\n else\n % Compute the SVD of the coefficient matrix.\n [U, S, V] = svd(A.');\n % Find the rank of A, which is also the rank of the PDE operator and\n % construct the low rank expansion for A.\n rk = find(diag(S) > tol, 1, 'last');\n U = U(:,1:rk);\n S = S(1:rk,1:rk);\n V = V(:,1:rk);\n [na, nb] = size(A.');\n end\nelse\n rk = size(N.S, 2);\n U = N.U;\n V = N.V;\n S = N.S;\n na = size(U, 1); \n nb = size(V, 1);\nend\n% LEFT = zeros(m); RIGHT = zeros(n);\n\n% Construct the discretisation in matrix equation form.\nCC = cell(rk,2);\n\nfor jj = 1 : rk\n \n RIGHT = unconstrainedMatrixEquation(V, jj, n, xorder, rect(1:2)); % jjth term on the right.\n LEFT = unconstrainedMatrixEquation(U, jj, m, yorder, rect(3:4)); % jjth term on the left.\n \n % Balance out the scaling from the singular value. This does slightly\n % improve the accuracy.\n singvalue = sqrt(S(jj,jj));\n CC{jj,2} = singvalue * RIGHT;\n CC{jj,1} = singvalue * LEFT;\n \nend\n\n%%\n% Test to see if we can solve subproblems. This checks if the PDE operator\n% contains differential terms of the same parity.\nysplit = 0; xsplit=0;\nif ~iscell(U) && ~iscell(V)\n emask = 1:2:na;\n omask = 2:2:na;\n if ( min( norm(U(emask,:)), norm(U(omask,:)) ) < 10*tol )\n ysplit = 1;\n end\n emask = 1:2:nb;\n omask = 2:2:nb;\n if ( min( norm(V(emask,:)), norm(V(omask,:)) ) < 10*tol )\n xsplit = 1;\n end\nend\n\n%%\n% We have a discretisation for the PDE operator, now let's find a\n% discretisation for the boundary conditions.\n\n% If no boundary conditions is prescribed then make it empty.\nbcLeft = []; \nleftVal = [];\nbcRight = []; \nrightVal = [];\nbcUp = []; \nupVal = [];\nbcDown = []; \ndownVal = [];\n\nif ( ~isempty(N.lbc) ) % Left boundary conditions.\n [bcLeft, leftVal] = chebop2.constructBC(N.lbc, -1, m, n, rect(3:4), rect(1:2), xorder);\nend\nif ( ~isempty(N.rbc) ) % Right boundary conditions.\n [bcRight, rightVal] = chebop2.constructBC(N.rbc, 1, m, n, rect(3:4), rect(1:2), xorder);\nend\nif ( ~isempty(N.ubc) ) % Top boundary conditions.\n [bcUp, upVal] = chebop2.constructBC(N.ubc, 1, n, m, rect(1:2), rect(3:4), yorder);\nend\nif ( ~isempty(N.dbc) ) % Bottom boundary conditions.\n [bcDown, downVal] = chebop2.constructBC(N.dbc, -1, n, m, rect(1:2), rect(3:4), yorder);\nend\n\n%%\n\n% For the down and up BCs we have B^TX = g^T.\nBy = [ bcUp.'; bcDown.' ];\nGy = [ upVal.'; downVal.' ];\n[By, Gy, Py] = canonicalBC(By, Gy);\n\n% For the left and right BCs we have X*B = g. We do the LU to B^T.\nBx = [ bcLeft.'; bcRight.' ];\nGx = [ leftVal.'; rightVal.' ];\n[Bx, Gx, Px] = canonicalBC(Bx, Gx);\nBx = Bx.';\nGx = Gx.'; % Now transpose so that X*B = g;\n\n%% \n% Construct the RHS of the Sylvester matrix equation.\n\n% Complete the RHS (part of the RHS could have been in the operator): \nif ( ~isempty(N.rhs) && ( isa(N.rhs, 'chebfun2') || isa(N.rhs, 'double') ) )\n f = f + N.rhs; \nend\nE = zeros(m, n);\n[n2, n1] = length(f);\nF = chebcoeffs2(f);\n\n% Map the RHS to the right ultraspherical space.\nlmap = ultraS.convertmat(n1, 0, yorder-1);\nrmap = ultraS.convertmat(n2, 0, xorder-1);\nF = lmap * F * rmap.';\n\n% Place those coefficients of the forcing function onto the RHS.\nn1 = min(n1, m); \nn2 = min(n2, n); \nE(1:n1,1:n2) = F(1:n1,1:n2);\n\nif ( ~flag ) % Impose boundary conditions.\n \n % Use the eliminated boundary condition to place zeros in the columns of\n % the matrix equation discretization. There are rk columns to zero out.\n \n for jj = 1:rk % For term in the matrix equation.\n [C, E] = zeroDOF(CC{jj,1}, CC{jj,2}, E, By, Gy);\n CC{jj,1} = C;\n [C, E] = zeroDOF(CC{jj,2}, CC{jj,1}, E.', Bx.', Gx.');\n CC{jj,2} = C; \n E = E.';\n end\n \n % Remove degrees of freedom.\n nn = n - max(xorder, yorder);\n mm = m - max(xorder, yorder);\n df1 = max(0, xorder - yorder);\n df2 = max(0, yorder - xorder);\n for jj = 1:rk\n CC{jj,1} = CC{jj,1}(1:mm, yorder+1:m-df1);\n CC{jj,2} = CC{jj,2}(1:nn, xorder+1:n-df2);\n end\n % Truncation of righthand side.\n rhs = E(1:mm, 1:nn);\n \nelse\n rhs = E;\nend\n\n% Pass back the eliminated boundary conditions.\nbb = {bcLeft bcRight bcUp bcDown};\ngg = {leftVal rightVal upVal downVal};\n\n%% \n% Check boundary continunity conditions.\n\n% Check BCs at corners:\nallbc = 0;\nif ( ~isempty(bcUp) && ~isempty(upVal) && ~isempty(bcRight) && ~isempty(rightVal) )\n if ( norm(rightVal(end-4:end),inf) < sqrt(tol) && norm(upVal(end-4:end),inf) < sqrt(tol) )\n allbc = allbc + norm(upVal.'*bcRight - bcUp.'*rightVal);\n end\nend\nif ( ~isempty(bcUp) && ~isempty(upVal) && ~isempty(bcLeft) && ~isempty(leftVal) )\n if ( norm(leftVal(end-4:end),inf) < sqrt(tol) && norm(upVal(end-4:end),inf) < sqrt(tol) )\n allbc = allbc + norm(upVal.'*bcLeft - bcUp.'*leftVal);\n end\nend\nif ( ~isempty(bcDown) && ~isempty(downVal) && ~isempty(bcRight) && ~isempty(rightVal) )\n if ( norm(rightVal(end-4:end),inf) < sqrt(tol) && norm(downVal(end-4:end),inf) < sqrt(tol) )\n allbc = allbc + norm(downVal.'*bcRight - bcDown.'*rightVal);\n end\nend\nif ( ~isempty(bcDown) && ~isempty(downVal) && ~isempty(bcLeft) && ~isempty(leftVal) )\n if ( norm(leftVal(end-4:end),inf)= 100*sqrt(tol)\n% s = sprintf('Boundary conditions differ by %1.4f', allbc');\n% warning('CHEBFUN:CHEBOP2:discretize:BCs', s)\n% end\n\nend\n\nfunction B = unconstrainedMatrixEquation(ODE, jj, n, order, dom)\n% Construct the unconstrained Matix Equation. Adding in the constraints later.\n\nB = spalloc(n, n, 3*n);\nfor kk = 1:size(ODE, 1)\n \n % Get conversion and differentiation matrices: \n S = ultraS.convertmat(n, kk-1, order-1);\n D = ((2./diff(dom))^(kk-1)) * ultraS.diffmat(n, kk-1);\n \n if ( iscell(ODE(kk,jj)) && isa(ODE{kk,jj}, 'chebfun') )\n % Variable coefficient term: \n c = ODE{kk,jj}.coeffs; \n M = ultraS.multmat(n, c, kk-1); \n A = S * M * D;\n \n elseif ( iscell(ODE(kk,jj)) && ~isempty(ODE{kk,jj}) )\n % Constant coefficient term in a variable coefficient ODE:\n A = ODE{kk,jj}.* S * D;\n \n elseif ( isa(ODE(kk,jj),'double') )\n % Constant coefficient term in a constant coefficient ODE:\n A = ODE(kk,jj).* S * D;\n \n else\n % Empty cell in array, so no term: \n A = zeros(n);\n \n end\n \n % Form the ODE operator: \n B = B + A;\n \nend\n\nend\n\nfunction [B, G, P] = canonicalBC(B, G)\n%CANONICALBC Form a linear combintation of the boundary conditions \n%so that they can be used for imposing on the PDE. \n\nP = nonsingularPermute(B);\nB = B*P;\n[L, B] = lu(B); \nG = L \\ G;\n\n% Scale so that B is unit upper triangular.\nif ( min(size(B)) > 1 )\n D = diag(1./diag(B));\nelseif ( ~isempty(B) )\n D = 1./B(1,1);\nelse\n D = []; % No boundary conditions.\nend\nB = D*B; \nG = D*G;\n\nend\n\nfunction P = nonsingularPermute(B)\n%NONSINGULARPERMUTE Permute the columns of B to ensure that the principal\n%m*m submatrix of B is nonsingular, where m = size(B, 1).\n%\n% Note: This is needed for solving the matrix equations with linear\n% constraints, see DPhil thesis of Alex Townsend (section 6.5).\n\nm = size(B, 1);\nk = 1;\n\n% [TODO]: improve this check.\n% Try each mxm block in a linear fashion: \nwhile ( rank(B(:,k:m+k-1)) < m )\n k = k+1;\n if ( m+k > size(B, 2) )\n error('CHEBFUN:CHEBOP2:discretize:nonsingularPermute:BCs', ...\n 'Boundary conditions are linearly dependent.');\n end\nend\n\nP = speye(size(B, 2));\nP = P(:,[k:m+k-1, 1:k-1, m+k:end]);\n\nend\n\nfunction [C1, E] = zeroDOF(C1, C2, E, B, G)\n%ZERODOF Eliminate so degrees of freedom in the matrix equation can be\n%removed.\n\nfor ii = 1:size(B, 1) % For each boundary condition, zero a column.\n for kk = 1:size(C1, 1)\n if ( abs(C1(kk,ii)) > 10*eps )\n c = C1(kk, ii); % Constant required to zero entry out.\n C1(kk,:) = C1(kk,:) - c*B(ii,:);\n E(kk,:) = E(kk,:) - c*G(ii,:)*C2.';\n end\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/@chebop2/discretize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6034207503537433}} {"text": "function [ xmin, xmax ] = r8_gaml ( )\n\n%*****************************************************************************80\n%\n%% R8_GAML evaluates bounds for an R8 argument of the gamma function.\n%\n% Discussion:\n%\n% This function calculates the minimum and maximum legal bounds\n% for X in the evaluation of GAMMA ( X ).\n%\n% XMIN and XMAX are not the only bounds, but they are the only\n% non-trivial ones to calculate.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Output, real XMIN, XMAX, the bounds.\n%\n alnsml = log ( r8_mach ( 1 ) );\n xmin = - alnsml;\n\n for i = 1 : 10\n\n xold = xmin;\n xln = log ( xmin );\n xmin = xmin - xmin * ( ( xmin + 0.5 ) * xln - xmin ...\n - 0.2258 + alnsml ) / ( xmin * xln + 0.5 );\n\n if ( abs ( xmin - xold ) < 0.005 )\n\n xmin = - xmin + 0.01;\n\n alnbig = log ( r8_mach ( 2 ) );\n xmax = alnbig;\n\n for j = 1 : 10\n\n xold = xmax;\n xln = log ( xmax );\n xmax = xmax - xmax * ( ( xmax - 0.5 ) * xln - xmax ...\n + 0.9189 - alnbig ) / ( xmax * xln - 0.5 );\n\n if ( abs ( xmax - xold ) < 0.005 )\n xmax = xmax - 0.01;\n xmin = max ( xmin, - xmax + 1.0 );\n return\n end\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAML - Fatal error!\\n' );\n fprintf ( 1, ' Unable to find XMAX.\\n' );\n error ( 'R8_GAML - Fatal error!' )\n\n end\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAML - Fatal error!\\n' );\n fprintf ( 1, ' Unable to find XMIN.\\n' );\n\n error ( 'R8_GAML - Fatal error!' )\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_gaml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6034141830471138}} {"text": " function sino = fbp2_sino_weight(sg, sino, varargin)\n%|function sino = fbp2_sino_weight(sg, sino, varargin)\n%|\n%| Apply sinogram weighting for first step of 2D fan-beam FBP.\n%| This matlab version is the backup alternative for users lacking mex routine.\n%|\n%| in\n%|\tsg\t\t\tsino_geom()\n%|\tig\t\t\timage_geom()\n%|\tsino\t[nb,na,(L)]\tfan-beam sinogram(s) (line integrals)\n%| out\n%|\tsino\t[nb,na,(L)]\tweighted sinogram\n%|\n%| Copyright 2006-4-19 by Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(sg, 'test'), fbp2_sino_weight_test, return, end\nif nargin < 2, ir_usage, end\n\narg.chat = 0;\narg = vararg_pair(arg, varargin);\n\nidim = size(sino);\nsino = reshape(sino, idim(1), idim(2), []); % [nb,na,*L]\nsino = fbp2_sino_weight_do(sino, sg);\nsino = reshape(sino, idim); % [nb,na,(L)]\n\n\n%\n% fbp2_sino_weight_do()\n%\nfunction sino = fbp2_sino_weight_do(sino, sg)\n\nif isinf(sg.dfs)\n\tsino = fbp2_sino_weight_flat(sino, ...\n\t\tsg.s, sg.dsd, sg.dso, sg.source_offset);\nelseif sg.dfs == 0\n\tsino = fbp2_sino_weight_arc(sino, ...\n\t\tsg.s, sg.dsd, sg.dso, sg.source_offset);\nelse\n\terror 'only flat and arc done'\nend\n\n\n%\n% fbp2_sino_weight_arc()\n%\nfunction sino = fbp2_sino_weight_arc(sino, ss, dsd, dso, source_offset);\nna = size(sino,2);\nnz = size(sino,3);\ngam = ss / dsd;\nw1 = abs(dso * cos(gam) - source_offset * sin(gam)) / dsd; % 1D weighting\nsino = sino .* repmat(w1, [1 na nz]);\n\n\n%\n% fbp2_sino_weight_flat()\n%\nfunction sino = fbp2_sino_weight_flat(sino, ss, dsd, dso, source_offset);\nna = size(sino,2);\nnz = size(sino,3);\ngam = atan(ss / dsd);\nw1 = abs(dso * cos(gam) - source_offset * sin(gam)) / dsd; % 1D weighting\nsino = sino .* repmat(w1, [1 na nz]);\n\n\n%\n% fbp2_sino_weight_test()\n%\nfunction fbp2_sino_weight_test\nsg = sino_geom('ge1', 'down', 4);\nsino = sg.ones;\ns1 = fbp2_sino_weight(sg, sino);\n\nim pl 1 2\nim(1, s1), cbar\n%max_percent_diff(s1,s2)\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/fbp2_sino_weight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6032765637137084}} {"text": "function pos2 = aberat (pos1, ve, tlight)\n\n% this function corrects position vector for aberration of light.\n% algorithm includes relativistic terms. adapted from murray (1981)\n% mon. notices royal ast. society 195, 639-648.\n\n% input\n\n% pos1 = position vector of observed object, with reespect to\n% origin at observer (or the geocenter), components in au\n\n% ve = velocity vector of observer (or the geocenter),\n% with respect to origin at solar system barycenter,\n% components in au/day (in)\n\n% tlight = light time from body to observer (or the geocenter) in days\n\n% output\n\n% pos2 = position vector of observed object, with respect to\n% origin at observer (or the geocenter), corrected\n% for aberration, components in au\n\n% ported from NOVAS 3.1\n\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% light-time for one astronomical unit in seconds, from de-405\n\nausec = 499.0047838061d0;\n\n% speed of light in au/day\n\nc = 86400.0d0 / ausec;\n\ntl = tlight;\n\np1mag = tl * c;\n\nif (tl == 0.0d0)\n\n p1mag = sqrt(pos1(1)^2 + pos1(2)^2 + pos1(3)^2);\n\n tl = p1mag / c;\nend\n\nvemag = sqrt(ve(1)^2 + ve(2)^2 + ve(3)^2);\n\nbeta = vemag / c;\n\nrdotv = pos1(1) * ve(1) + pos1(2) * ve(2) + pos1(3) * ve(3);\n\ncosd = rdotv / (p1mag * vemag);\n\ngammai = sqrt(1.0d0 - beta^2);\n\np = beta * cosd;\n\nq = (1.0d0 + p / (1.0d0 + gammai)) * tl;\n\nr = 1.0d0 + p;\n\nfor j = 1:1:3\n\n pos2(j) = (gammai * pos1(j) + q * ve(j)) / r;\n\nend\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/novas/aberat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.6032574205101884}} {"text": "%IMM_FILTER Interacting Multiple Model (IMM) Filter prediction and update steps\n%\n% Syntax:\n% [X_i,P_i,MU,X,P] = IMM_FILTER(X_ip,P_ip,MU_ip,p_ij,ind,dims,A,Q,Y,H,R)\n%\n% In:\n% X_ip - Cell array containing N^j x 1 mean state estimate vector for\n% each model j after update step of previous time step\n% P_ip - Cell array containing N^j x N^j state covariance matrix for \n% each model j after update step of previous time step\n% MU_ip - Vector containing the model probabilities at previous time step\n% p_ij - Model transition matrix\n% ind - Indices of state components for each model as a cell array\n% dims - Total number of different state components in the combined system\n% A - State transition matrices for each model as a cell array.\n% Q - Process noise matrices for each model as a cell array.\n% Y - Dx1 measurement vector.\n% H - Measurement matrices for each model as a cell array.\n% R - Measurement noise covariances for each model as a cell array.\n%\n%\n% Out:\n% X_p - Updated state mean for each model as a cell array\n% P_p - Updated state covariance for each model as a cell array\n% MU - Model probabilities as vector\n% X - Combined state mean estimate\n% P - Combined state covariance estimate\n% \n% Description:\n% IMM filter prediction and update steps. Use this instead\n% of separate prediction and update functions, if you don't need\n% the prediction estimates.\n%\n% See also:\n% IMM_UPDATE, IMM_SMOOTH, IMM_FILTER\n\n% History:\n% 01.11.2007 JH The first official version.\n%\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% $Id: imm_update.m 111 2007-11-01 12:09:23Z jmjharti $\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nfunction [X_i,P_i,MU,X,P] = imm_filter(X_ip,P_ip,MU_ip,p_ij,ind,dims,A,Q,Y,H,R)\n % Number of models\n m = length(X_ip);\n\n % Default values for state mean and covariance\n MM_def = zeros(dims,1);\n PP_def = diag(20*ones(dims,1));\n\n % Normalizing factors for mixing probabilities\n c_j = zeros(1,m);\n for j = 1:m\n for i = 1:m\n c_j(j) = c_j(j) + p_ij(i,j).*MU_ip(i);\n end\n end\n \n % Mixing probabilities\n MU_ij = zeros(m,m);\n for i = 1:m\n for j = 1:m\n MU_ij(i,j) = p_ij(i,j) * MU_ip(i) / c_j(j);\n end\n end\n \n % Calculate the mixed state mean for each filter \n X_0j = cell(1,m);\n for j = 1:m\n X_0j{j} = zeros(dims,1);\n for i = 1:m\n X_0j{j}(ind{i}) = X_0j{j}(ind{i}) + X_ip{i}*MU_ij(i,j);\n end\n end\n \n % Calculate the mixed state covariance for each filter \n P_0j = cell(1,m);\n for j = 1:m\n P_0j{j} = zeros(dims,dims);\n for i = 1:m\n P_0j{j}(ind{i},ind{i}) = P_0j{j}(ind{i},ind{i}) + MU_ij(i,j)*(P_ip{i} + (X_ip{i}-X_0j{j}(ind{i}))*(X_ip{i}-X_0j{j}(ind{i}))');\n end\n end\n\n % Space for estimates\n X_p = cell(1,m);\n P_p = cell(1,m);\n X_i = cell(1,m);\n P_i = cell(1,m);\n lambda = zeros(1,m);\n\n % Filter the estimates for each model\n for i = 1:m\n % Predict the estimates\n [X_p{i}, P_p{i}] = kf_predict(X_0j{i}(ind{i}),P_0j{i}(ind{i},ind{i}),A{i},Q{i});\n % Update the estimates\n [X_i{i}, P_i{i}, K, IM, IS] = kf_update(X_p{i},P_p{i},Y,H{i},R{i});\n \n % Calculate likelihoods\n lambda(i) = kf_lhood(X_p{i},P_p{i},Y,H{i},R{i});\n end\n \n % Calculate the model probabilities \n MU = zeros(1,m); \n c = sum(lambda.*c_j);\n MU = c_j.*lambda/c;\n\n \n % Output the combined updated state mean and covariance, if wanted.\n if nargout > 3\n % Space for estimates \n X = zeros(dims,1);\n P = zeros(dims,dims);\n % Updated state mean \n for i = 1:m\n X(ind{i}) = X(ind{i}) + MU(i)*X_i{i};\n end\n % Updated state covariance\n for i = 1:m\n P(ind{i},ind{i}) = P(ind{i},ind{i}) + MU(i)*(P_i{i} + (X_i{i}-X(ind{i}))*(X_i{i}-X(ind{i}))');\n end\n end\n ", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/imm_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.6031307033370572}} {"text": "function dx = dynamics(x,u,p)\n% dx = dynamics(x,u,p)\n%\n% Computes the dynamics for the simple pendulum\n%\n\nq = x(1,:);\ndq = x(2,:);\n\nk = p.k; c = p.c;\nddq = -c*dq - k*sin(q) + u;\ndx = [dq;ddq];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/simplePendulum/dynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6030502516895857}} {"text": "function [r,u,t,p] = macroproperties1d(n,j_x,E,nx,nv,theta)\n%% Recover Macroscopic Properties\n% compute back, fugacity, macroscopic velocities, temperature and pressure.\n % Computing first velocite,s from the momentum:\n u = j_x./n; \n \n% to compute fugacity, temperature and pressure, we need to rely on the\n% distribution fucntion that we where are using: MB, FD, BE.\n\nswitch theta\n case{-1} % BE\n % If BE: we apply bisection method to the approx BE distribution Eq.\n r_a = 0.001; r_b = 0.99; tol = 1e-7;\n for i = 1:nx\n psi = @(r_x) 2*E(i)- BE(r_x,1.5)*(n(i)/BE(r_x,0.5))^3/(2*pi) ...\n - n(i)*(u(i)^2);\n r_p = bisection(psi,r_a,r_b,tol);\n r(i) = r_p;\n t(i) = n(i)^2/(pi*(BE(r_p,0.5))^2);\n p(i) = E(i) - 1/2*n(i)*(u(i)^2);\n end\n \n \n case{1} % FD\n % if FD: we apply bisection method to the approx FD distribution Eq.\n r_a = 0.001; r_b = 0.99; tol = 1e-7;\n for i = 1:nx\n psi = @(r_x) 2*E(i)- FD(r_x,1.5)*(n(i)/FD(r_x,0.5))^3/(2*pi) ...\n - n(i)*(u(i)^2);\n r_p = bisection(psi,r_a,r_b,tol);\n r(i) = r_p;\n t(i) = n(i)^2/(pi*(FD(r_p,0.5))^2);\n p(i) = E(i) - 1/2*n(i)*(u(i)^2);\n end \n \n case{0} % MB\n % IF MB: the task is much simple.\n t = 4*E./n - 2*u.^2;\n r = n./sqrt(pi.*t);\n p = E - 1/2.*n.*u.^2;\n otherwise \n error('theta can only be: -1, 0, +1 ');\nend\n\n% Using Discrete Ordinate Method:\n% r = repmat(r,nv,1); u = repmat(u,nv,1);\n% t = repmat(t,nv,1); p = repmat(p,nv,1);\n% n = repmat(n,nv,1);", "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/BufferProblem/test/2013.1.21/macroproperties1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.6030203100759148}} {"text": "function loglik = compute_log_lik(P, S_bar, V, E_z, E_zz, RO, Tr, sigma_sq)\n\n[K, T] = size(E_z);\nJ = size(S_bar, 2);\n\nM_t = zeros(2*J, K);\n\nloglik = - 0.5*T * (2*J*log(sigma_sq));\nfor t = 1:T, \n R_t = RO{t};\n \n Sdef = S_bar;\n for kk = 1:K,\n Sdef = Sdef + E_z(kk,t)*V((kk-1)*3+[1:3],:);\n \n M_t(1:J, kk) = (R_t(1,:)*V((kk-1)*3+[1:3],:))'; \n M_t(J+1:end, kk) = (R_t(2,:)*V((kk-1)*3+[1:3], :))';\n end;\n \n invSigmaSq_p = eye(2*J)./sigma_sq;\n \n f_bar_t = R_t(1:2,:)*S_bar;\n f_bar_t = [f_bar_t(1,:) f_bar_t(2,:)]';\n \n f_t = [P(t, :) P(t+T, :)]';\n t_vect_t = [Tr(t,1)*ones(J,1); Tr(t,2)*ones(J,1)];\n \n covZ_t = E_zz((t-1)*K+1:t*K,:) - E_z(:,t)*E_z(:,t)'; \n loglik = loglik - 0.5*(((f_t-f_bar_t-t_vect_t)./sigma_sq)'*(f_t-f_bar_t-t_vect_t)) + (((f_t-f_bar_t-t_vect_t)'./sigma_sq)*M_t*E_z(:,t)) ...\n - 0.5*trace(((M_t./sigma_sq)'*M_t) * E_zz((t-1)*K+1:t*K,:)) - 0.5*log(det(covZ_t));\nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/pdm_generation/nrsfm-em/compute_log_lik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.6030202948248196}} {"text": "% Data file PILZ1\n% Forced damped vibrations of a mechanical\n% system with one degree of freedom, contained\n% a reverse pendulum.\n Ek = '3.6666*qt^2'; % Kinetic energy\n N = '(10*sin(p*t)-c*q-k*qt+19.62*sin(10*q))*qt'; % power\n Tend = 10; % upper bound of integration\n q0 = '0.1'; % initial coordinate\n qt0 = '0'; % initial velocity\n eps = 1e-10; % desirable accuracy\n np = 3; % number of parameters\n P{1} = 'c'; % spring stiffness\n P{2} = 'k'; % coefficient of damping\n P{3} = 'p'; % disturbance frequency", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/DATA Files/PILZ1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.603012219374597}} {"text": "function [relaxRxnBool, solutionRelax] = minCardinalityConservationRelaxationVector(S, param, printLevel)\n% DC programming for solving the cardinality optimization problem\n%\n% .. math::\n%\n% min ~& \\lambda ||x||_0 \\\\\n% s.t. ~& x + S^T z = 0 \\\\\n% ~& -\\infty \\leq x \\leq \\infty, \\\\\n% ~& 1 \\leq z \\leq 1 / \\epsilon\n%\n% USAGE:\n%\n% [relaxRxnBool, solutionRelax] = minCardinalityConservationRelaxationVector(S, param, printLevel)\n%\n% INPUT:\n% S: `m` x `n` stoichiometric matrix\n%\n% OPTIONAL INPUTS:\n% param: structure with:\n%\n% * param.epsilon - (getCobraSolverParams('LP', 'feasTol')*100) 1/epsilon is the largest flux expected\n% * param.eta - (`feasTol` * 100), cutoff for mass leak/siphon\n% * param.nonRelaxBool - (false(n, 1)), `n` x 1 boolean vector for reactions not to relax\n% printLevel: verbose level\n%\n% OUTPUTS:\n% relaxRxnBool: `n` x 1 boolean vector where true correspond to relaxation\n% solutionRelax: structure with:\n%\n% * solutionRelax.stat - solution status\n% * solutionRelax.x - `n` x 1 vector where nonzeros>eta correspond to relaxations\n% * solutionRelax.z - `m` x 1 vector where positives correspond to molecular mass\n\n[mlt,nlt]=size(S');\n\nif ~exist('param','var') || isempty(param)\n param.epsilon=getCobraSolverParams('LP', 'feasTol')*100;\n feasTol = getCobraSolverParams('LP', 'feasTol');\n param.eta=feasTol*100;\n param.nonRelaxBool=false(mlt,1);\n param.checkConsistency=0;\nelse\n if ~isfield(param,'epsilon')\n param.epsilon=getCobraSolverParams('LP', 'feasTol')*100;\n end\n if ~isfield(param,'eta')\n feasTol = getCobraSolverParams('LP', 'feasTol');\n param.eta=feasTol*100;\n end\n if ~isfield(param,'nonRelaxBool')\n param.nonRelaxBool=false(mlt,1);\n end\n if ~isfield(param,'checkConsistency')\n param.checkConsistency=1;\n end\nend\n\nif ~exist('printLevel','var') \n printLevel =0;\nend\n\nif param.checkConsistency\n % Check the stoichiometric consistency of the network without relaxation by\n % solving the following linear problem\n % min sum(m_i)\n % s.t S'*m = 0\n % m >= 1\n % where l is is a mx1 vector of the molecular mass of m molecular species\n cardProblem.A=S';\n cardProblem.b=zeros(size(cardProblem.A,1),1);\n cardProblem.lb=ones(size(cardProblem.A,2),1);\n cardProblem.ub=inf*ones(size(cardProblem.A,2),1);\n cardProblem.c=1*ones(size(cardProblem.A,2),1);\n cardProblem.osense=1;\n cardProblem.csense(1:size(cardProblem.A,1),1)='E';\n \n solutionRelax = solveCobraLP(cardProblem,'printLevel',printLevel);\n if solutionRelax.stat==1\n solutionRelax.z = solutionRelax.full;\n solutionRelax.x = S'*solutionRelax.z;\n end\n done=1;\nelse\n done=0;\nend\n\n%relaxation problem\nif done==0\n cardProblem.p=mlt;\n cardProblem.q=0;\n cardProblem.r=nlt;\n cardProblem.c=zeros(nlt+mlt,1);\n if 1\n cardProblem.A=[speye(mlt,mlt),S'];\n else\n cardProblem.A=[sparse(mlt,mlt),S'];\n end\n cardProblem.b=zeros(mlt,1);\n cardProblem.lb=[-inf*ones(mlt,1);ones(nlt,1)];\n %cardProblem.lb=[zeros(mlt,1);epsilon*ones(nlt,1)];\n cardProblem.ub=[inf*ones(nlt,1);(1/param.epsilon)*ones(mlt,1)];\n %omits flux from this reaction - perhaps not a good way to do it.\n if any(param.nonRelaxBool)\n %prevent relaxation of specified reactions\n cardProblem.lb([param.nonRelaxBool;false(mlt,1)])=0;\n cardProblem.ub([param.nonRelaxBool;false(mlt,1)])=0;\n end\n cardProblem.csense(1:mlt,1)='E';\n cardProblem.lambda0=1;\n cardProblem.lambda1=getCobraSolverParams('LP', 'feasTol')*100;% sensitive to this value, 1e-4 works for Recon3Model.\n cardProblem.delta=0;\n solutionRelax = optimizeCardinality(cardProblem,param);\n % problem Structure containing the following fields describing the problem\n % p size of vector x\n % q size of vector y\n % r size of vector z\n % c (p+q+r) x 1 linear objective function vector\n % lambda trade-off parameter of ||x||_0\n % delta trade-off parameter of ||y||_0\n % A s x (p+q+r) LHS matrix\n % b s x 1 RHS vector\n % csense s x 1 Constraint senses, a string containting the constraint sense for\n % each row in A ('E', equality, 'G' greater than, 'L' less than).\n % lb (p+q+r) x 1 Lower bound vector\n % ub (p+q+r) x 1 Upper bound vector\n %\n % OPTIONAL INPUTS\n % param parameters structure\n % nbMaxIteration stopping criteria - number maximal of iteration (Defaut value = 1000)\n % epsilon stopping criteria - (Defaut value = 10e-6)\n % theta parameter of the approximation (Defaut value = 2)\n %\n % OUTPUT\n % solution Structure containing the following fields\n % x p x 1 solution vector\n % y q x 1 solution vector\n % z r x 1 solution vector\n % stat status\n % 1 = Solution found\n % 2 = Unbounded\n % 0 = Infeasible\n % -1= Invalid input\nend\n\n%check optimality\nif printLevel>2\n fprintf('%g%s\\n',norm(solutionRelax.x + S'*solutionRelax.z),' = ||x + S''*z||')\n fprintf('%g%s\\n',min(solutionRelax.z),' = min(z_i)')\n fprintf('%g%s\\n',max(solutionRelax.z),' = min(z_i)')\n fprintf('%g%s\\n',min(solutionRelax.x),' = min(x_i)')\n fprintf('%g%s\\n',max(solutionRelax.x),' = max(x_i)')\nend\n\nif solutionRelax.stat==1\n %conserved if relaxation is below epsilon\n relaxRxnBool=abs(solutionRelax.x)>=param.eta;\n if printLevel>1\n fprintf('%g%s\\n',norm(S(:,~relaxRxnBool)'*solutionRelax.z),' = ||N''*z|| (should be zero)')\n end\n if printLevel>1\n fprintf('%s\\n',[int2str(nnz(relaxRxnBool)) '/' int2str(length(relaxRxnBool)) ' reactions relaxed.'])\n end\nelse\n disp(solutionRelax)\n error('solve for minimum cardinality of conservation relaxation vector failed')\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/reconstruction/modelGeneration/stoichConsistency/minCardinalityConservationRelaxationVector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6030122138510156}} {"text": "function [N,E] = rentian_scaling(A,XYZ,n)\n%RENTIAN_SCALING Physical Rentian scaling\n%\n% [N E] = rentian_scaling(A,XYZ,n)\n%\n% Physical Rentian scaling (or more simply Rentian scaling) is a property \n% of systems that are cost-efficiently embedded into physical space. It is \n% what is called a \"topo-physical\" property because it combines information \n% regarding the topological organization of the graph with information \n% about the physical placement of connections. Rentian scaling is present \n% in very large scale integrated circuits, the C. elegans neuronal network, \n% and morphometric and diffusion-based graphs of human anatomical networks.\n% Rentian scaling is determined by partitioning the system into cubes, \n% counting the number of nodes inside of each cube (N), and the number of \n% edges traversing the boundary of each cube (E). If the system displays \n% Rentian scaling, these two variables N and E will scale with one another \n% in loglog space. The Rent's exponent is given by the slope of log10(E) \n% vs. log10(N), and can be reported alone or can be compared to the \n% theoretical minimum Rent's exponent to determine how cost efficiently the \n% network has been embedded into physical space. Note: if a system displays \n% Rentian scaling, it does not automatically mean that the system is \n% cost-efficiently embedded (although it does suggest that). Validation \n% occurs when comparing to the theoretical minimum Rent's exponent for that\n% system.\n%\n% Inputs:\n% \tA MxM adjacency matrix \n% must be unweighted, binary, and symmetric.\n% \tXYZ Vector of node placement coordinates\n% must be Mx3 matrix, where M is the number of nodes.\n% \tn Number of partitions to compute. Each partition is a data\n% point. You want a large enough number to adequately estimate\n% the Rent's exponent.\n%\n% Outputs:\n%\tN nx1 vector of the number of nodes in each of the n partitions.\n%\tE nx1 vector of the number of edges crossing the boundary of each\n% partition.\n%\n% Subsequent Analysis:\n% Rentian scaling plots are then created by: figure; loglog(E,N,'*');\n%\n%\tTo determine the Rent's exponent, p, it is important not to use\n%\tpartitions which may be affected by boundary conditions. In Bassett et\n%\tal. 2010 PLoS CB, only partitions with Nrandx(1) & XYZn(:,1)randx(1) & XYZn(:,2)randx(1) & XYZn(:,3).\nfunction robot = parameters()\n\nrobot.name='Example 2DOF planar arm';\n\n%kinematic data DH parameters\nrobot.DH.theta='[q(1) q(2)]';\nrobot.DH.d='[0 0]';\nrobot.DH.a='[1 1]';\nrobot.DH.alpha='[0 0]';\n\n%number of degrees of freedom\nrobot.DOF = 2;\n\n%rotational: R, translational: T\nrobot.kind=['R' 'R'];\n\n%Jacobian matrix. It is easy to obtain the Jacobian matrix of this robot\n% J is defined such that:\n% v=[vn wn]', where vn is the linear speed of the end effector and wn in\n% the angular speed. vn=[vx vy vz] and wn = [wx wy wz]. Being this a planar\n% robot, vz=0 and wx=wy=0\nrobot.J=['[-a(1)*sin(q(1))-a(2)*sin(q(1)+q(2)) -a(2)*sin(q(1)+q(2));' ... \n 'a(1)*cos(q(1))+a(2)*cos(q(1)+q(2)) a(2)*cos(q(1)+q(2));' ...\n ' 0 0;' ...\n ' 0 0;' ...\n ' 0 0;' ...\n ' 1 1]'];\n%Function name to compute inverse kinematic\nrobot.inversekinematic_fn = 'inversekinematic_2dofplanar(robot, T)';\nrobot.directkinematic_fn = 'directkinematic(robot, q)';\n\n%minimum and maximum rotation angle in rad\nrobot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum\n deg2rad(-180) deg2rad(180)]; %Axis 2, minimum, maximum\n \n%maximum absolute speed of each joint rad/s or m/s\nrobot.velmax = [deg2rad(100);\n deg2rad(100)]; \n\nrobot.accelmax=robot.velmax/3; % 0.1 is here an acceleration time\n\n% end effectors maximum velocity\nrobot.linear_velmax = 0.5; %m/s, \n\n\n%base reference system\nrobot.T0 = eye(4);\n\n%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n%position, velocity and acceleration\nrobot=init_sim_variables(robot);\nrobot.path = pwd;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% GRAPHICS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%read graphics files\nrobot.graphical.has_graphics=1;\nrobot.graphical.color = [25 20 40];\n%for transparency\nrobot.graphical.draw_transparent=0;\n%draw DH systems\nrobot.graphical.draw_axes=1;\n%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for\n%bigger robots\nrobot.graphical.axes_scale=1;\n%adjust for a default view of the robot\nrobot.axis = [-2.2 2.2 -2.2 2.2 0 2.2];\nrobot = read_graphics(robot);\n\n\n% INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION\n% position, velocity and acceleration\nrobot.q=[0 0]';\nrobot.qd=[0 0]';\nrobot.qdd=[0 0]';\nrobot.time = [];\n\nrobot.q_vector=[];\nrobot.qd_vector=[];\nrobot.qdd_vector=[];\n\nrobot.last_target=directkinematic(robot, robot.q);\nrobot.last_zone_data = 'fine';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DYNAMIC PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nrobot.has_dynamics=1;\n\n%consider friction or not\nrobot.dynamics.friction=0;\n\n%link masses (kg)\nrobot.dynamics.masses=[2 2];\n\n%COM of each link with respect to own reference system\nrobot.dynamics.r_com=[-0.5 0 0; %(rx, ry, rz) link 1, w/r to reference system 1\n -0.5 0 0];%(rx, ry, rz) link 2\n\n%link masses\nm1 = robot.dynamics.masses(1);\nm2 = robot.dynamics.masses(2);\n\n%eval a to obtain parameters.\na=eval(robot.DH.a);\nL1 = a(1);\nL2 = a(2);\n\n\n%Inertia matrices of each link\n% Ixx\tIyy\tIzz\tIxy\tIyz\tIxz, or each row\nrobot.dynamics.Inertia=[0 m1*L1^2/12 m1*L1^2/12 0\t0\t0;\n 0 m2*L2^2/12 m2*L2^2/12 0\t0\t0];\n\n\n%Inertia of the rotor\nrobot.motors.Inertia=[0 0];\n%Reduction ratio: motor_speed/joint speed\nrobot.motors.G=[10 10];\n\n\n%Viscous friction factor of the motor\nrobot.motors.Viscous = [0.9 0.9];\n%Coulomb friction of the motor\n%Tc+, Tc-\nrobot.motors.Coulomb = [0\t0;\n 0\t0];\n \n%Obtained from motor catalog under practicals/inverse_dynamics\n% R(Ohm) L(H) Kv (V/rad/s):speed constant Kp (Nm/A):torque constant Max_current (A) \nrobot.motors.constants=[0.345 0.273e-3 2.3474e-05 84.9e-3 139];%these correspond to Maxon, 167132;\n \n\n \n \n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/example/2dofplanar/parameters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6029452209824656}} {"text": "function x = blend_rs_1dn ( r, s, n, bound_rs )\n\n%*****************************************************************************80\n%\n%% BLEND_RS_1DN extends vector data along sides into a square.\n%\n% Diagram:\n%\n% 01-----r1-----11\n% | . |\n% | . |\n% 0s.....rs.....1s\n% | . |\n% | . |\n% 00-----r0-----10\n%\n% Discussion:\n%\n% BLEND_RS_1DN is NOT equivalent to a bilinear finite element method,\n% since the data is sampled everywhere along the boundary lines,\n% rather than at a finite number of nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% William Gordon,\n% Blending-Function Methods of Bivariate and Multivariate Interpolation\n% and Approximation,\n% SIAM Journal on Numerical Analysis,\n% Volume 8, Number 1, March 1971, pages 158-177.\n%\n% William Gordon and Charles Hall,\n% Transfinite Element Methods: Blending-Function Interpolation over\n% Arbitrary Curved Element Domains,\n% Numerische Mathematik,\n% Volume 21, Number 1, 1973, pages 109-129.\n%\n% William Gordon and Charles Hall,\n% Construction of Curvilinear Coordinate Systems and Application to\n% Mesh Generation,\n% International Journal of Numerical Methods in Engineering,\n% Volume 7, 1973, pages 461-477.\n%\n% Joe Thompson, Bharat Soni, Nigel Weatherill,\n% Handbook of Grid Generation,\n% CRC Press, 1999.\n%\n% Parameters:\n%\n% Input, real R, S, the (R,S) coordinates of the point to be\n% evaluated.\n%\n% Input, integer N, the dimension of the vector space.\n%\n% External, BOUND_RS, is a function which is given (R,S)\n% coordinates and an component value I, and returns XI, the value\n% of the I-th component of the N-vector at that point. BOUND_RS\n% will only be called for \"sides\", that is, for values (R,S) where\n% at least one of R and S is either 0.0 or 1.0. BOUND_RS has the\n% form:\n% function xi = bound_rs ( r, s, i )\n%\n% Output, real X(N), the interpolated value at the point (R,S).\n%\n for i = 1 : n\n%\n% Get the I-th coordinate component at the four corners.\n%\n x00 = bound_rs ( 0.0, 0.0, i );\n x01 = bound_rs ( 0.0, 1.0, i );\n x10 = bound_rs ( 1.0, 0.0, i );\n x11 = bound_rs ( 1.0, 1.0, i );\n%\n% Get the I-th coordinate component at the sides.\n%\n xr0 = bound_rs ( r, 0.0, i );\n xr1 = bound_rs ( r, 1.0, i );\n x0s = bound_rs ( 0.0, s, i );\n x1s = bound_rs ( 1.0, s, i );\n%\n% Interpolate the I-th coordinate component of the interior point.\n%\n x(i) = blend_112 ( r, s, x00, x01, x10, x11, xr0, xr1, x0s, x1s );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blend/blend_rs_1dn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6029304592469661}} {"text": "function [detvtx,pth] = SStat_mass_FDR2(pval,maskvtx,rate)\n% [detvtx,pth] = SStat_mass_FDR2(pval,maskvtx,rate)\n%\n% Two-stage FDR approach to achieve tighter control of the FDR. This\n% procedure is more powerful than the original FDR procedure implemented in\n% SStat_mass_FDR.\n%\n% Input\n% pval: P-values.\n% maskvtx: Mask's vertices (1-based). Default [] (all vertices included).\n% rate: Expected FDR (between 0 and 1).\n%\n% Output\n% detvtx: Detected vertices (1-based).\n% pth: FDR threshold.\n%\n% $Revision: 1.1 $ $Date: 2015/01/06 17:03:59 $\n% Original Author: Jorge Luis Bernal Rusiel \n% CVS Revision Info:\n% $Author: mreuter $\n% $Date: 2015/01/06 17:03:59 $\n% $Revision: 1.1 $\n% References: Benjamini, Y., Krieger, A.M., Yekutieli, D. (2006). Adaptive\n% linear step-up procedures that control the false discovery rate. \n% Biometrika, 93, 491-507.\n%\nif nargin < 3\n rate = 0.05;\n if nargin < 2\n maskvtx = [];\n end\nend;\nnv0 = length(pval);\nif isempty(maskvtx)\n maskvtx = 1:nv0; \nend;\np = pval(maskvtx);\nnv = length(p);\n%% First stage (m0 estimation)\nq0 = rate/(1+rate);\npth0 = SStat_mass_FDR(p,q0);\ndetv0 = maskvtx(p <= pth0);\nndetv0 = length(detv0);\nm0 = nv-ndetv0;\n%% Second stage\nif (ndetv0 ~= 0) && (ndetv0 ~= nv)\n pth = SStat_mass_FDR(p,q0*nv/m0);\n detvtx = maskvtx(p <= pth);\nelse\n detvtx = detv0;\n pth = pth0;\nend;\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/external/freesurfer/Survival/mass_univariate/SStat_mass_FDR2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6026817034039994}} {"text": "%% DEMO 18: Arbitrary axis of rotation\n%\n%\n%\n% Some modenr CT geometires are starting to be a bit more complex, one of\n% the common things being arbitrary axis of rotation i.e. the detector and the\n% source can move not in a circular path, but in a \"spherical\" path. \n%\n% In TIGRE this has been implemented by defining the rotation with 3\n% angles, specifically the ZYZ configuration of Euler angles.\n%\n% This demo shows how to use it. \n% \n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% % Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri \n%--------------------------------------------------------------------------\n%% Initialize\n\nclear;\nclose all;\n%% Define Geometry\n% \n% VARIABLE DESCRIPTION UNITS\n%-------------------------------------------------------------------------------------\ngeo.DSD = 1536; % Distance Source Detector (mm)\ngeo.DSO = 1000; % Distance Source Origin (mm)\n% Detector parameters\ngeo.nDetector=[512; 512];\t\t\t\t\t% number of pixels (px)\ngeo.dDetector=[0.8; 0.8]; \t\t\t\t\t% size of each pixel (mm)\ngeo.sDetector=geo.nDetector.*geo.dDetector; % total size of the detector (mm)\n% Image parameters\ngeo.nVoxel=[128;128;128]; % number of voxels (vx)\n\n% a bit smaller than usual because the demo includes a very big detector\n% angle for showcase\ngeo.sVoxel=[256;256;256]/1.5; % total size of the image (mm)\n\n\ngeo.dVoxel=geo.sVoxel./geo.nVoxel; % size of each voxel (mm)\n% Offsets\ngeo.offOrigin =[0;0;0]; % Offset of image from origin (mm) \ngeo.offDetector=[0; 0]; % Offset of Detector (mm)\n\n\n% Auxiliary \ngeo.accuracy=0.5; % Accuracy of FWD proj (vx/sample)\n\ngeo.mode='cone';\n\n%% Define angles\nnumProjs = 100;\n\nanglesY=linspace(0,2*pi,numProjs);\nanglesZ2=anglesY;\nanglesZ1=pi*sin(linspace(0,2*pi,numProjs));\nangles=[anglesZ1;anglesY;anglesZ2];\n%% Get Image\n\nhead=headPhantom(geo.nVoxel);\n\n%% Project\n\nprojections=Ax(head,geo,angles);\n\nplotProj(projections,(1:100)*pi/180); % angle information not right in the title\n%% Reconstruct:\n\n% Note, FDK will not work.\n\nimgSIRT = SIRT(projections,geo, angles,50);\nimgCGLS = CGLS(projections,geo, angles,10);\n\nplotImg([head imgCGLS imgSIRT] ,'dim',3)", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Demos/d18_ArbitraryAxisOfRotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6026816986830146}} {"text": "function [S,SE] = sample_edges(V,E,samples_per_edge)\n % SAMPLE_EDGES Compute samples_per_edge extra points along each edge in E\n % defined over vertices of V.\n %\n % S = sample_edges(V,E,samples_per_edge)\n %\n % Inputs:\n % V vertices over which edges are defined, # vertices by dim\n % E edge list, # edges by 2\n % samples_per_edge number of extra samples to be computed along edge not\n % including start and end points\n % Outputs:\n % S sampled vertices, size less than # edges * (2+samples_per_edge) by dim,\n % always begins with V so that E is also defined over S\n %\n %\n\n dim = size(V,2);\n\n % trivial case\n if(isempty(E))\n S = [];\n SE = [];\n elseif(samples_per_edge < 0)\n S = V;\n SE = [];\n else\n % fraction parameter\n t = linspace(0.0,1.0,samples_per_edge+2);\n % get rid of start and end points\n t = t(2:(end-1));\n % repeat for each coordinate\n t = reshape(repmat(t,dim,1),1,size(t,2)*dim);\n % repeat for each edge\n t = repmat(t,size(E,1),1);\n % repeat start coords\n\n sp = repmat(V(E(:,1),:),1,samples_per_edge);\n % repeat end coords\n ep = repmat(V(E(:,2),:),1,samples_per_edge);\n % lerp from start point to end point for each coordinate\n S = sp.*(1-t) + ep.*t;\n % reshape to list coordinates\n S = S';\n S = reshape(S,dim,prod(size(S))/dim)';\n S = [V;S];\n % Determine edges between samples\n E1 = repmat((1:(samples_per_edge-1))',size(E,1),1);\n E2 = repmat((2:(samples_per_edge))',size(E,1),1);\n off = size(V,1) + ...\n reshape( ...\n repmat( ...\n samples_per_edge*((1:size(E,1))-1), ...\n samples_per_edge-1, ...\n 1), ...\n (samples_per_edge-1)*size(E,1),...\n 1);\n SE = repmat(off,1,2) + [E1 E2];\n % end point edges\n SE = [ ...\n SE; ...\n E(:,1) size(V,1) + (1+samples_per_edge*((1:size(E,1))-1))'; ...\n E(:,2) size(V,1) + (samples_per_edge*((1:size(E,1))))'];\n end\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/sample_edges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6026816855766054}} {"text": "function [elem2dof,elem2edge,edge,bdDof,freeDof] = dofP3(elem)\n%% DOFP3 dof structure for P3 element.\n%\n% [elem2dof,edge,bdDof] = DOFP3(elem) constructs the dof structure\n% for the quadratic element based on a triangle. elem2dof(t,i) is the\n% global index of the i-th dof of the t-th element.\n%\n% The global indices of the dof is organized according to the order of\n% nodes, edges and elements, namely, first give index number to the dofs\n% on nodes, then the dofs on edges, last the dofs on elements.\n%\n% See also dofP2, dof3P3.\n% \n% Created by Jie Zhou. \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nN = max(max(elem)); NT = size(elem,1); \n\n%% Data structure\ntotalEdge = uint32(sort([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])],2));\nmatlabversion = version;\nif str2double(matlabversion(end-5:end-2)) > 2012\n [edge, i2, j] = unique(totalEdge,'rows','legacy');\nelse\n [edge, i2, j] = unique(totalEdge,'rows');\nend\nNE = size(edge,1);\nelem2edge = reshape(j,NT,3);\n\n%% Nodal dof\nelem2dof = uint32(zeros(NT,10));\nelem2dof(:,1:3) = elem;\n\n%% Two dof on each edge\n% edge 1\nidx0 = (elem(:,3) > elem(:,2));\nelem2dof(idx0,4) = N + 2*(elem2edge(idx0,1))-1;\nelem2dof(idx0,5) = N + 2*(elem2edge(idx0,1));\nelem2dof(~idx0,4)= N + 2*(elem2edge(~idx0,1));\nelem2dof(~idx0,5)= N + 2*(elem2edge(~idx0,1))-1;\n% edge 2\nidx0 = (elem(:,3) > elem(:,1));\nelem2dof(idx0,6) = N + 2*(elem2edge(idx0,2));\nelem2dof(idx0,7) = N + 2*(elem2edge(idx0,2))-1;\nelem2dof(~idx0,6) = N + 2*(elem2edge(~idx0,2))-1;\nelem2dof(~idx0,7) = N + 2*(elem2edge(~idx0,2));\n% edge 3\nidx0 = (elem(:,2) > elem(:,1));\nelem2dof(idx0,8) = N + 2*(elem2edge(idx0,3))-1;\nelem2dof(idx0,9) = N + 2*(elem2edge(idx0,3));\nelem2dof(~idx0,8) = N + 2*(elem2edge(~idx0,3));\nelem2dof(~idx0,9) = N + 2*(elem2edge(~idx0,3))-1;\n\n%% Element dof\nelem2dof(:,10) = (N+2*NE+1:N+2*NE+NT)';\n\n%% Boundary dof\ni1(j(3*NT:-1:1)) = 3*NT:-1:1; \ni1 = i1';\nbdEdgeIdx = (i1 == i2);\nisBdDof = false(N+2*NE+NT,1);\nisBdDof(edge(bdEdgeIdx,:)) = true; % boundary node \nidx = find(bdEdgeIdx);\nisBdDof(N+2*idx) = true; % two dof on boundary edges\nisBdDof(N+2*idx-1) = true;\nbdDof = find(isBdDof);\n freeDof = find(~isBdDof);", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/dof/dofP3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.60267884139686}} {"text": "function [Y,h]=glyph(X,r,c)\n%Syntax: [Y,h]=glyph(X,r,c)\n%__________________________\n%\n% 3D glyph visualization. The glyph is a convex deltahedron where each\n% node is connected to its 6 nearest nodes.\n%\n% Y is the N-by-3 matrix whith the cartesian coordinates of the points on \n% the glyph.\n% h returns a vector of tetrahedra handles. Each element of h is a handle\n% to the set of patches forming one tetrahedron. Type \"help tetramesh\"\n% for more info.\n% X is the N-by-3 matrix whith the cartesian coordinates of the points on \n% the sphere.\n% r is the range parameter.\n% c is the color parameter.\n%\n%\n% References:\n%\n% Sangole A., Knopf G. K. (2002): Representing high-dimensional data sets\n% as close surfaces. Journal of Information Visualization 1: 111-119\n%\n% Sangole A., Knopf G. K. (2003): Geometric representations for\n% high-dimensional data using a spherical SOFM. International Journal of\n% Smart Engineering System Design 5: 11-20\n%\n% Sangole A., Knopf G. K. (2003): Visualization of random ordered numeric\n% data sets using self-organized feature maps. Computers and Graphics 27:\n% 963-976\n%\n% Sangole A. P. (2003): Data-driven Modeling using Spherical\n% Self-organizing Feature Maps. Doctor of Philosophy (Ph.D.) Thesis. \n% Department of Mechanical and Materials Engineering. Faculty of\n% Engineering. The University of Western Ontario, London, Ontario, Canada.\n%\n%\n% Remark:\n%\n% If no output is desired, the function plots the glyph.\n%\n%\n% Archana P. Sangole, PhD., P.E. (TX chapter)\n% School of Physical & Occupational Therapy\n% McGill University\n% 3654 Promenade Sir-William-Osler\n% Montreal, PQ, H3G 1Y5\n% e-mail: archana.sangole@mail.mcgill.ca\n%\n% CRIR, Rehabilitation Institute of Montreal\n% 6300 Ave Darlington\n% Montreal, PQ, H3S 2J5\n% Tel: 514.340.2111 x2188\n% Fax: 514.340.2154\n%\n%\n% Alexandros Leontitsis, PhD\n% Department of Education\n% University of Ioannina\n% 45110- Dourouti\n% Ioannina\n% Greece\n% \n% University e-mail: me00743@cc.uoi.gr\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n% \n% 23-Mar-2006\n\n\n% Add a center to the sphere, which is [0 0 0]\nX=[X;zeros(1,3)];\n\n% 3-dimensional Delaunay tessellation\ntri=delaunay3(X(:,1),X(:,2),X(:,3));\n\n% Remove the center\nX(end,:)=[];\n\nif nargin<2 | isempty(r)==1\n r=ones(length(X),1);\nelse\n % r must be a vector\n if min(size(r))>1\n error('r must be a vector.');\n end\n % The length of r should be equal to the length of X.\n if length(r)~=length(X)\n error('The length of r should be equal to the length of X.');\n end\n r=r(:);\nend\n\nif nargin<3 | isempty(c)==1\n c=r;\nelse\n % c must be a vector\n if min(size(c))>1\n error('c must be a vector.');\n end\n % The length of c should be equal to the length of X.\n if length(c)~=length(X)\n error('The length of c should be equal to the length of X.');\n end\n c=c(:);\nend\n\n% Go to spherical coordinates, ...\n[theta,phi]=cart2sph(X(:,1),X(:,2),X(:,3));\n% ... and compute the cartesian coordinates with the given r\n[Y(:,1),Y(:,2),Y(:,3)]=sph2cart(theta,phi,r);\n\n% Add a center to the glyph, which is [0 0 0]\nY=[Y;zeros(1,3)];\n% Sort the vertices of each tereahedron ...\ntri=sort(tri')';\n% ... in order to calculate the color\ni=1:length(tri);\ncnew(i)=mean(c(tri(i,1:end-1))')';\n\n% If no output is desired, plot the glyph\nif nargout==0\n % Plot the glyph\n tetramesh(tri,Y,cnew,'FaceAlpha',1,'LineStyle','-');\n % Define the x axis\n xlim([-1.2 1.2])\n % Define the y axis\n ylim([-1.2 1.2])\n % Define the z axis\n zlim([-1.2 1.2])\n % Define the color axis\n caxis([1 1.2]);\n % Remove the axes\n axis off\n % Freeze aspect ratio properties to faciliate 3D rotation\n axis vis3d\n% Else if the handle is desired\nelseif nargout==2\n % Retrieve the handle\n h=tetramesh(tri,Y,cnew,'FaceAlpha',1,'LineStyle','none');\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/13252-s-sofm-toolbox/glyph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6026788413602104}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = inversekinematic_Viper_s1300(robot, T)\t\n% Solves the inverse kinematic problem for the ADEPT Viper_S1300 robot\n% where:\n% robot stores the robot parameters.\n% T is an homogeneous transform that specifies the position/orientation\n% of the end effector.\n%\n% A call to Q=inversekinematic_Viper_s1300 returns 8 possible solutions, thus,\n% Q is a 6x8 matrix where each column stores 6 feasible joint values.\n%\n% \n% Example code:\n%\n% robot=load_robot('ADEPT', 'Viper_s1300');\n% q = [0 0 0 0 0 0];\t\n% T = directkinematic(robot, q);\n% %Call the inversekinematic for this robot\n% qinv = inversekinematic(robot, T);\n% check that all of them are feasible solutions!\n% and every Ti equals T\n% for i=1:8,\n% Ti = directkinematic(robot, qinv(:,i))\n% end\n%\tSee also DIRECTKINEMATIC.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction [q] = inversekinematic_Viper_s1300(robot, T)\n\n%initialize q,\n%eight possible solutions are generally feasible\nq=zeros(6,8);\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%See geometry at the reference for this robot, distance from the wrist to\n%the end effector\nL6=d(6);\n\n\n%T= [ nx ox ax Px;\n% ny oy ay Py;\n% nz oz az Pz];\nPx=T(1,4);\nPy=T(2,4);\nPz=T(3,4);\n\n%Compute the position of the wrist, being W the Z component of the end effector's system\nW = T(1:3,3);\n\n% Pm: wrist position\nPm = [Px Py Pz]' - L6*W; \n\n%first joint, two possible solutions admited: \n% if q(1) is a solution, then q(1) + pi is also a solution, obtain theta1\n% by geometric methods\nq1 = atan2(Pm(2), Pm(1));\n\n\n%solve for q2\nq2_1=solve_for_theta2(robot, [q1 0 0 0 0 0 0], Pm);\n\nq2_2=solve_for_theta2(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n%solve for q3\nq3_1=solve_for_theta3(robot, [q1 0 0 0 0 0 0], Pm);\n\nq3_2=solve_for_theta3(robot, [q1+pi 0 0 0 0 0 0], Pm);\n\n\n%Arrange solutions, there are 8 possible solutions so far.\n% if q1 is a solution, q1* = q1 + pi is also a solution.\n% For each (q1, q1*) there are two possible solutions\n% for q2 and q3 (namely, elbow up and elbow up solutions)\n% So far, we have 4 possible solutions. Howefer, for each triplet (theta1, theta2, theta3),\n% there exist two more possible solutions for the last three joints, generally\n% called wrist up and wrist down solutions. For this reason, \n%the next matrix doubles each column. For each two columns, two different\n%configurations for theta4, theta5 and theta6 will be computed. These\n%configurations are generally referred as wrist up and wrist down solution\nq = [q1 q1 q1 q1 q1+pi q1+pi q1+pi q1+pi; \n q2_1(1) q2_1(1) q2_1(2) q2_1(2) q2_2(1) q2_2(1) q2_2(2) q2_2(2);\n q3_1(1) q3_1(1) q3_1(2) q3_1(2) q3_2(1) q3_2(1) q3_2(2) q3_2(2);\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0;\n 0 0 0 0 0 0 0 0];\n\n%leave only the real part of the solutions\nq=real(q);\n\n%Note that in this robot, the joint q3 has a non-simmetrical range. In this\n%case, the joint ranges from 60 deg to -219 deg, thus, the typical normalizing\n%step is avoided in this angle (the next line is commented). When solving\n%for the orientation, the solutions are normalized to the [-pi, pi] range\n%only for the theta4, theta5 and theta6 joints.\n\n%normalize q to [-pi, pi]\nq(1,:) = normalize(q(1,:));\nq(2,:) = normalize(q(2,:));\n\n% solve for the last three joints\n% for any of the possible combinations (theta1, theta2, theta3)\nfor i=1:2:size(q,2),\n % use solve_spherical_wrist2 for the particular orientation\n % of the systems in this ABB robot\n % use either the geometric or algebraic method.\n % the function solve_spherical_wrist2 is used due to the relative\n % orientation of the last three DH reference systems.\n \n %use either one algebraic method or the geometric \n %qtemp = solve_spherical_wrist(robot, q(:,i), T, 1, 'geometric'); %wrist up\n qtemp = solve_spherical_wrist(robot, q(:,i), T, 1,'algebraic'); %wrist up\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i)=qtemp;\n \n %qtemp = solve_spherical_wrist(robot, q(:,i), T, -1, 'geometric'); %wrist down\n qtemp = solve_spherical_wrist(robot, q(:,i), T, -1, 'algebraic'); %wrist down\n qtemp(4:6)=normalize(qtemp(4:6));\n q(:,i+1)=qtemp;\nend\n\n \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for second joint theta2, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q2 = solve_for_theta2(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%DH table parameters with which we calculate theta2, using\n%geometric methods\nL2=a(2);\nL3=d(4);\n\n%Offset distance between the centers of the reference systems of the links\n%2 and 3\nA1 = a(3);\n\n%See geometry of the robot. Considering L4 calculate the offset between the\n%centers of the reference systems of the links 2 and 3\nL4 = sqrt(A1^2 + L3^2);\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\n%Distance between the system 1 to the wrist\nr = sqrt(p1(1)^2 + p1(2)^2);\n\nbeta = atan2(-p1(2), p1(1));\ngamma = real(acos((L2^2+r^2-L4^2)/(2*r*L2))); %Theorem of the cosine\n\nif ~isreal(gamma)\n disp('WARNING:inversekinematic_Viper_s1300: the point is not reachable for this configuration, imaginary solutions'); \n %gamma = real(gamma);\nend\n\n%return two possible solutions\n%elbow up and elbow down\n%the order here is important and is coordinated with the function\n%solve_for_theta2. We add pi/2 to offset lags in our reference systems\nq2(1) = pi/2 - beta - gamma; %elbow up\nq2(2) = pi/2 - beta + gamma; %elbow down\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% solve for third joint theta3, two different\n% solutions are returned, corresponding\n% to elbow up and down solution\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction q3 = solve_for_theta3(robot, q, Pm)\n\n%Evaluate the parameters\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n%DH table parameters with which we calculate theta3, using\n%geometric methods\nL2=a(2);\nL3=d(4);\n\nA1 = a(3);\n\n%See geometry of the robot, like in the function q2\nL4 = sqrt(A1^2 + L3^2);\n\n%The delta angle is fixed because they are the lines that make up the gap\n%between the links 2, 3 and 4\ndelta = real(acos((A1^2+L4^2-L3^2)/(2*A1*L4))); %Theorem of the cosine\n\n%given q1 is known, compute first DH transformation\nT01=dh(robot, q, 1);\n\n%Express Pm in the reference system 1, for convenience\np1 = inv(T01)*[Pm; 1];\n\n%Same as the function q2\nr = sqrt(p1(1)^2 + p1(2)^2);\n\n%Real angle between the links 2 and 3\nro = real(acos((L2^2 + L4^2 - r^2)/(2*L2*L4))); %Theorem of the cosine\n\nif ~isreal(ro)\n disp('WARNING:inversekinematic_Viper_s1300: the point is not reachable for this configuration, imaginary solutions'); \n %ro = real(ro);\nend\n\n%return two possible solutions\n%elbow up and elbow down \n%the order here is important and is coordinated with the function\n%solve_for_theta3. We add pi to offset lags in our reference systems\nq3(1) = pi - ro - delta; %elbow up\nq3(2) = pi + ro - delta; %elbow down\n\n\n\n%remove complex solutions for q for the q1+pi solutions\nfunction qreal = arrange_solutions(q)\nqreal=q(:,1:4);\n\n%sum along rows if any angle is complex, for any possible solutions, then v(i) is complex\nv = sum(q, 1);\n\nfor i=5:8,\n if isreal(v(i))\n qreal=[qreal q(:,i)]; %store the real solutions\n end\nend\n\nqreal = real(qreal);", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/robots/ADEPT/Viper_s1300b/inversekinematic_Viper_s1300.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6026078762640528}} {"text": "function BED = calc_BED(paramS,varargin)\n%BED = calc_BED(paramS)\n%Ref: Comparison Between Mechanistic Radiobiological Modeling Vs. \n%Fowler BED Equation in Evaluating Lung Cancer Radiotherapy Outcome \n%for a Broad Range of Fractionation, J Jeong et al., AAPM 2017\n%-----------------------------------------------------------------------\n% INPUTS\n% paramS : Parameter dictionary with fields:\n% d - Fraction size\n% n - No. fractions\n% T - No. treatment days\n% alpha\n% abRatio\n% Note : For a 3D dose distibution, calculate 3D BED by setting input \n% paramS.frxSize.val = doseArray3M/numFrx\n%-----------------------------------------------------------------------\n% AI 12/4/17\n% AI 07/30/18 Updated to handle 3D dose distibution\n \n\n%Define constants \nTk = paramS.Tk.val; %Kick-off time of repopulation (days)\nTp = paramS.Tp.val; %Potential tumor doubling time (days)\n\n\nalpha = paramS.alpha.val; \nabRatio = paramS.abRatio.val; %alpha/beta for tumor\nd = paramS.frxSize.val;\nn = paramS.numFractions.val;\nif isfield(paramS,'treatmentDays')\n txDaysV = paramS.treatmentDays.val;\n %Check for numeric input\n if ~isnumeric(txDaysV)\n txDaysV = str2num(txDaysV);\n end\n %Otherwise assume function specified\n if isempty(txDaysV)\n txDaysV = eval([txDaysV,'(',num2str(n),')']);\n end\n T = txDaysV(end);\nelse\n % Default: Compute length of treatment assuming one fraction every\n % weekday with weekend breaks.\n T = floor(n/5)*7 + mod(n,5);\nend\n\n\n\n%Compute BED\nBED = n.* d .* (1 + d./abRatio);\nif T > Tk\n BED = BED - log(2) * (T-Tk)/(alpha*Tp);\nend\n \n \n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/calc_BED.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6025782219276046}} {"text": "function [axis,angle]=rotation2axisangle(R)\ncosq = 0.5*(R(1,1)+R(2,2)+R(3,3)-1);\nif(cosq>1)\n cosq=1;\nend\nif(cosq<-1)\n cosq=-1;\nend\nangle = acos(cosq);\naxis = zeros(3,1);\nif(abs(angle)<1e-4) \nelseif(abs(angle-pi)<1e-4)\n for i=1:3\n a = 0.5*(R(i,i)+1);\n if abs(a)<1e-4\n axis(i) = 0;\n else\n axis(i) = a^0.5;\n end\n end\n \n maxind = 1;\n if axis(2)>axis(1)\n maxind = 2;\n end\n if axis(3)>axis(2)\n maxind = 3;\n end\n if(maxind == 1)\n a1a2 = R(1,2) + R(2,1);\n a1a3 = R(1,3) + R(3,1);\n if(a1a2<0)\n axis(2) = -axis(2);\n end\n if(a1a3<0)\n axis(3) = -axis(3);\n end\n end\n if(maxind == 2)\n a1a2 = R(1,2) + R(2,1);\n a2a3 = R(2,3) + R(3,2);\n if(a1a2<0)\n axis(1) = -axis(1);\n end\n if(a2a3<0)\n axis(3) = -axis(3);\n end\n end\n if(maxind == 3)\n a1a3 = R(1,3) + R(3,1);\n a2a3 = R(2,3) + R(3,2);\n if(a1a3<0)\n axis(1) = -axis(1);\n end\n if(a2a3<0)\n axis(2) = -axis(2);\n end\n end\n axis = axis/norm(axis);\nelse\n axis(1) = R(3,2) - R(2,3);\n axis(2) = R(1,3) - R(3,1);\n axis(3) = R(2,1) - R(1,2);\n axis = axis/norm(axis);\nend\n\nend", "meta": {"author": "xuhuairuogu", "repo": "V-REP-Simulation-Projects", "sha": "841b944af4ea3a8fb250578d36434515f577f411", "save_path": "github-repos/MATLAB/xuhuairuogu-V-REP-Simulation-Projects", "path": "github-repos/MATLAB/xuhuairuogu-V-REP-Simulation-Projects/V-REP-Simulation-Projects-841b944af4ea3a8fb250578d36434515f577f411/admittance control(adapted from an example in the book--A Systematic Approach to Learning Robot Programming with ROS)/iiwa14_kinematics/rotation2axisangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699185, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.602570467309095}} {"text": "% Estimation of the standard deviation of an image assuming that the noise\n% is Gaussian white additive. The file estimates the standard deviation\n% using the median filter on the fine scale subband of the wavelet\n% decomposition.\n function sd_estimate=sdest(x)\n [ca,ch,cv,cd] = dwt2(x,'sym4','mode','sym');\n sd_estimate = mad(cd(:),1)/0.6745\n\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/Shearlet/Util/sdest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6025704601530685}} {"text": "% Figure 10.72 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% Fig. 10.72\n% Data for RTP Demo 3-3-99\n% Data provided by Dr. Gwen van der Linden\n% Data is from System Identification Studies\nInputFlux=[3.460064464376177e-1 1.177299050104922e-1 2.838023866104041e-2;\n 3.880303397347619e-11 8.024902450324316e-2 1.807231516460469e-2;\n 8.004191616976514e-9 2.721604310757543e-3 3.171348842079633e-2];\nM_inv=diag([1.000040130716728 5.557442686788876 13.63821806414694]);\nRadiation=[5.47621193859299e-2 -8.570695054070524e-3 -8.296135532988507e-4... \n -4.536181077856052e-2;\n -8.570695054070524e-3 8.570946319867835e-3 -1.621311365067015e-7...\n -8.913466080455817e-8;\n -8.296135532988507e-4 -1.621311365067015e-7 8.299854517643017e-4...\n -2.097673289443245e-7];\nConduction=[3.559939609150268e-7 -1.113667477845243e-7 -1.976161155515125e-7...\n -4.701109757899004e-8;\n -1.113667477845243e-7 1.160207476868843e-2 -2.502736022145532e-3...\n -9.099227379795117e-3;\n -1.976161155515125e-7 -2.502736022145532e-3 6.37364815665867e-3...\n -3.870714518397587e-3];\nScaleTemp=diag([0.01 0.01 0.01 0.01]);\n\nclf;\n%\nsim('fig10_71')\n%plot(tout,r,'-');\n%hold on;\n%plot(tout,y,'--');\n%xlabel('Time (sec)');\n%ylabel('Temperature (K)');\n%hold off;\n%pause;\nii=240:876;\nplot(tout(ii),r(ii),'-',tout(ii),y(ii,2),'--');\nlegend('r','y');\ngrid on;\nxlabel('Time (sec)');\nylabel('Temperature (K)');\ntitle('Fig. 10.72(a) Temperature tracking response');\npause;\nhold off;\nii=240:876;\nplot(tout(ii),u(ii),'-');\nxlabel('Time (sec)');\nylabel('Lamp voltage (V)');\ngrid on;\nlegend('u');\ntitle('Fig. 10.72(b) Control effort');\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/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_72.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6025074350318553}} {"text": "function [u,p,edgeC,A,eqn,info] = StokesisoP2P1(node,elem,pde,bdFlag,option)\n%% STOKESISOP2P1 Stokes equation: isoP2-P1 modified Taylor-Hood elements.\n%\n% [u,p] = STOKESisoP2P1(node,elem,pde,bdFlag) use constinous P1 element\n% on grid h and continous P1 element on grid H = 2*h to approximate\n% velocity u and pressure p, repectively.\n%\n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% with\n% Dirichlet boundary condition u = g_D on \\Gamma_D,\n% Neumann boundary condition du/dn - np = g_N on \\Gamma_N.\n%\n% Created by Ming Wang at Aug., 2012.\n%\n% See also StokesisoP2P0, StokesP2P1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('option','var'), option = []; end\n\n%% Refine grid for P1\nnodeC = node; elemC = elem; bdFlagC = bdFlag;\n[tempvar,edgeC] = dofP2(elemC);\n[node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\nNC = size(nodeC,1); NTC = size(elemC,1); \nN = size(node,1); NT = size(elem,1); Nu = N; Np = NC; \n\ntic;\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\nareaC = sum(reshape(area,NTC,4),2);\n\n%% Assemble stiffness matrix for Laplace operator\nA = sparse(Nu,Nu);\nfor i = 1:3\n for j = i:3\n Aij = (Dlambda(:,1,i).*Dlambda(:,1,j) + ...\n Dlambda(:,2,i).*Dlambda(:,2,j)).*area;\n if isfield(pde,'mu') && (pde.mu~=1)\n Aij = pde.mu*Aij;\n end\n if (j==i)\n A = A + sparse(elem(:,i),elem(:,j),Aij,N,N);\n else\n A = A + sparse([elem(:,i);elem(:,j)],[elem(:,j);elem(:,i)],...\n [Aij; Aij],N,N);\n end\n end\nend\nclear Aij\nA = blkdiag(A,A);\n\n%% Assemble the matrix for divergence operator\n% idea: Basis on coarse grids can be expanded from fine grids, i.e., \n% lambda_{i,c} = lambda_{i,f} + 1/2*sum_{j \\ in V(i)} lambda_{j,f}\n% where V(i) is the index of points on edges surrounding point i.\nDx = sparse(N,N);\nDy = sparse(N,N);\nfor j = 1:3 % loop for u index\n Dx = Dx + sparse(elem(:),repmat(elem(:,j),3,1),...\n repmat(1/3*Dlambda(:,1,j).*area,3,1),N,N);\n Dy = Dy + sparse(elem(:),repmat(elem(:,j),3,1),...\n repmat(1/3*Dlambda(:,2,j).*area,3,1),N,N);\nend\nBf = [-Dx -Dy];\nBv = Bf(1:NC,:);\nBe = Bf(NC+1:end,:);\nD = 1/2*icdmat(double(edgeC),[1,1]);\nB = Bv + D'*Be;\n\n\n%% Assemble right hand side by 4-points quadrature rule\nf1 = zeros(Nu,1);\nf2 = zeros(Nu,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isempty(pde.f)\n % quadrature points in the barycentric coordinate\n [lambda,weight] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n ft1 = zeros(NT,3);\n ft2 = zeros(NT,3);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n % function values at quadrature points\n fp = pde.f(pxy);\n % evaluate fp outside.\n for j = 1:3\n ft1(:,j) = ft1(:,j) + fp(:,1).*lambda(p,j)*weight(p);\n ft2(:,j) = ft2(:,j) + fp(:,2).*lambda(p,j)*weight(p);\n end\n end\n ft1 = ft1.*repmat(area,1,3);\n ft2 = ft2.*repmat(area,1,3);\n f1 = accumarray(elem(:),ft1(:),[Nu 1]);\n f2 = accumarray(elem(:),ft2(:),[Nu 1]);\nend\n\n[AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesisoP2P1;\n\n%% Record assembeling time\nassembleTime = toc;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(ufreeDof), return; end\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if length(f)+length(g) <= 1e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % Multigrid-type solver for large size systems\n option.solver = 'asmg';\n end\nend\nsolver = option.solver;\n\n%% Solver\nswitch solver\n case 'direct'\n tic;\n bigA = [AD, BD'; ...\n BD, sparse(Np,Np)];\n bigF = [f; g];\n bigu = [u; p];\n bigFreeDof = [ufreeDof; 2*Nu+pDof];\n bigu(bigFreeDof) = bigA(bigFreeDof,bigFreeDof)\\bigF(bigFreeDof);\n u = bigu(1:2*Nu);\n p = bigu(2*Nu+1:end);\n residual = norm(bigF - bigA*bigu);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual); \n case 'mg'\n option.solver = 'WCYCLE';\n [u(ufreeDof),p,info] = mgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n u(ufreeDof),p,elemC,ufreeDof,option); \n case 'asmg'\n [u(ufreeDof),p,info] = asmgstokes(A(ufreeDof,ufreeDof),B(:,ufreeDof),f(ufreeDof),g,...\n u,p,nodeC,elemC,bdFlagC,ufreeDof,option); \nend\n\n%% Post-process\nif length(pDof)~=Np % p is unique up to a constant\n % impose the condition int(p)=0\n c = sum(mean(p(elemC),2).*areaC)/sum(areaC);\n p = p - c;\nend\n\n%% Output information\neqn = struct('A',AD,'B',BD,'f',f,'g',g,'ufreeDof',ufreeDof,'pDof',pDof);\ninfo.assembleTime = assembleTime;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdStokesisoP2P1\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,BD,f,g,u,p,ufreeDof,pDof] = getbdStokesisoP2P1\n %% Initial set up\n g = zeros(Np,1);\n u = zeros(2*Nu,1);\n p = zeros(Np,1);\n ufreeDof = (1:Nu)';\n pDof = (1:Np)';\n if ~exist('bdFlag','var'), bdFlag = []; end\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Find Dirichlet dof and modify the matrix\n % Find Dirichlet boundary dof: fixedDof and pDof\n isFixedDof = false(Nu,1);\n if ~isempty(bdFlag) % case: bdFlag is not empty\n allEdge = [elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])];\n Dirichlet = allEdge((bdFlag(:) == 1),:);\n isFixedDof(Dirichlet(:)) = true;\n fixedDof = find(isFixedDof);\n ufreeDof = find(~isFixedDof);\n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N)\n fixedDof = findboundary(elem);\n isFixedDof(fixedDof) = true;\n ufreeDof = find(~isFixedDof);\n end\n if isempty(fixedDof) % pure Neumann boundary condition\n % pde.g_N could be empty which is homogenous Neumann boundary condition\n fixedDof = 1;\n ufreeDof = 2:Nu; % eliminate the kernel by enforcing u(1) = 0;\n end\n \n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % AD(fixedDof,fixedDof)=I, AD(fixedDof,ufreeDof)=0, AD(ufreeDof,fixedDof)=0.\n % BD(:,fixedDof) = 0 and thus BD'(fixedDof,:) = 0.\n bdidx = zeros(2*Nu,1);\n bdidx(fixedDof) = 1;\n bdidx(Nu+fixedDof) = 1;\n Tbd = spdiags(bdidx,0,2*Nu,2*Nu);\n T = spdiags(1-bdidx,0,2*Nu,2*Nu);\n AD = T*A*T + Tbd;\n BD = B*T;\n \n %% Part 2: Find boundary edges and modify the right hand side f and g\n % Find boundary edges: Neumann and Robin\n Neumann = []; Robin = []; %#ok<*NASGU>\n if ~isempty(bdFlag)\n allEdge = [elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])];\n Neumann = allEdge((bdFlag(:)==2)|(bdFlag(:) == 3),:);\n Robin = allEdge((bdFlag(:) == 3),:);\n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n [tempvar,Neumann] = findboundary(elem);\n if ~isempty(pde.g_R)\n Robin = Neumann;\n end\n end\n \n % Neumann boundary condition\n if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n [lambda,w] = quadpts1(3);\n nQuad = size(lambda,1);\n ve = node(Neumann(:,1),:) - node(Neumann(:,2),:); % length of edge\n edgeLength = sqrt(sum(ve.^2,2));\n % update RHS\n gex = zeros(size(Neumann,1),2); % x-component\n gey = zeros(size(Neumann,1),2); % y-component\n for pp = 1:nQuad\n pxy = lambda(pp,1)*node(Neumann(:,1),:)+lambda(pp,2)*node(Neumann(:,2),:);\n gp = pde.g_N(pxy);\n gex(:,1) = gex(:,1) + w(pp)*edgeLength.*gp(:,1)*lambda(pp,1);\n gex(:,2) = gex(:,2) + w(pp)*edgeLength.*gp(:,1)*lambda(pp,2);\n gey(:,1) = gey(:,1) + w(pp)*edgeLength.*gp(:,2)*lambda(pp,1);\n gey(:,2) = gey(:,2) + w(pp)*edgeLength.*gp(:,2)*lambda(pp,2);\n end\n f1(1:N) = f1(1:N) + accumarray(Neumann(:), gex(:),[N,1]);\n f2(1:N) = f2(1:N) + accumarray(Neumann(:), gey(:),[N,1]);\n end\n f = [f1; f2];\n % The case non-empty Neumann but g_N=[] corresponds to the zero flux\n % boundary condition on Neumann edges and no modification is needed.\n \n % Dirichlet boundary conditions\n if ~isempty(fixedDof) && ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n u1 = zeros(Nu,1);\n u2 = zeros(Nu,1);\n uD = pde.g_D(node(fixedDof,:));\n u1(fixedDof) = uD(:,1);\n u2(fixedDof) = uD(:,2);\n u = [u1;u2];\n f = f - A*u; % bring affect of nonhomgenous Dirichlet bd condition\n g = g - B*u; % to the right hand side\n g = g - mean(g);\n f(fixedDof) = u1(fixedDof);\n f(fixedDof+Nu) = u2(fixedDof);\n end\n % The case non-empty Dirichlet but g_D=[] corresponds to the zero Dirichlet\n % boundary condition and no modification is needed.\n \n % modfiy pressure dof for pure Dirichlet\n if isempty(Neumann)\n pDof = (1:Np-1)';\n end\n\n ufreeDof = [ufreeDof; Nu+ufreeDof]; \n end % end of function getbdStokesisoP2P1\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/equation/StokesisoP2P1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6025074274637442}} {"text": "% FactorMarginalization Sums given variables out of a factor.\n% B = FactorMarginalization(A,V) computes the factor with the variables\n% in V summed out. The factor data structure has the following fields:\n% .var Vector of variables in the factor, e.g. [1 2 3]\n% .card Vector of cardinalities corresponding to .var, e.g. [2 2 2]\n% .val Value table of size prod(.card)\n%\n% The resultant factor should have at least one variable remaining or this\n% function will throw an error.\n%\n% See also FactorProduct.m, IndexToAssignment.m, and AssignmentToIndex.m\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nfunction B = FactorMarginalization(A, V)\n\n% Check for empty factor or variable list\nif (isempty(A.var) || isempty(V)), B = A; return; end;\n\n% Construct the output factor over A.var \\ V (the variables in A.var that are not in V)\n% and mapping between variables in A and B\n[B.var, mapB] = setdiff(A.var, V);\n\n% Check for empty resultant factor\nif isempty(B.var)\n %error('Error: Resultant factor has empty scope');\n B.var = [];\n B.card = [];\n B.val = [];\n return;\nend;\n\n% Initialize B.card and B.val\nB.card = A.card(mapB);\nB.val = zeros(1,prod(B.card));\n\n% Compute some helper indices\n% These will be very useful for calculating C.val\n% so make sure you understand what these lines are doing\nassignments = IndexToAssignment(1:length(A.val), A.card);\nindxB = AssignmentToIndex(assignments(:, mapB), B.card);\n\nfor i = 1:length(A.val),\n B.val(indxB(i)) = B.val(indxB(i)) + A.val(i);\nend;\n\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/7.CRF Learning for OCR/FactorMarginalization.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6024708785161778}} {"text": "function c=ref_edgt(f,g,a,M)\n%REF_EDGT Reference Even Discrete Gabor transform\n% Usage c=ref_edgt(f,g,a,M);\n%\n% The input window must be odd-centered.\n\nL=size(f,1);\nW=size(f,2);\n\nN=L/a;\nM=L/b;\n\nF=zeros(L,M*N);\n\nl=(0:L-1)';\nfor n=0:N-1\n for m=0:M-1\n F(:,1+m+n*M)=exp(2*pi*i*m.*(l+.5)*b/L).*circshift(g,n*a);\n end;\nend;\n\nc=F'*f;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/reference/ref_edgt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.602434396456129}} {"text": "function [e, edata, eprior] = gperr(net, x, t)\n%GPERR\tEvaluate error function for Gaussian Process.\n%\n%\tDescription\n%\tE = GPERR(NET, X, T) takes a Gaussian Process data structure NET\n%\ttogether with a matrix X of input vectors and a matrix T of target\n%\tvectors, and evaluates the error function E. Each row of X\n%\tcorresponds to one input vector and each row of T corresponds to one\n%\ttarget vector.\n%\n%\t[E, EDATA, EPRIOR] = GPERR(NET, X, T) additionally returns the data\n%\tand hyperprior components of the error, assuming a Gaussian prior on\n%\tthe weights with mean and variance parameters PRMEAN and PRVARIANCE\n%\ttaken from the network data structure NET.\n%\n%\tSee also\n%\tGP, GPCOVAR, GPFWD, GPGRAD\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nerrstring = consist(net, 'gp', x, t);\nif ~isempty(errstring);\n error(errstring);\nend\n\ncn = gpcovar(net, x);\n\nedata = 0.5*(sum(log(eig(cn, 'nobalance'))) + t'*inv(cn)*t);\n\n% Evaluate the hyperprior contribution to the error.\n% The hyperprior is Gaussian with mean pr_mean and variance\n% pr_variance\nif isfield(net, 'pr_mean')\n w = gppak(net);\n m = repmat(net.pr_mean, size(w));\n if size(net.pr_mean) == [1 1]\n eprior = 0.5*((w-m)*(w-m)');\n e2 = eprior/net.pr_var;\n else\n wpr = repmat(w, size(net.pr_mean, 1), 1)';\n eprior = 0.5*(((wpr - m').^2).*net.index);\n e2 = (sum(eprior, 1))*(1./net.pr_var);\n end\nelse\n e2 = 0;\n eprior = 0;\nend\n\ne = edata + e2;\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/gperr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6024343960284297}} {"text": "function [xEst,PEst]=batchLSLinMeasLinDyn(z,H,F,R,kD,Q,numMeas)\n%%BATCHLSLINMEASLINDYN Perform batch least squares state estimation under a\n% linear measurement model and a linear dynamic model with\n% optional process noise.\n%\n%INPUTS: z The zDim X N matrix of measurements for the whole batch. It is\n% assumed that the measurements have the same dimensionality over\n% the batch. If an empty matrix is passed, then it is assumed that\n% the user only wants the covariance matrix and not xEst. \n% H The zDim X xDim X N hypermatrix of measurement matrices such\n% that H(:,:,k)*x+w is the measurement at time k, where x is the\n% state and w is zero-mean Gaussian noise with covariance matrix\n% R(:,:,k). Alternatively, if all of the measurement matrices are\n% the same, one can just pass a single zDim X xDim matrix.\n% F An xDim X xDim X (N-1) hypermatrix of matrices. The state at\n% discrete-time k+1 is modeled as F(:,:,k) times the state at time\n% k plus zero-mean Gaussian process noise with covariance matrix\n% Q(:,:,k). Alternatively, if all of the state transition matrices\n% are the same, one can just pass a single xDim X xDim matrix.\n% Note that all of the F matrices must be invertible if kD is not\n% equal to one.\n% R The zDim X zDim X N hypermatrix of measurement covariance\n% matrices. Alternatively, if all of the measurement covariance\n% matrices are the same, one can just pass a single zDimXzDim\n% matrix.\n% kD The discrete time-step for which the covariance matrix of an\n% estimate is desired, where z(:,1) is at discrete time-step 1\n% (not 0).\n% Q The xDim X xDim X (N-1) hypermatrix of process noise covariance\n% matrices. Alternatively, if all of the process noise covariance\n% matrices are the same, one can just pass a single xDimXxDim\n% matrix. If an empty matrix is passed for Q, then the estimation\n% is performed assuming there is no process noise.\n% numMeas If an empty matrix is passed for z, then the numMeas parameter\n% must be passed indicating the number of measurements in the\n% batch. Otherwise, this parameter is\n% ignored.\n%\n%OUTPUTS: xEst The batch state estimate at step kD, unless an empty matrix\n% was passed for z, in which case xEst is empty.\n% PEst A covariance matrix estimate that goes with the state\n% estimate.\n%\n%The algorithm is an implementation of the method of Section 3.3.2 of [1]\n%for a linear dynamic model. Note that the cases in equation 28 to 32 of\n%the paper did not cover all of the possibilities, so the correct\n%generalization had to be derived from E[epsilon_{p,k}*epsilon_{q,k}'].\n%\n%REFERENCES:\n%[1] A. B. Poore, B. J. Slocumb, B. J. Suchomel, F. H. Obermeyer, S. M.\n% Herman, and S. M. Gadaleta, \"Batch maximum likelihood (ML) and maximum\n% a posteriori (MAP) estimation with process noise for tracking\n% applications,\" in Proceedings of SPIE: Signal and Data Processing of\n% Small Targets, vol. 5204, San Diego, CA, 3 Aug. 2003, pp. 188-199.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(~isempty(z))\n numMeas=size(z,2);\nend\n\nxDim=size(F,1);\nzDim=size(R,1);\n\nif(size(H,3)==1)\n HMats=repmat(H,[1,1,numMeas]);\nelse\n HMats=H;\nend\n\nif(size(F,3)==1)\n F=repmat(F,[1,1,numMeas-1]);\nend\n\nif(size(R,3)==1)\n R=repmat(R,[1,1,numMeas]);\nend\n\nif(isempty(Q))\n Q=zeros(xDim,xDim,numMeas);\nelseif(size(Q,3)==1)\n Q=repmat(Q,[1,1,numMeas-1]);\nend\n\ntransMats=getTransMats(F);\n\nWMat=zeros(zDim*numMeas,zDim*numMeas);\nfor p=1:numMeas\n pIdxMin=(p-1)*zDim+1;\n pIdxMax=p*zDim;\n pSpan=pIdxMin:pIdxMax;\n for q=1:numMeas\n qIdxMin=(q-1)*zDim+1;\n qIdxMax=q*zDim;\n qSpan=qIdxMin:qIdxMax;\n if(pkD&&q>kD)\n CumMat=zeros(xDim,xDim);\n \n for i=(kD+1):min(p,q)\n CumMat=CumMat+transMats(:,:,p,i)*Q(:,:,i-1)*transMats(:,:,q,i)';\n end\n \n WMat(pSpan,qSpan)=KDelta(p-q)*R(:,:,p)+HMats(:,:,p)*CumMat*HMats(:,:,q)';\n elseif(p==kD&&q==kD)\n WMat(pSpan,qSpan)=R(:,:,p);\n end\n end\nend\n\n%The propagated measurement matrices.\nbigH=zeros(zDim*numMeas,xDim);\nfor curMeas=1:numMeas\n idxMin=(curMeas-1)*zDim+1;\n idxMax=curMeas*zDim;\n \n bigH(idxMin:idxMax,:)=HMats(:,:,curMeas)*transMats(:,:,curMeas,kD);\nend\n\nWInv=inv(WMat);\nPEstInv=bigH'*WInv*bigH;\nPEst=inv(PEstInv);\nif(isempty(z))\n xEst=[];\nelse\n xEst=PEstInv\\bigH'*(WMat\\z(:));\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Dynamic_Estimation/Batch_and_Smoothing/batchLSLinMeasLinDyn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6024343910565594}} {"text": "function [pitch, roll, yaw] = q2att(qnb)\n q11 = qnb(1)*qnb(1); q12 = qnb(1)*qnb(2); q13 = qnb(1)*qnb(3); q14 = qnb(1)*qnb(4);\n q22 = qnb(2)*qnb(2); q23 = qnb(2)*qnb(3); q24 = qnb(2)*qnb(4); \n q33 = qnb(3)*qnb(3); q34 = qnb(3)*qnb(4);\n q44 = qnb(4)*qnb(4);\n C12=2*(q23-q14);\n C22=q11-q22+q33-q44;\n C31=2*(q24-q13); C32=2*(q34+q12); C33=q11-q22-q33+q44;\n \n pitch = asind(C32);\n roll = atan2d(-C31,C33);\n yaw = atan2d(C12,C22);\n yaw = yaw + (yaw<0)*360;\nend\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/eskf156/q2att.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.6023868000479746}} {"text": "function [fx] = evolution0bisND(x,theta,u,in)\n% 0-ToM's evolution function (without doubled hidden states)\n% function [fx] = evolution0bisND(x,theta,u,in)\n% 0-ToM is simply tracking the log-odds of P(o=1), where o is the\n% opponent's action. This variable is updated according to a Laplace-Kalman\n% filter, yielding 2 sufficient statistics, m and V. In this scheme, the\n% only evolution param (theta) is 0-ToM's prior volatity about her\n% opponent's log-odds. \n% IN:\n% - x: sufficient statistics of log-odds of P(o=1):\n% x(1)= E[log-odds]\n% x(2)= log V[log-odds] (log-scale for numerical reasons)\n% - theta: 0-ToM's prior (log-) volatity\n% - u: u(1)= last opponent's move (o)\n% - in: [useless here]\n% OUT:\n% - fx: updated sufficient statistics of log-odds of P(o=1)\n\nif isempty(u)||isnan(u(1)) % missed trial\n fx = x; % no update\nelse % trial OK\n % -- deal with superceding competition with other generative models --\n % [See, e.g., f_metaTom.m]\n try\n w = inF.metaweight;\n catch\n w = 1;\n end\n % -- learning rule --\n m0 = x(1); % current E[log-odds]\n V0 = exp(x(2)); % current V[log-odds]\n p0 = VBA_sigmoid(m0); % current estimate of P(o=1)\n volatility = exp(theta(1));\n V = 1./((1./(volatility+V0))+w*p0*(1-p0)); % updated V[log-odds]\n m = m0 + w*V*(u(1)-p0); % updated E[log-odds] (Laplace-Kalman update rule)\n % wrap-up\n fx = [VBA_sigmoid(VBA_sigmoid(m),'inverse',true);log(V)]; % for numerical purposes\nend ", "meta": {"author": "MBB-team", "repo": "VBA-toolbox", "sha": "01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414", "save_path": "github-repos/MATLAB/MBB-team-VBA-toolbox", "path": "github-repos/MATLAB/MBB-team-VBA-toolbox/VBA-toolbox-01ff63f43ef7a6473bc5e3f28dd9ffa58fcfb414/demos/_models/evolution0bisND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6023466031672517}} {"text": "% confusion_matrix(1,1) = fraction of true 1 classified as 1\n% confusion_matrix(1,2) = fraction of true 1 classified as 2\n% confusion_matrix(1,3) = fraction of true 1 classified as unknown\n% confusion_matrix(2,1) = fraction of true 2 classified as 1\n% confusion_matrix(2,2) = fraction of true 2 classified as 2\n% confusion_matrix(2,3) = fraction of true 2 classified as unknown\nfunction confusion_matrix = ComputeConfusionMatrix(hs,diff_logprob,maxdiff_logprob1,mindiff_logprob2)\n\nconfusion_matrix = nan(2,3);\nhsPr1 = diff_logprob < maxdiff_logprob1;\nhsPr2 = diff_logprob > mindiff_logprob2;\nn1 = nnz(hs==1);\nn2 = nnz(hs==2);\n\nconfusion_matrix(1,1) = nnz(hsPr1(hs==1)) / n1;\nconfusion_matrix(1,2) = nnz(hsPr2(hs==1)) / n1;\nconfusion_matrix(1,3) = 1 - confusion_matrix(1,1) - confusion_matrix(1,2);\n\nconfusion_matrix(2,1) = nnz(hsPr1(hs==2)) / n2;\nconfusion_matrix(2,2) = nnz(hsPr2(hs==2)) / n2;\nconfusion_matrix(2,3) = 1 - confusion_matrix(2,1) - confusion_matrix(2,2);\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ComputeConfusionMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6023465978103849}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Setting up advection-diffusion solver\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [C,laplacian_C] = please_Update_Adv_Diff_Concentration_Flux_Limiter_FV(C,dt,dx,dy,uX,uY,k)\n\n% C: concentration \n% dt: time-step\n% dx,dy: spatial steps in x and y, respectively\n% uX: x-Component of Velocity\n% uY: y-Component of Velocity\n% k: diffusion coefficient\n\n% Compute Fluxes (Note: these calculations could be parallalized)\nselection = 'superbee';\nFx = give_Necessary_Fluxes(C,dx,uX,'x',selection,dt); % Fluxes in x\nFy = give_Necessary_Fluxes(C,dy,uY,'y',selection,dt); % Fluxes in y\n\n% \"forward difference of fluxes in x\"\nF2x = [Fx(:,2:end) Fx(:,1)];\nF1x = [Fx(:,end) Fx(:,1:end-1)];\ndiffX = 0.5/dx*( F2x - F1x ); \n\n% \"forward differences of fluxes in y\"\nF2y = [Fy(2:end,:); Fy(1,:)];\nF1y = [Fy(end,:); Fy(1:end-1,:)];\ndiffY = 0.5/dy*( F2y - F1y );\n \ndiffY=0;\n\n% Compute 2nd Derivative Terms\nCxx = DD(C,dx,'x');\nCyy = DD(C,dy,'y');\n\n\n% Forms Laplacian\nlaplacian_C = Cxx+Cyy;\n \n% UPWIND\nC = C - dt * ( diffX + diffY ) + dt*( k*laplacian_C );\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Computes derivative based on sign of Velocity, u, using UPWIND\n% approach\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction C_z = give_Necessary_Fluxes(C,dz,uZ,string,selection,dt)\n\nC_z = zeros(size(C));\nlen = length(uZ(:,1));\nsigns = sign(uZ);\n\nif strcmp(string,'x')\n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %left side of grid\n if signs(i,1) <= 0\n r = ( C(i,2) - C(i,1) ) / ( C(i,1) - C(i,len) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,1) = uZ(i,1)*C(i,2) ;% + 0.5*abs( uZ(i,1) )*( 1 - abs( 0.5*dt*uZ(i,1)/dz ) )*phi*( C(i,2) - C(i,len) );\n else\n r = ( C(i,1) - C(i,len) ) / ( C(i,2) - C(i,1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,1) = uZ(i,1)*C(i,len) ;%+ 0.5*abs( uZ(i,1) )*( 1 - abs( 0.5*dt*uZ(i,1)/dz ) )*phi*( C(i,2) - C(i,len) );\n end\n\n %right side of grid\n if signs(len,1) <= 0\n r = ( C(i,1) - C(i,len) ) / ( C(i,len) - C(i,len-1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,len) = uZ(i,len)*C(i,1) ;% + 0.5*abs( uZ(i,len) )*( 1 - 0.5*abs( dt*uZ(i,len)/dz ) )*phi*( C(i,1) - C(i,len-1) );\n else\n r = ( C(i,len) - C(i,len-1) ) / ( C(i,1) - C(i,len) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,len) = uZ(i,len)*C(i,len-1);% + 0.5*abs( uZ(i,len) )*( 1 - 0.5*abs( dt*uZ(i,len)/dz ) )*phi*( C(i,1) - C(i,len-1) );\n end\n\n end\n %Standard Upwind \n for i=1:len\n for j=2:len-1\n if signs(i,j) <= 0\n r = ( C(i,j+1) - C(i,j) ) / ( C(i,j) - C(i,j-1) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,j) = uZ(i,j)*C(i,j+1);% + 0.5*abs( uZ(i,j) )*( 1 - 0.5*abs( dt*uZ(i,j)/dz ) )*phi*( C(i,j+1) - C(i,j-1) );\n else\n r = ( C(i,j) - C(i,j-1) ) / ( C(i,j+1) - C(i,j) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(i,j) = uZ(i,j)*C(i,j-1);% + 0.5*abs( uZ(i,j) )*( 1 - 0.5*abs( dt*uZ(i,j)/dz ) )*phi*( C(i,j+1) - C(i,j-1) );\n end\n end\n end\n\n % Ends x-Direction calculation %\n \nelseif strcmp(string,'y') \n\n %For periodicity on ends w/ UPWIND\n for i=1:len\n\n %bottom of grid\n if signs(1,i) <= 0\n r = ( C(2,i) - C(1,i) ) / ( C(1,i) - C(len,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(1,i) = uZ(1,i)*C(2,i) + 0.5*abs( uZ(1,i) )*( 1 - abs( 0.5*dt*uZ(1,i)/dz ) )*phi*( C(2,i) - C(len,i) );\n else\n r = ( C(1,i) - C(len,i) ) / ( C(2,i) - C(1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(1,i) = uZ(1,i)*C(len,i) + 0.5*abs( uZ(1,i) )*( 1 - abs( 0.5*dt*uZ(1,i)/dz ) )*phi*( C(2,i) - C(len,i) );\n end\n\n %top of grid\n if signs(len,1) <= 0\n r = ( C(1,i) - C(len,i) ) / ( C(len,i) - C(len-1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(len,i) = uZ(len,i)*C(1,i) + 0.5*abs( uZ(len,i) )*( 1 - abs( 0.5*dt*uZ(len,i)/dz ) )*phi*( C(1,i) - C(len-1,i) );\n else\n r = ( C(len,i) - C(len-1,i) ) / ( C(1,i) - C(len,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(len,i) = uZ(len,i)*C(len-1,i) + 0.5*abs( uZ(len,i) )*( 1 - abs( 0.5*dt*uZ(len,i)/dz ) )*phi*( C(1,i) - C(len-1,i) );\n end\n\n end\n \n %Standard Upwind\n for i=1:len\n for j=2:len-1\n if signs(j,i) <= 0\n r = ( C(j+1,i) - C(j,i) ) / ( C(j,i) - C(j-1,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(j,i) = uZ(j,i)*C(j+1,i) + 0.5*abs( uZ(j,i) )*( 1 - abs( 0.5*dt*uZ(j,i)/dz ) )*phi*( C(j+1,i) - C(j-1,i) );\n else\n r = ( C(j,i) - C(j-1,i) ) / ( C(j+1,i) - C(j,i) );\n phi = please_Give_Flux_Limiter(r,selection);\n C_z(j,i) = uZ(j,i)*C(j-1,i) + 0.5*abs( uZ(j,i) )*( 1 - abs( 0.5*dt*uZ(j,i)/dz ) )*phi*( C(j+1,i) - C(j-1,i) );\n end\n end\n end\n\n % Ends y-Direction calculation %\n \nelse\n \n fprintf('\\n\\n\\n ERROR IN FUNCTION FOR COMPUTING FLUX LIMITERS\\n');\n \nend\n \nclear signs; clear len;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: Finds CENTERED finite difference approximation to 2ND\n% DERIVATIVE in z direction, specified by input and 'string' \n% Note: It automatically accounts for periodicity of the domain.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction u_zz = DD(u,dz,string)\n\n% u: velocity \n% dz: spatial step in \"z\"-direction\n% string: specifies which 2ND derivative to take (to enforce periodicity)\n\nlen = length(u(:,1));\n\nif strcmp(string,'x')\n\n %For periodicity on ends\n u_zz(:,1) = ( u(:,2) - 2*u(:,1) + u(:,len) ) / (dz^2);\n u_zz(:,len)= ( u(:,1) - 2*u(:,len) + u(:,len-1) ) / (dz^2);\n\n %Standard Upwind Scheme (Centered Difference)\n for j=2:len-1\n u_zz(:,j) = ( u(:,j+1) - 2*u(:,j) + u(:,j-1) ) / (dz^2);\n end\n\nelseif strcmp(string,'y')\n\n %For periodicity on ends\n u_zz(1,:) = ( u(2,:) - 2*u(1,:) + u(len,:) ) / (dz^2);\n u_zz(len,:)= ( u(1,:) - 2*u(len,:) + u(len-1,:) ) / (dz^2);\n\n %Standard Upwind Scheme (Centered Difference)\n for j=2:len-1\n u_zz(j,:) = ( u(j+1,:) - 2*u(j,:) + u(j-1,:) ) / (dz^2);\n end\n\nelse\n \n fprintf('\\n\\n\\n ERROR IN FUNCTION DD FOR COMPUTING 2ND DERIVATIVE\\n');\n fprintf('Need to specify which desired derivative, x or y.\\n\\n\\n'); \n \nend\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes flux limiter with choice of which one\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction phi = please_Give_Flux_Limiter(r,selection)\n\nif strcmp(selection,'superbee')\n max1 = max( min(1,2*r),min(2,r) );\n phi = max(0,max1);\nelseif strcmp(selection,'vanLeer')\n phi = ( r + abs(r) ) / ( 1 + abs(r) );\nelse\n fprintf('\\n\\n');\n error('NEED TO CHOOSE AN APPROPRIATE FLUX LIMITER');\nend", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Testing/Advection_Diffusion/please_Update_Adv_Diff_Concentration_Flux_Limiter_FV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6023220883763215}} {"text": "classdef MOEADM2M_F5 < PROBLEM\n% \n% Benchmark MOP for testing MOEA/D-M2M\n\n%------------------------------- Reference --------------------------------\n% H. Liu, F. Gu, and Q. Zhang, Decomposition of a multiobjective\n% optimization problem into a number of simple multiobjective subproblems,\n% IEEE Transactions on Evolutionary Computation, 2014, 18(3): 450-455.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n t = X(:,2:end) - repmat(sin(pi/2*X(:,1)),1,size(X,2)-1);\n g = 2*abs(cos(pi*X(:,1))).*sum(-0.9*t.^2+abs(t).^0.6,2);\n PopObj(:,1) = (1+g).*X(:,1);\n PopObj(:,2) = (1+g).*(1-sqrt(X(:,1)));\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - sqrt(R(:,1));\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/MOEADM2M_F5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6023220126035466}} {"text": "% Count the number of self-loops in the graph\n%\n% INPUT: adjacency matrix, nxn\n% OUTPUT: integer, number of self-loops\n%\n% Note: in the adjacency matrix representation loops appear as non-zeros on the diagonal\n% GB: last updated, Sep 20 2012\n\nfunction sl=selfLoops(adj)\n\nsl=sum(diag(adj));", "meta": {"author": "aeolianine", "repo": "octave-networks-toolbox", "sha": "e70f79eb62a54ef96934d900830f9177caf732c9", "save_path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox", "path": "github-repos/MATLAB/aeolianine-octave-networks-toolbox/octave-networks-toolbox-e70f79eb62a54ef96934d900830f9177caf732c9/selfLoops.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.602321994162399}} {"text": "function [out] = saturation_8(p1,p2,S,Smax,In)\n%saturation_8 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Saturation excess flow from a store with different degrees \n% of saturation (min-max linear variant)\n% Constraints: -\n% @(Inputs): p1 - minimum fraction contributing area [-]\n% p2 - maximum fraction contributing area [-]\n% S - current storage [mm]\n% Smax - maximum contributing storage [mm]\n% In - incoming flux [mm/d]\n\nout = (p1+(p2-p1)*S/Smax)*In;\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/saturation_8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256631249078, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6022622745580916}} {"text": "function M = getmassmat3(node,elem2dof,volume,type,K)\n%% GETMASSMAT Get mass matrix of the finite element space\n%\n% M = GETMASSMAT(node,elem2dof,volume,type,K) get mass matrix of the finite element\n% space specified by elemType. \n%\n% The type can be: \n% - 'P1': full mass matrix for P1 element\n% - 'lump': lumped mass matrix for P1 element\n\nN = size(node,1);\nNT = length(volume);\nNdof = double(max(elem2dof(:)));\n\n%% Coefficients and default type\nif ~exist('type','var'), type = 'P1'; end\nif ~exist('K','var'), K = []; end\n\n%% Assembling\nn = size(elem2dof,2);\nswitch n\n case 4 % P1 element\n if strcmp(type,'lump')\n %% Assemble the mass matrix by the mass lumping\n M = accumarray([elem2dof(:,1);elem2dof(:,2);elem2dof(:,3);elem2dof(:,4)],...\n [volume;volume;volume;volume]/4,[N,1]); \n if exist('K','var') && ~isempty(K) && ~isnumeric(K) % K is a function\n M = K(node).*M;\n elseif exist('K','var') && ~isempty(K) && isnumeric(K) && size(K,1) == N \n M = K.*M;\n end \n M = spdiags(M,0,N,N); \n else\n %% Assemble the full mass matrix\n if exist('K','var') && ~isempty(K) && ~isnumeric(K) % K is a function\n center = (node(elem2dof(:,1),:) + node(elem2dof(:,2),:) + ...\n node(elem2dof(:,3),:) + node(elem2dof(:,4),:))/4;\n volume = K(center).*volume;\n elseif exist('K','var') && ~isempty(K) && isnumeric(K) && size(K,1) == NT \n volume = K.*volume;\n end \n M = sparse(N,N);\n for i = 1:4\n for j = i:4\n ii = double(elem2dof(:,i));\n jj = double(elem2dof(:,j));\n if (j==i)\n M = M + sparse(ii,jj,volume/10,N,N);\n else\n M = M + sparse([ii;jj],[jj;ii],[volume/20; volume/20],N,N); \n end \n end\n end \n end\n case 10 % P2 element\n %% Assemble the full mass matrix using nodal basis\n % indexing follows Poisson3P2\n [lambda, w] = quadpts3(2);\n nQuad = size(lambda,1);\n ii = zeros(55*NT,1); % 55: # of upper triangular entries\n jj = zeros(55*NT,1); \n sM = zeros(55*NT,1);\n phi(:,1) = lambda(:,1).*(2*lambda(:,1)-1);\n phi(:,2) = lambda(:,2).*(2*lambda(:,2)-1);\n phi(:,3) = lambda(:,3).*(2*lambda(:,3)-1);\n phi(:,4) = lambda(:,4).*(2*lambda(:,4)-1);\n phi(:,5) = 4*lambda(:,1).*lambda(:,2);\n phi(:,6) = 4*lambda(:,1).*lambda(:,3);\n phi(:,7) = 4*lambda(:,1).*lambda(:,4);\n phi(:,8) = 4*lambda(:,2).*lambda(:,3);\n phi(:,9) = 4*lambda(:,2).*lambda(:,4);\n phi(:,10)= 4*lambda(:,3).*lambda(:,4);\n \n index = 0;\n for i = 1:10\n for j = i:10\n Mij = 0;\n for p = 1:nQuad; Mij = Mij + w(p)*phi(p,i).*phi(p,j); end\n Mij = Mij.*volume;\n ii(index+1:index+NT) = double(elem2dof(:,i));\n jj(index+1:index+NT) = double(elem2dof(:,j));\n sM(index+1:index+NT) = Mij;\n index = index + NT;\n end\n end\n diagIdx = (ii == jj); upperIdx = ~diagIdx;\n M = sparse(ii(diagIdx),jj(diagIdx),sM(diagIdx),Ndof,Ndof);\n MU = sparse(ii(upperIdx),jj(upperIdx),sM(upperIdx),Ndof,Ndof);\n M = M + MU + MU';\n \nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getmassmat3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6022622597925992}} {"text": "function [tfr,rtfr,hat] = tfrrpwv(x,t,N,h,trace);\n%TFRRPWV Reassigned pseudo Wigner-Ville distribution.\n%\t[TFR,RTFR,HAT] = TFRRPWV(X,T,N,H,TRACE) \n%\tcomputes the pseudo Wigner-Ville distribution\n%\tand its reassigned version.\n% \n%\tX : analysed signal,\n%\tT : the time instant(s) (default : 1:length(X)).\n%\tN : number of frequency bins (default : length(X)).\n%\tH : frequency smoothing window, H(0) being forced to 1\n%\t (default : Hamming(N/4)).\n%\tTRACE : if nonzero, the progression of the algorithm is shown\n%\t (default : 0).\n%\tTFR, : time-frequency representation and its reassigned\n%\tRTFR version. When called without output arguments, \n%\t TFRRPWV runs TFRQVIEW.\n%\tHAT : Complex matrix of the reassignment vectors.\n%\n%\tExample:\n%\t sig=fmlin(128,0.1,0.4); t=1:2:128;\n%\t h=tftb_window(17,'Kaiser'); tfrrpwv(sig,t,64,h,1);\n%\n%\tSee also all the time-frequency representations listed in\n%\t the file CONTENTS (TFR*)\n\n%\tF. Auger, May-July 1994, July 1995.\n%\tCopyright (c) 1996 by CNRS (France).\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 St, Fifth Floor, Boston, MA 02110-1301 USA\n\nif (nargin == 0),\n error('At least 1 parameter required');\nend;\n[xrow,xcol] = size(x);\nif (nargin < 1),\n error('At least 1 parameter is required');\nelseif (nargin <= 2),\n N=xrow;\nend;\n\nhlength=floor(N/4);\nif (rem(hlength,2)==0),\n hlength=hlength+1;\nend;\n\nif (nargin == 1),\n t=1:xrow; h = tftb_window(hlength); trace=0;\nelseif (nargin == 2)|(nargin == 3),\n h = tftb_window(hlength); trace=0;\nelseif (nargin == 4),\n trace = 0;\nend;\n\nif (N<0),\n error('N must be greater than zero');\nend;\n[trow,tcol] = size(t);\nif (xcol~=1),\n error('X must have only one column');\nelseif (trow~=1),\n error('T must only have one row'); \nelseif (2^nextpow2(N)~=N),\n fprintf('For a faster computation, N should be a power of two\\n');\nend; \n\n[hrow,hcol]=size(h); Lh=(hrow-1)/2; h=h/h(Lh+1);\nif (hcol~=1)|(rem(hrow,2)==0),\n error('H must be a smoothing window with odd length');\nend;\n\nif (tcol==1),\n Dt=1; \nelse\n Deltat=t(2:tcol)-t(1:tcol-1); \n Mini=min(Deltat); Maxi=max(Deltat);\n if (Mini~=Maxi),\n error('The time instants must be regularly sampled.');\n else\n Dt=Mini;\n end;\n clear Deltat Mini Maxi;\nend;\n\ntfr= zeros(N,tcol); tf2= zeros(N,tcol);\nif trace, disp('Pseudo Wigner-Ville distribution'); end;\nDh=dwindow(h);\nfor icol=1:tcol,\n ti= t(icol); taumax=min([ti-1,xrow-ti,round(N/2)-1,Lh]);\n tau=-taumax:taumax; indices= rem(N+tau,N)+1;\n if trace, disprog(icol,tcol,10); end;\n tfr(indices,icol)= h(Lh+1+tau).*x(ti+tau).*conj(x(ti-tau));\n tf2(indices,icol)=Dh(Lh+1+tau).*x(ti+tau).*conj(x(ti-tau));\n tau=round(N/2); \n if (ti<=xrow-tau)&(ti>=tau+1)&(tau<=Lh),\n tfr(tau+1,icol) = 0.5 * ( h(Lh+1+tau) * x(ti+tau,1) * conj(x(ti-tau,xcol)) + ...\n h(Lh+1-tau) * x(ti-tau,1) * conj(x(ti+tau,xcol))) ;\n tf2(tau+1,icol) = 0.5 * (Dh(Lh+1+tau) * x(ti+tau,1) * conj(x(ti-tau,xcol)) + ...\n Dh(Lh+1-tau) * x(ti-tau,1) * conj(x(ti+tau,xcol))) ;\n end;\nend ;\ntfr= real(fft(tfr)); \ntf2=imag(fft(tf2));\ntfr=tfr(:);tf2=tf2(:);\navoid_warn=find(tfr~=0);\ntf2(avoid_warn)=round(N*tf2(avoid_warn)./tfr(avoid_warn)/(2.0*pi)); \n%tf2= round(N*imag(fft(tf2))./tfr/(2.0*pi)); \nif trace, fprintf ('\\nreassignment: \\n'); end;\ntfr=reshape(tfr,N,tcol);\ntf2=reshape(tf2,N,tcol);\n\nrtfr= zeros(N,tcol); \nEx=mean(abs(x(min(t):max(t))).^2); Threshold=1.0e-6*Ex;\nfor icol=1:tcol,\n if trace, disprog(icol,tcol,10); end;\n for jcol=1:N,\n if abs(tfr(jcol,icol))>Threshold,\n jcolhat= jcol - tf2(jcol,icol);\n jcolhat=rem(rem(jcolhat-1,N)+N,N)+1;\n rtfr(jcolhat,icol)=rtfr(jcolhat,icol) + tfr(jcol,icol) ;\n tf2(jcol,icol)=jcolhat;\n else \n tf2(jcol,icol)=inf;\n rtfr(jcol,icol)=rtfr(jcol,icol) + tfr(jcol,icol) ;\n end;\n end;\nend;\n\nif trace, fprintf('\\n'); end;\nif (nargout==0),\n TFTBcontinue=1;\n while (TFTBcontinue==1),\n choice=menu ('Choose the representation:',...\n 'stop',...\n 'pseudo Wigner-Ville distribution',...\n 'reassigned pseudo Wigner-Ville distribution');\n if (choice==1), TFTBcontinue=0;\n elseif (choice==2), \n tfrqview(tfr,x,t,'tfrpwv',h);\n elseif (choice==3),\n tfrqview(rtfr,x,t,'tfrrpwv',h);\n end;\n end;\nelseif (nargout>2),\n hat=tf2;\nend;\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/mfiles/tfrrpwv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6022622546847973}} {"text": "function c = upc_check_digit ( p, l, r )\n\n%*****************************************************************************80\n%\n%% UPC_CHECK_DIGIT returns the check digit of a UPC.\n%\n% Discussion:\n%\n% UPC stands for Universal Price Code.\n%\n% A full UPC is a string of 12 digits, in groups of size 1, 5, 5, and 1,\n% of the form P-LLLLL-RRRRR-C, where:\n%\n% P is the one-digit product type code.\n% L is the five-digit manufacturer code.\n% R is the five_digit product code\n% C is the check digit.\n%\n% Example:\n%\n% 0-72890-00011-8\n% 0-12345-67890-5\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer P, the one-digit product type code.\n%\n% Input, integer L, the five-digit manufacturer code.\n%\n% Input, integer R, the five-digit product code.\n%\n% Output, integer C, the check digit.\n%\n if ( p < 0 | 9 < p )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UPC_CHECK_DIGIT - Fatal error!\\n' );\n fprintf ( 1, ' P < 0 or 9 < P!\\n' );\n error ( 'UPC_CHECK_DIGIT - Fatal error!' );\n end\n\n if ( l < 0 | 99999 < l )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UPC_CHECK_DIGIT - Fatal error!\\n' );\n fprintf ( 1, ' L < 0 or 99999 < L!\\n' );\n error ( 'UPC_CHECK_DIGIT - Fatal error!' );\n end\n\n if ( r < 0 | 99999 < r )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UPC_CHECK_DIGIT - Fatal error!\\n' );\n fprintf ( 1, ' R < 0 or 99999 < R!\\n' );\n error ( 'UPC_CHECK_DIGIT - Fatal error!' );\n end\n\n lc = i4_to_digits_decimal ( l, 5 );\n rc = i4_to_digits_decimal ( r, 5 );\n\n c = ( p + lc(2) + lc(4) + rc(1) + rc(3) + rc(5) ) * 3 ...\n + lc(1) + lc(3) + lc(5) + rc(2) + rc(4);\n\n c = mod ( c, 10 );\n\n c = mod ( 10 - c, 10 );\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/subpak/upc_check_digit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.6021304639735552}} {"text": "function phiFaceAverage = upwindMean2D(phi, u)\n% This function gets the value of the field variable phi defined\n% over the MeshStructure and calculates the upwind average on\n% the cell faces, based on the direction of the velocity vector for a uniform mesh.\n%\n% SYNOPSIS:\n% phiFaceAverage = upwindMean2D(phi, u)\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% Written by Ali A. Eftekhari\n% See the license file\n\n% extract the velocity data\n% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]\nux = u.xvalue;\nuy = u.yvalue;\n\n% check the size of the variable and the mesh dimension\nNxy = phi.domain.dims;\nNx = Nxy(1); Ny = Nxy(2);\n\n% assign to a temp variable for boundary corrections\nphi_tmp = phi.value;\n\n% correct the value of phi at the boundary (calculation trick)\n% assign the value of the left boundary to the left ghost cells\nphi_tmp(1,:) = (phi.value(1,:)+phi.value(2,:))/2;\n% assign the value of the right boundary to the right ghost cells\nphi_tmp(end,:) = (phi.value(end,:)+phi.value(end-1,:))/2;\n% assign the value of the bottom boundary to the bottom ghost cells\nphi_tmp(:,1) = (phi.value(:,1)+phi.value(:,2))/2;\n% assign the value of the top boundary to the top ghost cells\nphi_tmp(:,end) = (phi.value(:,end)+phi.value(:,end-1))/2;\n\n% calculate the average value\nxvalue = (ux>0).*phi_tmp(1:Nx+1,2:Ny+1)+ ...\n (ux<0).*phi_tmp(2:Nx+2,2:Ny+1)+ ...\n 0.5*(ux==0).*(phi.value(1:Nx+1,2:Ny+1)+phi.value(2:Nx+2,2:Ny+1));\nyvalue = (uy>0).*phi_tmp(2:Nx+1,1:Ny+1)+ ...\n (uy<0).*phi_tmp(2:Nx+1,2:Ny+2)+ ...\n 0.5*(uy==0).*(phi.value(2:Nx+1,1:Ny+1)+phi.value(2:Nx+1,2:Ny+2));\nphiFaceAverage=FaceVariable(phi.domain, xvalue, yvalue, []);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Utilities/upwindMean2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519378, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6021304568616229}} {"text": "function fem1d_bvp_quadratic_test04 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_BVP_QUADRATIC_TEST04 carries out test case #4.\n%\n% Discussion:\n%\n% Use A4, C4, F4, EXACT4, EXACT_UX4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dianne O'Leary,\n% Scientific Computing with Case Studies,\n% SIAM, 2008,\n% ISBN13: 978-0-898716-66-5,\n% LC: QA401.O44.\n%\n n = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_BVP_QUADRATIC_TEST04\\n' );\n fprintf ( 1, ' Solve -( A(x) U''(x) )'' + C(x) U(x) = F(x)\\n' );\n fprintf ( 1, ' for 0 < x < 1, with U(0) = U(1) = 0.\\n' );\n fprintf ( 1, ' A4(X) = 1.0 + X * X\\n' );\n fprintf ( 1, ' C4(X) = 0.0\\n' );\n fprintf ( 1, ' F4(X) = ( X + 3 X^2 + 5 X^3 + X^4 ) * exp ( X )\\n' );\n fprintf ( 1, ' U4(X) = X * ( 1 - X ) * exp ( X )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', n );\n%\n% Geometry definitions.\n%\n x_first = 0.0;\n x_last = 1.0;\n x = linspace ( x_first, x_last, n );\n x = x(:);\n\n u = fem1d_bvp_quadratic ( n, @a4, @c4, @f4, x );\n\n uexact = exact4 ( x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X U Uexact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, ' %4d %8f %8f %8f %8e\\n', ...\n i, x(i), u(i), uexact(i), abs ( u(i) - uexact(i) ) );\n end\n\n e1 = l1_error ( n, x, u, @exact4 );\n e2 = l2_error_quadratic ( n, x, u, @exact4 );\n h1s = h1s_error_quadratic ( n, x, u, @exact_ux4 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' l1 norm of error = %g\\n', e1 );\n fprintf ( 1, ' L2 norm of error = %g\\n', e2 );\n fprintf ( 1, ' Seminorm of error = %g\\n', h1s );\n\n return\nend\nfunction value = a4 ( x )\n\n%*****************************************************************************80\n%\n%% A4 evaluates A function #4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of A(X).\n%\n value = 1.0 + x .* x;\n\n return\nend\nfunction value = c4 ( x )\n\n%*****************************************************************************80\n%\n%% C4 evaluates C function #4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of C(X).\n%\n value = 0.0;\n\n return\nend\nfunction value = exact4 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT4 evaluates exact solution #4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of U(X).\n%\n value = x .* ( 1.0 - x ) .* exp ( x );\n\n return\nend\nfunction value = exact_ux4 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT_UX4 evaluates the derivative of exact solution #4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX(X).\n%\n value = ( 1.0 - x - x .* x ) .* exp ( x );\n\n return\nend\nfunction value = f4 ( x )\n\n%*****************************************************************************80\n%\n%% F4 evaluates right hand side function #4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n value = ( x + 3.0 * x.^2 + 5.0 * x.^3 + x.^4 ) .* exp ( x );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_bvp_quadratic/fem1d_bvp_quadratic_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6021304416818388}} {"text": "function b = r83_to_r8ge ( n, a )\n\n%*****************************************************************************80\n%\n%% R83_TO_R8GE copies an R83 matrix to a R8GE matrix.\n%\n% Discussion:\n%\n% The R83 storage format is used for a tridiagonal matrix.\n% The superdiagonal is stored in entries (1,2:N), the diagonal in\n% entries (2,1:N), and the subdiagonal in (3,1:N-1). Thus, the\n% original matrix is \"collapsed\" vertically into the array.\n%\n% Example:\n%\n% Here is how a R83 matrix of order 5 would be stored:\n%\n% * A12 A23 A34 A45\n% A11 A22 A33 A44 A55\n% A21 A32 A43 A54 *\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be at least 2.\n%\n% Input, real A(3,N), the R83 matrix.\n%\n% Output, real B(N,N), the R8GE matrix.\n%\n for i = 1 : n\n for j = 1 : n\n\n if ( j == i-1 )\n b(i,j) = a(3,j);\n elseif ( j == i )\n b(i,j) = a(2,j);\n elseif ( j == i+1 )\n b(i,j) = a(1,j);\n else\n b(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r83_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6020835529348569}} {"text": "function errplotl(sol,eldata,ev,xy,x,y,fig)\n%errplotl plots solution and error estimate on L-shaped domain\n% errplotl(sol,eldata,ev,xy,x,y,fig)\n% input\n% sol nodal solution vector \n% eldata element error vector\n% ev element mapping matrix\n% xy vertex coordinate vector \n% x vector of x-axis interpolation points\n% y vector of y-axis interpolation points\n% fig figure number\n%\n% IFISS function: DJS; 5 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nfprintf('plotting solution and estimated errors... ')\n% interpolate to a cartesian product mesh\n[X,Y]=meshgrid(x,y);\nxysol = griddata(xy(:,1),xy(:,2),sol,X,Y);\n[II,JJ]=find(X<0 & Y<0); xysol(II,JJ)=nan;\nfigure(fig)\nsubplot(221),contour(X,Y,xysol,20),axis('square')\naxis('off'), ellx, title('Finite Element Solution')\nsubplot(222),mesh(X,Y,xysol),axis('square')\nview(330,30)\n%%\nxx=xy(:,1); yy=xy(:,2);\nnel=length(eldata);\n% loop over elements \nfor ielem = 1:nel\nxl = xx(ev(ielem,:));\nyl = yy(ev(ielem,:)); \nxc(ielem,1) = 0.25*sum(xl);\nxc(ielem,2) = 0.25*sum(yl);\nend\n%\n% interpolate to a cartesian product mesh\nx=0.5*(x(1:end-1)+x(2:end));\ny=0.5*(y(1:end-1)+y(2:end));\n[X,Y]=meshgrid(x,y);\nxysol = griddata(xc(:,1),xc(:,2),eldata,X,Y);\n[II,JJ]=find(X<0 & Y<0); xysol(II,JJ)=nan;\nsubplot(223),contour(X,Y,xysol,15),axis('square')\naxis('off'), ellx, title('Estimated Error')\nsubplot(224),mesh(X,Y,xysol),axis('square')\nview(330,30)\nsubplot(111)\nfprintf('done\\n')\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/graphs/errplotl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6020324563164936}} {"text": "classdef MOEADDE_F4 < PROBLEM\n% \n% Benchmark MOP for testing MOEA/D-DE\n\n%------------------------------- Reference --------------------------------\n% H. Li and Q. Zhang, Multiobjective optimization problems with complicated\n% Pareto sets, MOEA/D and NSGA-II, IEEE Transactions on Evolutionary\n% Computation, 2009, 13(2): 284-302.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 30; end\n obj.lower = [0,-ones(1,obj.D-1)];\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n J1 = 3 : 2 : obj.D;\n J2 = 2 : 2 : obj.D;\n PopObj(:,1) = X(:,1) + 2*mean((X(:,J1)-0.8*repmat(X(:,1),1,length(J1)).*cos(repmat(2*pi*X(:,1),1,length(J1))+repmat(J1*pi/obj.D/3,size(X,1),1))).^2,2);\n PopObj(:,2) = 1-sqrt(X(:,1)) + 2*mean((X(:,J2)-0.8*repmat(X(:,1),1,length(J2)).*sin(repmat(6*pi*X(:,1),1,length(J2))+repmat(J2*pi/obj.D,size(X,1),1))).^2,2);\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = 1 - R(:,1).^0.5;\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/MOEADDE_F4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6020324525153503}} {"text": "function linpack_s_test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests SGBFA and SGBSL.\n%\n% Discussion:\n%\n% SGBFA and SGBSL are for general banded matrices.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n n = 100;\n ml = 25;\n mu = 25;\n lda = 2*ml+mu+1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST07\\n' );\n fprintf ( 1, ' For a general banded matrix,\\n' );\n fprintf ( 1, ' SGBFA factors the matrix,\\n' );\n fprintf ( 1, ' SGBSL solves a factored linear system.\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Assign values to matrix A and right hand side B.\n%\n% We want to try a problem with a significant bandwidth.\n%\n m = ml + mu + 1;\n fprintf ( 1, ' The bandwidth of the matrix is %d\\n', m );\n\n for j = 1 : n\n\n ilo = max ( 1, j - mu );\n ihi = min ( n, j + ml );\n\n temp = 0.0;\n for i = ilo : ihi\n a(i-j+m,j) = -1.0;\n temp = temp - 1.0;\n end\n\n temp = temp + 1.0;\n a(m,j) = 4.0 - temp;\n b(j) = 4.0;\n\n end\n%\n% Force B to be a column vector.\n%\n b = b';\n%\n% Factor the matrix A.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Factor the matrix.\\n' );\n\n [ a, ipivot, info ] = sgbfa ( a, lda, n, ml, mu );\n\n if ( info ~= 0 )\n fprintf ( 1, ' Error! SGBFA returns INFO = %d\\n', info );\n return\n end\n%\n% Call SGBSL to solve the linear system.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the linear system.\\n' );\n\n job = 0;\n b = sgbsl ( a, lda, n, ml, mu, ipivot, b, job );\n%\n% Print the results.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The first and last 5 entries of the solution:\\n' );\n fprintf ( 1, ' (All should be 1):\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n if ( i <= 5 | n-5 < i )\n fprintf ( 1, ' %6d %14f\\n', i, b(i) );\n end\n if ( i == 5 )\n fprintf ( 1, ' ...... ..............\\n' );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_s/linpack_s_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6020324443281982}} {"text": "function [ fplanes,cplanes,info ] = tfjigsawsep( f, varargin )\n%TFJIGSAWSEP Time frequency jigsaw puzzle tonal-transient separation\n% Usage: fplanes = tfjigsawsep(f);\n% fplanes = tfjigsawsep(f,r1,r2);\n% fplanes = tfjigsawsep(f,r1,r2,p);\n% [fplanes, cplanes, info] = tfjigsawsep(...);\n%\n% Input parameters:\n% f : Input signal\n% r1 : Significance level of the tonal layer refered to\n% a white noise reference\n% r2 : Same for the transient layer\n% p : Proportionfactor of the supertilesizes relative \n% to the time-, and frequency stepsize \n% \n% Output parameters:\n% fplanes : signallength-by-3 array containing the 3 produced\n% layers, tonal in fplanes(:,1), transient in\n% fplanes(:,2) and the noisy residual in fplanes(:,3).\n% cplanes : 3-by-1 cellarray containing the Gabor coefficients\n% for the individual layers\n%\n% `tfjigsawsep(f)` applies the separation algorithm on the input signal *f*\n% and returns the tonal, the transient and the residual parts.\n% The following default values are used, *r1=r2=0.95*, *p=4* and for the \n% 3 Gabor systems:\n% \n% \"Tonal\" system: g1 = {'hann',4096}; a1 = 512; M1 = 4096;\n% \n% \"Transient\" system: g2 = {'hann',256}; a2 = 32; M2 = 256;\n%\n% \"Residual\" system: g3 = {'hann',2048}; a3 = 512; M3 = 2048;\n% \n% `tfjigsawsep(f,r1,r2)` works as before, but allows changing threshold\n% parameters *r1* and *r2*. Good values are in range [0.85,0.95]. \n% *t2* sometimes has to be chosen larger (~ 1.05), eg. for \n% percussions in music signals.\n%\n% `tfjigsawsep(f,r1,r2,p)` (recommended) additionally allows changing the\n% size of the supertiles to a1*p in timesamples and b2*p in\n% frequencysamples. The choice of this particular proportion is\n% reasonable since it provides equal numbers of coefficients of the two\n% Gabor systems in each supertile. Good values are in the range of [1,10],\n% but it depends very much on the type of signal.\n% E.g. for speech signals, higher values yield better results. \n%\n% `[fplanes, cplanes, info] = tfjigsawsep(...)` additionally returns\n% a 3 element cell array *cplanes* containing |dgtreal| coefficients\n% of the respective separated layers and a structure *info*, with the\n% parameters used in the algorithm. The relationship between *fplanes*\n% and *cplanes* is the following:\n\n% Additional parameters:\n% ----------------------\n%\n% The function accepts the following flags:\n%\n% 'ver2' Uses the second version of the algorithm.\n%\n% 'plot' Plots the separated waveforms and the coefficients.\n%\n% 'verbose' Information about the boundary condition.\n%\n%\n% and the following key-value pairs:\n% \n% 'wintype' Requested windowtype\n%\n% 'winsize1' and 'winsize2' Windowlengths\n%\n% 'a1' and 'a2' Time stepsizes\n%\n% 'M1' and 'M2' Number of frequency channels\n%\n% 'T' and 'F' Supertile sizes in samples manually - alternative to p!\n%\n% 'maxit' Maximum number of iterations. The default value is 15.\n%\n% Algorithm:\n% ----------\n%\n% The algorithm is based on [1]. It transforms a signal into a two-windowed\n% Gabor expansion such that one wide window shall lead to a high frequency\n% resolution (tonal layer is represented well) and a narrow one to a high\n% time resolution (transient layer is repr. well). The resulting Gabor\n% coefficients are respectively considered within rectangular 'supertiles'\n% in the time-frequency plane. An entropy criterion chooses those tiles\n% respectively, where tonal and transient parts of the signal are\n% represented better and are below a estimated threshold. The rest is set\n% to zero. The leftover Gabor coefficients are transformed back and\n% subtracted from the original signal. By applying this procedure\n% iteratively on the residual, tonal and transient layers emerge.\n%\n% Examples:\n% ---------\n% \n% The following example shows the basic usage of the function:::\n% \n% % Load the glockenspiel test signal and add some noise\n% [f,fs] = gspi; f = f + 0.001*randn(size(f));\n% % Setup the parameters\n% p = 2; r1 = 0.92; r2 = 0.93;\n% [fplanes,cplanes,info] = tfjigsawsep(f,r1,r2,p,'plot','ver2','fs',fs);\n% \n% See also: dgtreal plottfjigsawsep\n% \n% References: jato07\n\n%AUTHOR: Daniel Haider, 2017 \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Remarks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The residual condition is computed very heuristically, designing it %\n% more flexible would be a nice improvement of the algorithm. %\n% It would also be useful to provide parameter settings for specific %\n% types of signals (ie. speech, music,...) . %\n% %\n% Version 1 of the algorithm (default) works particularly well for %\n% speech signals, but also for depicting the transient layer %\n% (eg. percussive elements) nicely in musical signals. %\n% Version 2 works particularly well for depicting a nice tonal layer. %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n[f,Ls,W,wasrow,remembershape]=comp_sigreshape_pre(f,upper(mfilename),0);\n\nif W>1\n error('%s: Multichannel inputs are not supported.',upper(mfilename));\nend\n\ndefinput.keyvals.r1 = [];\ndefinput.keyvals.r2 = [];\ndefinput.keyvals.p = [];\ndefinput.keyvals.T = [];\ndefinput.keyvals.F = [];\ndefinput.keyvals.wintype = 'hann';\ndefinput.keyvals.winsize1 = 4096;\ndefinput.keyvals.a1 = 512;\ndefinput.keyvals.M1 = 4096;\ndefinput.keyvals.winsize2 = 512;\ndefinput.keyvals.a2 = 64;\ndefinput.keyvals.M2 = 512;\ndefinput.keyvals.maxit = 15;\ndefinput.keyvals.fs = [];\ndefinput.flags.algver = {'ver1','ver2'};\ndefinput.flags.plot = {'noplot','plot'};\ndefinput.flags.verbose = {'noverbose','verbose'};\n[flags,kv] = ltfatarghelper({'r1','r2','p','T','F','wintype','winsize1','a1','M1','winsize2','a2','M2'},definput,varargin);\n\n% significance level\nr1 = kv.r1;\nr2 = kv.r2;\n% Gabor system settings\nwintype = kv.wintype;\nwinsize1 = kv.winsize1;\na1 = kv.a1;\nM1 = kv.M1;\nwinsize2 = kv.winsize2;\na2 = kv.a2;\nM2 = kv.M2;\n% supertile sizes\nif isempty(kv.T) && isempty(kv.F)\n if isempty(kv.p)\n p = 4;\n else\n p = kv.p;\n end\n T = a1*p;\n F = dgtlength(Ls,a2,M2)/M2*p;\nelseif isempty(kv.p)\n T = kv.T;\n F = kv.F;\nelse\n error('%s: Use EITHER the proportional setting OR set T and F manually.',upper(mfilename));\nend\n\nif winsize1 < winsize2\n error('%s: The tonal system uses a shorter window than the transient system!',upper(mfilename));\nend\n\n% why this and not setting the kv on top?\nif xor(isempty(r1),isempty(r2))\n error('%s: Both r1 and r2 must be defined.',upper(mfilename));\nelse\n if isempty(r1), r1 = 0.95; end\n if isempty(r2), r2 = 0.95; end\nend \n\n% windows\ng1 = {wintype,winsize1};\ng2 = {wintype,winsize2};\n\nL1 = dgtlength(Ls,a1,M1);\nL2 = dgtlength(Ls,a2,M2);\nb1 = L1/M1;\nb2 = L2/M2;\n\ncomplainif_notposint(T,'T',mfilename);\nif ~( T < min([L1,L2]) )\n error('%s: Supertile length must be smaller than the signal length [%i]',...\n upper(mfilename),min([L1,L2]));\nelseif ~( F < min([L1/2+1,L2/2+1]) )\n error('%s: Supertile height must be smaller than the frequency range [%i]',...\n upper(mfilename),min([L1/2+1,L2/2+1]));\nelseif ~( T > max([a1,a1]) )\n error('%s: Supertile length must be larger than the time stepsizes [%i]',...\n upper(mfilename),max([a1,a1]));\nelseif ~( F > max([b1,b2]) )\n error('%s: Supertile height must be larger than the frequency stepsizes [%i]',...\n upper(mfilename),max([b1,b2]));\nend\n\n% entropy reference from noise signal\n% thresholds tau1,tau2 for tonal resp. transient layer are chosen to have\n% a certain significance with respect to the estimated reference\n[ref1,ref2] = noisest(Ls,g1,g2,a1,a2,M1,M2,T,F);\ntau1 = ref1*r1;\ntau2 = ref2*r2;\n\n% initialization of residual, layers, min and max number of iterations\n% and epsilon, the upper limit for the residual condition, which is\n% computed at the kmin-th iteration\n% R = postpad(f,L);\nR = f;\nl1 = zeros(Ls,1);\nl2 = zeros(Ls,1);\nk = 1;\nkmin = 5;\nkmax = kv.maxit;\nepsilon = 0;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%% main loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% runs until all values in R are below epsilon to exclude single peaks \nwhile all(abs(R) < epsilon) ~= 1\n\n switch flags.algver\n case 'ver1'\n [x1,x2]=jigsaw1(R,g1,g2,a1,a2,M1,M2,T,F,tau1,tau2);\n case 'ver2'\n [x1,x2]=jigsaw2(R,g1,g2,a1,a2,M1,M2,T,F,tau1,tau2);\n end\n \n % residual parts of the signal\n R = R-x1-x2;\n l1 = l1+x1;\n l2 = l2+x2;\n \n if k == kmax\n break\n end\n \n if k == kmin\n % epsilon is computed as upper limit, corresponding to\n % an empirical p-quantile\n epsilon = sort(abs(R),'ascend');\n epsilon = 5/2*epsilon(round(0.998*numel(epsilon)));\n if flags.do_verbose\n disp(['The current maximum in the residual is ',num2str(max(abs(R)))])\n disp(['An upper bound is estimated to be ',num2str(epsilon)])\n end\n end\n \n k = k+1;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif flags.do_verbose\n disp('max. number of iteration reached: condition for residual is not fulfilled!')\n disp('Try to increase t2 slightly or change the size of the supertiles.')\nend\n\n% fplanes as Ls-by-3 array containing the layers\nfplanes = [l1,l2,R];\nfplanes = postpad(fplanes,Ls);\n\n% info structure\ninfo.g1 = {wintype, winsize1};\ninfo.g2 = {wintype, winsize2};\ninfo.g3 = {wintype, 2048};\ninfo.M1 = M1;\ninfo.M2 = M2;\ninfo.M3 = 2048;\ninfo.a1 = a1;\ninfo.a2 = a2;\ninfo.a3 = 512;\ninfo.supertilesizes = [F,T];\ninfo.noiseentropy_tonal = ref1;\ninfo.threshold_tonal = tau1;\ninfo.noiseentropy_transient = ref2;\ninfo.threshold_transient = tau2;\n\n% cplanes as 3-by-1 cell array containing\n% the gabor coefficients corresp. to the layers\nif nargout > 1 || flags.do_plot\n cplanes = cell(3,1);\n cplanes{1} = dgtreal(l1,g1,a1,M1);\n cplanes{2} = dgtreal(l2,g2,a2,M2);\n cplanes{3} = dgtreal(R,info.g3,info.a3,info.M3);\nend\n\n% option for plots\nif flags.do_plot\n plottfjigsawsep(fplanes,cplanes,info,'fs',kv.fs,'showbuttons','equalyrange');\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%% compiling functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ r ] = renyi( t,alpha )\n\n% computes the Renyi entropy for an array\n% yields high values for peaky data and\n% low values for almost constant\n\nif isempty(t)\n r = inf;\nelseif norm(t) == 0\n r = inf;\nelse\n switch nargin\n case 1\n alpha = 2.4;\n r = (1/(1-alpha))*log2(sum(sum(abs(t).^(2*alpha)))*(sum(sum(abs(t).^2)).^(-alpha)));\n case 2\n if alpha <= 0 || alpha == 1\n error('alpha must be chosen positive and unequal to 1.');\n else\n r = (1/(1-alpha))*log2(sum(sum(abs(t).^(2*alpha))).*norm(t(:),2)^(-2*alpha));\n end\n otherwise\n error('This function takes at least one input argument.');\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ref1,ref2] = noisest (Ls,g1,g2,a1,a2,M1,M2,T,F)\n\n% computes the entropy for a white noise signal within one supertile\n% as estimation reference for the tresholds tau1,tau2\n\nn = noise(Ls,'white');\nn1 = dgtreal(n,g1,a1,M1);\nn2 = dgtreal(n,g2,a2,M2);\nr1 = n1(1:floor(F*M1/Ls),1:floor(T/a1));\nr2 = n2(1:floor(F*M2/Ls),1:floor(T/a2));\nref1 = renyi(r1);\nref2 = renyi(r2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%% Version 1 of the jigsaw puzzle algorithm %%%%%%%%%%%%%%%%%%\n\nfunction [x1,x2] = jigsaw1(R,g1,g2,a1,a2,M1,M2,T,F,tau1,tau2)\n\n% error check?\n\n% signal lengths\nLs = length(R);\nL1 = dgtlength(Ls,a1,M1); \nL2 = dgtlength(Ls,a2,M2);\n\n% gabor transformations\nc1 = dgtreal(R,g1,a1,M1); % M1/2+1-by-L/a1\nc2 = dgtreal(R,g2,a2,M2); % M2/2+1-by-L/a2\n\n% frequency hop sizes\nb1 = L1/M1;\nb2 = L2/M2;\n\n% indices on the TF plane (L/2+1 x L), where the coefficients belong to\naa1 = 1:a1:L1;\naa2 = 1:a2:L2;\nbb1 = 1:b1:L1/2+1;\nbb2 = 1:b2:L2/2+1;\n\nL = max([L1,L2]);\n\n% find the indices for the coefficients in every single TF-supertile\nfor m=0:floor((L/2+1)/F)-1\n for n=0:floor(L/T)-1\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n % look for parts of c1,c2 where tonal/transient parts are repr well\n [c1,c2] = decision1(c1,c2,f1,f2,t1,t2,tau1,tau2);\n end\nend\n\n% last column of remaining supertiles \nfor m=0:floor((L/2+1)/F-1)\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=L & aa1>floor(L/T)*T);\n t2 = find(aa2<=L & aa2>floor(L/T)*T);\n \n [c1,c2] = decision1(c1,c2,f1,f2,t1,t2,tau1,tau2);\nend\n\n% upper row of remaining supertiles\nfor n=0:floor(L/T-1)\n f1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\n f2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n \n [c1,c2] = decision1(c1,c2,f1,f2,t1,t2,tau1,tau2);\nend\n\n% right upper remaining supertiles\nf1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\nf2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\nt1 = find(aa1<=L & aa1>floor(L/T)*T);\nt2 = find(aa2<=L & aa2>floor(L/T)*T);\n\n[c1,c2] = decision1(c1,c2,f1,f2,t1,t2,tau1,tau2);\n\n\n% synthesis with the canonical dual windows\nx1 = idgtreal(c1,{'dual',g1},a1,M1,Ls);\nx2 = idgtreal(c2,{'dual',g2},a2,M2,Ls);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [c1,c2] = decision1(c1,c2,f1,f2,t1,t2,tau1,tau2)\n\n% decision procedure for version 1\n% case 1: both entropies are above their thresholds -> set them to zero\n% case 2: g1 has a better repr. and the entropy is below its\n% threshold -> set the tile corr. to g2 to zero\n% case 3: vice versa\n% case 4: g1 has a better repr. and its entropy is above its\n% threshold tau1 but despite of that, the entropy corr. to\n% g2 is below its threshold tau2 -> set the tile corr. to\n% g1 to zero\n% case 5: vice versa\n\nE1 = renyi(c1(f1,t1));\nE2 = renyi(c2(f2,t2));\n\nif E1 > tau1 && E2 > tau2\n c1(f1,t1) = 0; \n c2(f2,t2) = 0;\nelse\n if (min([E1,E2]) == E1 && E1 < tau1) || (min([E1,E2]) == E2 && E2 > tau2 && E1 < tau1)\n c2(f2,t2) = 0;\n elseif (min([E1,E2]) == E2 && E2 < tau2) || (min([E1,E2]) == E1 && E1 > tau1 && E2 < tau2)\n c1(f1,t1) = 0;\n else\n warning('something went wrong with the decision criteria!');\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%% Version 2 of the jigsaw puzzle algorithm %%%%%%%%%%%%%%%%%%\n\nfunction [x1,x2] = jigsaw2(R,g1,g2,a1,a2,M1,M2,T,F,tau1,tau2)\n\n% signal lengths\nLs = length(R);\nL1 = dgtlength(Ls,a1,M1); \nL2 = dgtlength(Ls,a2,M2);\n\n% frequency hop sizes\nb1 = L1/M1;\nb2 = L2/M2;\n\n% gabor transformation\nc1 = dgtreal(R,g1,a1,M1); % M1/2+1-by-L/a1\nc2 = dgtreal(R,g2,a2,M2); % M2/2+1-by-L/a2\n\n% indices on the TF plane (L/2+1 x L), where the coefficients belong to\naa1 = 1:a1:L1;\naa2 = 1:a2:L2;\nbb1 = 1:b1:L1/2+1;\nbb2 = 1:b2:L2/2+1;\n\nL = max([L1,L2]);\n\nfor m=0:floor((L/2+1)/F)-1\n for n=0:floor(L/T)-1\n % find the indices for the coefficients in each TF-supertile\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n % keep the tonals\n [c1,c2] = decision2ton(c1,c2,f1,f2,t1,t2,tau1);\n end\nend\n\n% last column of remaining supertiles \nfor m=0:floor((L/2+1)/F-1)\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=L & aa1>floor(L/T)*T);\n t2 = find(aa2<=L & aa2>floor(L/T)*T);\n % keep the tonals\n [c1,c2] = decision2ton(c1,c2,f1,f2,t1,t2,tau1);\nend\n\n% upper row of remaining supertiles\nfor n=0:floor(L/T-1)\n f1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\n f2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n % keep the tonals\n [c1,c2] = decision2ton(c1,c2,f1,f2,t1,t2,tau1);\nend\n\n% right upper remaining supertile\nf1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\nf2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\nt1 = find(aa1<=L & aa1>floor(L/T)*T);\nt2 = find(aa2<=L & aa2>floor(L/T)*T);\n% keep the tonals\n[c1,~] = decision2ton(c1,c2,f1,f2,t1,t2,tau1);\n\n\n% synthesis of the tonal parts with the canonical dual window of g1\nx1 = idgtreal(c1,{'dual',g1},a1,M1,Ls);\nRR = R-x1;\n\n% the same procedure is now applied with respect to the narrow window g2\n\n% gabor transformation\nc1 = dgtreal(RR,g1,a1,M1); % M1/2+1-by-L/a1\nc2 = dgtreal(RR,g2,a2,M2); % M2/2+1-by-L/a2\n\nfor m=0:floor((L/2+1)/F)-1\n for n=0:floor(L/T)-1\n % find the indices for the coefficients in each TF-supertile\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n % keep the transients\n [~,c2] = decision2trans(c1,c2,f1,f2,t1,t2,tau2);\n end\nend\n\n% last column of remaining supertiles \nfor m=0:floor((L/2+1)/F-1)\n f1 = find(bb1<=(m+1)*F & bb1>m*F);\n f2 = find(bb2<=(m+1)*F & bb2>m*F);\n t1 = find(aa1<=L & aa1>floor(L/T)*T);\n t2 = find(aa2<=L & aa2>floor(L/T)*T);\n % keep the transients\n [~,c2] = decision2trans(c1,c2,f1,f2,t1,t2,tau2);\nend\n\n% upper row of remaining supertiles\nfor n=0:floor(L/T-1)\n f1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\n f2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\n t1 = find(aa1<=(n+1)*T & aa1>n*T);\n t2 = find(aa2<=(n+1)*T & aa2>n*T);\n % keep the transients\n [~,c2] = decision2trans(c1,c2,f1,f2,t1,t2,tau2);\nend\n\n% right upper remaining supertile\nf1 = find(bb1<=L/2+1 & bb1>floor((L/2+1)/F)*F);\nf2 = find(bb2<=L/2+1 & bb2>floor((L/2+1)/F)*F);\nt1 = find(aa1<=L & aa1>floor(L/T)*T);\nt2 = find(aa2<=L & aa2>floor(L/T)*T);\n% keep the transients\n[~,c2] = decision2trans(c1,c2,f1,f2,t1,t2,tau2);\n\n\n% synthesis of the transient parts with the canonical dual window of g2\nx2 = idgtreal(c2,{'dual',g2},a2,M2,Ls);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [c1,c2] = decision2ton(c1,c2,f1,f2,t1,t2,tau1)\n% decision procedure for tonals\n\nE1 = renyi(c1(f1,t1));\nE2 = renyi(c2(f2,t2));\n\nif min([E1,E2]) == E2 || E1 > tau1\n c1(f1,t1) = 0;\nend\n\nfunction [c1,c2] = decision2trans(c1,c2,f1,f2,t1,t2,tau2)\n% decision procedure for transients\n\nE1 = renyi(c1(f1,t1));\nE2 = renyi(c2(f2,t2));\n\nif min([E1,E2]) == E1 || E2 > tau2\n c2(f2,t2) = 0;\nend\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/tfjigsawsep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867851, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6019090217653958}} {"text": "function obj=stat_ellipse(obj,varargin)\n%stat_ellipse() Create confidence ellipses around 2D groups of\n% points\n%\n% Parameters:\n% 'type': The default '95percentile' displays an ellipse that\n% contains 95% of the points (assuming a bivariate normal\n% distribution). The option 'ci' will first compute boostrapped\n% 2D means and plot the 95% ellipse around these means\n% 'geom': Sets how to display the result 'area' for a shaded\n% area or 'line' for a simple contour line.\n% 'patch_opts': Provide additional patch properties as name-value\n% pairs in a cell array (as if those were options for Matlab's\n% built in patch() function)\n\np=inputParser;\nmy_addParameter(p,'type','95percentile'); %ci\nmy_addParameter(p,'geom','area'); %line\nmy_addParameter(p,'patch_opts',{});\nparse(p,varargin{:});\n\nobj.geom=vertcat(obj.geom,{@(dobj,dd)my_ellipse(dobj,dd,p.Results)});\nobj.results.stat_ellipse={};\nend\n\n\nfunction hndl=my_ellipse(obj,draw_data,params)\n\n\npersistent elpoints;\npersistent sphpoints;\n\n%Cache unity ellipse points\nif isempty(elpoints)\n res=30;\n ang=0:pi/(0.5*res):2*pi;\n elpoints=[cos(ang); sin(ang)];\n [x,y,z]=sphere(10);\n sphpoints=surf2patch(x,y,z);\nend\n\ncombx=shiftdim(comb(draw_data.x));\ncomby=shiftdim(comb(draw_data.y));\ncombz=shiftdim(comb(draw_data.z));\n\n%If we have \"enough\" points\nif sum(~isnan(combx))>2 && sum(~isnan(comby))>2\n \n if isempty(draw_data.z)\n \n \n r=[combx comby];\n %Using a chi square with 2 degrees of freedom is proper\n %here (tested: generated ellipse do contain 1-alpha of the\n %points)\n k=@(alpha) sqrt(chi2inv(1-alpha,2));\n \n \n %If a CI on the mean is requested, we replace the original points\n %with bootstrapped mean samples\n if strcmp(params.type,'ci')\n r=bootstrp(obj.stat_options.nboot,@nanmean,r);\n end\n \n %Extract mean and covariance\n m=nanmean(r);\n cv=nancov(r);\n \n \n %Compute ellipse points\n conf_elpoints=sqrtm(cv)*elpoints*k(obj.stat_options.alpha);\n \n %Compute ellipse axes\n [evec,eval]=eig(cv);\n if eval(2,2)>eval(1,1) %Reorder\n evec=fliplr(evec);\n eval=fliplr(flipud(eval));\n end\n elaxes=sqrtm(cv)*evec*k(obj.stat_options.alpha);\n \n \n \n obj.results.stat_ellipse{obj.result_ind,1}.mean=m;\n obj.results.stat_ellipse{obj.result_ind,1}.cv=cv;\n obj.results.stat_ellipse{obj.result_ind,1}.major_axis=elaxes(:,1)';\n obj.results.stat_ellipse{obj.result_ind,1}.minor_axis=elaxes(:,2)';\n \n %plot([0 elaxes(1,1)]+m(1),[0 elaxes(2,1)]+m(2),'k')\n %plot([0 elaxes(1,2)]+m(1),[0 elaxes(2,2)]+m(2),'k')\n \n switch params.geom\n case 'area'\n hndl=patch(conf_elpoints(1,:)+m(1),conf_elpoints(2,:)+m(2),draw_data.color,'FaceColor',draw_data.color,'EdgeColor',draw_data.color,'LineWidth',2,'FaceAlpha',0.2);\n \n case 'line'\n hndl=patch(conf_elpoints(1,:)+m(1),conf_elpoints(2,:)+m(2),draw_data.color,'FaceColor','none','EdgeColor',draw_data.color,'LineWidth',2); \n end\n set(hndl,params.patch_opts{:});\n %One matlab version displayed stuff if no output value was set (but\n %crashes 2014a and earlier versions)\n %tmp = set(hndl,params.patch_opts{:}); \n \n \n \n center_hndl=plot(m(1),m(2),'+','MarkerFaceColor',draw_data.color,'MarkerEdgeColor',draw_data.color,'MarkerSize',10);\n else\n \n r=[combx comby combz];\n k=@(alpha) sqrt(chi2inv(1-alpha,3));\n \n %If a CI on the mean is requested, we replace the original points\n %with bootstrapped mean samples\n if strcmp(params.type,'ci')\n r=bootstrp(obj.stat_options.nboot,@nanmean,r);\n end\n \n %Extract mean and covariance\n m=nanmean(r);\n cv=nancov(r);\n \n obj.results.stat_ellipse{obj.result_ind,1}.mean=m;\n obj.results.stat_ellipse{obj.result_ind,1}.cv=cv;\n obj.results.stat_ellipse{obj.result_ind,1}.major_axis=[];\n obj.results.stat_ellipse{obj.result_ind,1}.minor_axis=[];\n \n conf_sphpoints=sphpoints;\n conf_sphpoints.vertices=bsxfun(@plus,sqrtm(cv)*conf_sphpoints.vertices'*k(obj.stat_options.alpha),m')';\n hndl=patch(conf_sphpoints,'FaceColor',draw_data.color,'EdgeColor','none','LineWidth',2,'FaceAlpha',0.2);\n \n center_hndl=plot3(m(1),m(2),m(3),'+','MarkerFaceColor',draw_data.color,'MarkerEdgeColor',draw_data.color,'MarkerSize',10);\n end\n obj.results.stat_ellipse{obj.result_ind,1}.ellipse_handle=hndl;\n obj.results.stat_ellipse{obj.result_ind,1}.center_handle=center_hndl;\nelse\n warning('Not enough points for ellipse')\n \n obj.results.stat_ellipse{obj.result_ind,1}.mean=NaN;\n obj.results.stat_ellipse{obj.result_ind,1}.cv=NaN;\n obj.results.stat_ellipse{obj.result_ind,1}.major_axis=[];\n obj.results.stat_ellipse{obj.result_ind,1}.minor_axis=[];\n obj.results.stat_ellipse{obj.result_ind,1}.ellipse_handle=[];\n obj.results.stat_ellipse{obj.result_ind,1}.center_handle=[];\nend\nend", "meta": {"author": "piermorel", "repo": "gramm", "sha": "b0fc59245c17d6fbcd86a105d893aeb745fb51e2", "save_path": "github-repos/MATLAB/piermorel-gramm", "path": "github-repos/MATLAB/piermorel-gramm/gramm-b0fc59245c17d6fbcd86a105d893aeb745fb51e2/@gramm/stat_ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6019047229177014}} {"text": "function [exp_apx]=exp_approx3(dboun, exp_par,show_res)\n\n%convert i\nnind=find(exp_par(:,2)<=0);\nexp_par(nind,2)=-1*exp_par(nind,2);\n\ndind1=dboun(1,1):dboun(1,2);\nnd1=dboun(1,2)-dboun(1,1)+1;\ndind2=dboun(2,1):dboun(2,2);\nnd2=dboun(2,2)-dboun(2,1)+1;\ndind3=dboun(3,1):dboun(3,2);\nnd3=dboun(3,2)-dboun(3,1)+1;\ndind4=dboun(4,1):dboun(4,2);\nnd4=dboun(4,2)-dboun(4,1)+1;\nnd=nd1+nd2+nd3+nd4;\n\nH=zeros(nd,5);\nY=zeros(nd,1);\n\nH(1:nd1,1)=dind1;\nH(1:nd1,3)=1;\nH((nd1+1):(nd1+nd2),2)=dind2;\nH((nd1+1):(nd1+nd2),4)=1;\nH((nd1+nd2+1):(nd1+nd2+nd3),1)=dind3;\nH((nd1+nd2+1):(nd1+nd2+nd3),5)=1;\nH((nd1+nd2+nd3+1):nd,2)=dind4;\nH((nd1+nd2+nd3+1):nd,5)=1;\n\nRinv1=1./(linspace(dboun(1,1),dboun(1,2),length(dind1)));\nRinv2=1./(linspace(dboun(2,1),dboun(2,2),length(dind2)));\nRinv3=1./(linspace(dboun(3,1),dboun(3,2)^2,length(dind3)));\nRinv4=1./(linspace(dboun(4,1),dboun(4,2)^2,length(dind4)));\nHR(1:nd1,1)=dind1.*Rinv1;\nHR(1:nd1,3)=Rinv1;\nHR((nd1+1):(nd1+nd2),2)=dind2.*Rinv2;\nHR((nd1+1):(nd1+nd2),4)=Rinv2;\nHR((nd1+nd2+1):(nd1+nd2+nd3),1)=dind3.*Rinv3;\nHR((nd1+nd2+1):(nd1+nd2+nd3),5)=Rinv3;\nHR((nd1+nd2+nd3+1):nd,2)=dind4.*Rinv4;\nHR((nd1+nd2+nd3+1):nd,5)=Rinv4;\n\nY(1:nd1)=log(exp_par(1,2)*exp_par(1,1).^dind1);\nY((nd1+1):(nd1+nd2))=log(exp_par(2,2)*exp_par(2,1).^dind2);\nY((nd1+nd2+1):(nd1+nd2+nd3))=log(exp_par(3,2)*exp_par(3,1).^dind3);\nY((nd1+nd2+nd3+1):nd)=log(exp_par(4,2)*exp_par(4,1).^dind4);\n\nres=inv(HR'*H)*HR'*Y;\nexp_apx=[exp(res(1)) exp(res(3));exp(res(2)) exp(res(4));exp(res(1)) exp(res(5));exp(res(2)) exp(res(5))];\nexp_apx(nind,2)=-1*exp_apx(nind,2);\n\nif (show_res==1)\n exp_par(nind,2)=-1*exp_par(nind,2);\n figure;\n for i=1:4\n ind=0:dboun(i,2);\n plot(ind,exp_par(i,1).^ind*exp_par(i,2))\n hold on\n plot(ind,exp_apx(i,1).^ind*exp_apx(i,2),'r')\n end\n grid;\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/IMUModeling/exp_approx3_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6019047062950086}} {"text": "function [ abd, info ] = zpbfa ( abd, lda, n, m )\n\n%*****************************************************************************80\n%\n%% ZPBFA factors a complex hermitian positive definite band matrix.\n%\n% Discussion:\n%\n% ZPBFA is usually called by ZPBCO, but it can be called\n% directly with a saving in time if RCOND is not needed.\n%\n% Band storage:\n%\n% If A is a hermitian positive definite band matrix,\n% the following program segment will set up the input.\n%\n% m = (band width above diagonal)\n% do j = 1, n\n% i1 = max ( 1, j-m )\n% do i = i1, j\n% k = i-j+m+1\n% abd(k,j) = a(i,j)\n% end do\n% end do\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2007\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979,\n% ISBN13: 978-0-898711-72-1,\n% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, complex ABD(LDA,N); the matrix to be factored.\n% The columns of the upper triangle are stored in the columns of ABD\n% and the diagonals of the upper triangle are stored in the rows of ABD.\n%\n% Input, integer LDA, the leading dimension of ABD.\n% LDA must be at least M+1.\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer M, the number of diagonals above the main diagonal.\n% 0 <= M < N.\n%\n% Output, integer INFO.\n% 0, for normal return.\n% K, if the leading minor of order K is not positive definite.\n%\n% Output, complex ABD(LDA,N); an upper triangular matrix R, stored in\n% band form, so that A = hermitian(R)*R.\n%\n info = 0;\n\n for j = 1 : n\n\n s = 0.0;\n ik = m + 1;\n jk = max ( j - m, 1 );\n mu = max ( m + 2 - j, 1 );\n\n for k = mu : m\n t = abd(k,j) - abd(ik:ik+k-mu-1,jk)' * abd(mu:mu+k-mu-1,j);\n t = t / abd(m+1,jk);\n abd(k,j) = t;\n s = s + real ( t * conj ( t ) );\n ik = ik - 1;\n jk = jk + 1;\n end\n\n s = real ( abd(m+1,j) ) - s;\n\n if ( s <= 0.0 | imag ( abd(m+1,j) ) ~= 0.0 )\n info = j;\n break\n end\n\n abd(m+1,j) = sqrt ( s );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_z/zpbfa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.601899701407948}} {"text": "function [AF,BF]=gabframebounds(g,a,M,varargin)\n%GABFRAMEBOUNDS Calculate frame bounds of Gabor frame\n% Usage: fcond=gabframebounds(g,a,M);\n% [A,B]=gabframebounds(g,a,M);\n% [A,B]=gabframebounds(g,a,M,L);\n% [A,B]=gabframebounds(g,a,M,'lt',lt);\n%\n% Input parameters:\n% g : The window function.\n% a : Length of time shift.\n% M : Number of channels.\n% L : Length of transform to consider.\n% lt : Lattice type (for non-separable lattices).\n% Output parameters:\n% fcond : Frame condition number (B/A)\n% A,B : Frame bounds.\n% \n% `gabframebounds(g,a,M)` calculates the ratio $B/A$ of the frame bounds\n% of the Gabor system with window *g*, and parameters *a*, *M*.\n%\n% `[A,B]=gabframebounds(...)` returns the frame bounds *A* and *B*\n% instead of just the ratio.\n%\n% The window *g* may be a vector of numerical values, a text string or a\n% cell array. See the help of |gabwin| for more details.\n% \n% `gabframebounds(g,a,M,L)` will cut or zero-extend the window to length\n% *L*.\n%\n% `gabframebounds(g,a,M,'lt',lt)` does the same for a non-separable\n% lattice specified by *lt*. Please see the help of |matrix2latticetype|\n% for a precise description of the parameter *lt*.\n%\n% See also: gabrieszbounds, gabwin\n\n \n%% ---------- Assert correct input.\n\nif nargin<3\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\ndefinput.keyvals.L=[];\ndefinput.keyvals.lt=[0 1];\n[flags,kv,L]=ltfatarghelper({'L'},definput,varargin);\n\n\n%% ------ step 2: Verify a, M and L\nif isempty(L)\n if isnumeric(g)\n % Use the window length\n Ls=length(g);\n else\n % Use the smallest possible length\n Ls=1;\n end;\n\n % ----- step 2b : Verify a, M and get L from the window length ----------\n L=dgtlength(Ls,a,M,kv.lt);\n\nelse\n\n % ----- step 2a : Verify a, M and get L\n\n Luser=dgtlength(L,a,M,kv.lt);\n if Luser~=L\n error(['%s: Incorrect transform length L=%i specified. Next valid length ' ...\n 'is L=%i. See the help of DGTLENGTH for the requirements.'],...\n upper(mfilename),L,Luser);\n end;\n\nend;\n\n%% ----- step 3 : Determine the window \n\n[g,info]=gabwin(g,a,M,L,kv.lt,'callfun',upper(mfilename));\n\nif LM*R\n % This can is not a frame, so A is identically 0.\n AF=0;\nelse\n AF=lambdas(1);\nend;\n\nBF=lambdas(s);\n\nif nargout<2\n % Avoid the potential warning about division by zero.\n if AF==0\n AF=Inf;\n else\n AF=BF/AF;\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/gabor/gabframebounds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6018996966385816}} {"text": "%% Brightness and contrast adjustments\n%\n% In this demo we show how to perform the operation\n% $g(i,j) = \\alpha \\cdot f(i,j) + \\beta$.\n%\n% Sources:\n%\n% * \n% * \n% * \n% * \n%\n\n%% Theory\n%\n% A general image processing operator is a function that takes one or more\n% input images and produces an output image. Image transforms can be seen as:\n%\n% * Point operators (pixel transforms)\n% * Neighborhood (area-based) operators\n%\n% In pixel transforms, each output pixel's value depends on only the\n% corresponding input pixel value (plus, potentially, some globally collected\n% information or parameters). Examples of such operators include\n% *brightness and contrast adjustments* as well as color correction and\n% transformations.\n%\n% For brightness and contrast adjustments, two commonly used point processes\n% are *multiplication* and *addition* with a constant:\n%\n% $$g(x) = \\alpha f(x) + \\beta$$\n%\n% The parameters $\\alpha > 0$ and $\\beta$ are often called the *gain* and\n% *bias* parameters; sometimes these parameters are said to control *contrast*\n% and *brightness* respectively. You can think of $f(x)$ as the source image\n% pixels and $g(x)$ as the output image pixels. Then, more conveniently we can\n% write the expression as:\n%\n% $$g(i,j) = \\alpha \\cdot f(i,j) + \\beta$$\n%\n% where $i$ and $j$ indicates that the pixel is located in the *i-th* row and\n% *j-th* column.\n%\n% In the implementation below, instead of using a for-loop to access each\n% pixel, we simply use the function |cv.convertTo| which effectively performs\n% *new_image = saturate(a*image + beta)*. This is more optimized than\n% accessing each pixel and works a lot faster. Also notice that the operation\n% can give values out of range or not integers (if $\\alpha$ is float), in\n% which case |cv.convertTo| makes sure the values are valid.\n%\n\n%% Example\n%\n% We will put into practice what we have learned to correct an underexposed\n% image by adjusting the brightness and the contrast of the image. We will\n% also see another technique to correct the brightness of an image called\n% gamma correction.\n%\n%% Brightness and contrast adjustments\n%\n% Increasing/decreasing the $\\beta$ value will add/subtract a constant value\n% to every pixel. Pixel values outside of the |[0 ; 255]| range will be\n% saturated (i.e. a pixel value higher/lesser than 255/0 will be clamp to\n% 255/0).\n%\n% <>\n%\n% _In light gray, histogram of the original image, in dark gray when\n% |brightness = 80| in Gimp_\n%\n% The histogram represents for each color level the number of pixels with that\n% color level. A dark image will have many pixels with low color value and\n% thus the histogram will present a peak in his left part. When adding a\n% constant bias, the histogram is shifted to the right as we have added a\n% constant bias to all the pixels.\n%\n% The $\\alpha$ parameter will modify how the levels spread. If $\\alpha < 1$,\n% the color levels will be compressed and the result will be an image with\n% less contrast.\n%\n% <>\n%\n% _In light gray, histogram of the original image, in dark gray when\n% |contrast < 0| in Gimp_\n%\n% Note that these histograms have been obtained using the Brightness-Contrast\n% tool in the Gimp software. The brightness tool should be identical to the\n% $\\beta$ bias parameters but the contrast tool seems to differ to the\n% $\\alpha$ gain where the output range seems to be centered with Gimp (as you\n% can notice in the previous histogram).\n%\n% It can occur that playing with the $\\beta$ bias will improve the brightness\n% but in the same time the image will appear with a slight veil as the\n% contrast will be reduced. The $\\alpha$ gain can be used to diminue this\n% effect but due to the saturation, we will lose some details in the original\n% bright regions.\n%\n%% Gamma correction\n%\n% can be\n% used to correct the brightness of an image by using a non linear\n% transformation between the input values and the mapped output values:\n%\n% $$O = \\left( \\frac{I}{255} \\right)^{\\gamma} \\times 255$$\n%\n% As this relation is non linear, the effect will not be the same for all the\n% pixels and will depend to their original value.\n%\n% <>\n%\n% When $\\gamma < 1$, the original dark regions will be brighter and the\n% histogram will be shifted to the right whereas it will be the opposite with\n% $ gamma > 1$.\n%\n% For the gamma correction, a look-up table can be used to improve the\n% performance of the computation as only 256 values needs to be calculated\n% once.\n%\n% Let's an example of how to correct an underexposed image.\n%\n% The following image has been corrected with: $\\alpha = 1.3$ and $\\beta = 40$.\n%\n% <>\n%\n% The overall brightness has been improved but you can notice that the clouds\n% are now greatly saturated due to the numerical saturation of the\n% implementation used\n% (\n% in photography).\n%\n% The following image has been corrected with: $\\gamma = 0.4$.\n%\n% <>\n%\n% The gamma correction should tend to add less saturation effect as the\n% mapping is non linear and there is no numerical saturation possible as in\n% the previous method.\n%\n% <>\n%\n% * Left: histogram after alpha, beta correction\n% * Center: histogram of the original image\n% * Right: histogram after the gamma correction\n%\n% The previous figure compares the histograms for the three images (the\n% y-ranges are not the same between the three histograms). You can notice that\n% most of the pixel values are in the lower part of the histogram for the\n% original image. After $\\alpha$, $\\beta$ correction, we can observe a big\n% peak at 255 due to the saturation as well as a shift in the right. After\n% gamma correction, the histogram is shifted to the right but the pixels in\n% the dark regions are more shifted (see the gamma curves figure) than those\n% in the bright regions.\n%\n% In this tutorial, you have seen two simple methods to adjust the contrast\n% and the brightness of an image. They are basic techniques and are not\n% intended to be used as a replacement of a raster graphics editor!\n%\n%% Additional resources\n%\n% * \n% * \n% * \n%\n\n%% Code\n\nfunction varargout = linear_transform_demo_gui(im)\n % load source image\n if nargin < 1\n im = fullfile(mexopencv.root(),'test','lena.jpg');\n img = cv.imread(im);\n elseif ischar(im)\n img = cv.imread(im, 'Color',true);\n else\n img = im;\n end\n\n % create the UI\n h = buildGUI(img);\n if nargout > 0, varargout{1} = h; end\nend\n\nfunction onLinearTransform(~,~,h)\n %ONLINEARTRANSFORM Event handler for UI controls\n\n % retrieve current values from UI controls\n a = get(h.slid(1), 'Value');\n b = round(get(h.slid(2), 'Value'));\n set(h.txt(1), 'String',sprintf('Contrast: %.2f',a));\n set(h.txt(2), 'String',sprintf('Brightness: %2d',b));\n\n % linear transformation\n out = cv.convertTo(h.src, 'Alpha',a, 'Beta',b);\n\n % show result\n out = cv.putText(out, 'Brightness/Contrast Adjustment', [10 20], ...\n 'FontScale',0.5, 'Color',[0 255 0], 'LineType','AA');\n set(h.img(1), 'CData',out);\n drawnow;\nend\n\nfunction onGammaCorrection(~,~,h)\n %ONGAMMACORRECTION Event handler for UI controls\n\n % retrieve current values from UI controls\n g = get(h.slid(3), 'Value');\n set(h.txt(3), 'String',sprintf('Gamma: %.2f',g));\n\n % gamma correction\n lookUpTable = uint8((((0:255)/255) .^ g) * 255);\n if true\n out = cv.LUT(h.src, lookUpTable);\n elseif mexopencv.require('images')\n out = intlut(h.src, lookUpTable);\n else\n out = lookUpTable(double(h.src) + 1);\n end\n\n % show result\n out = cv.putText(out, 'Gamma Correction', [10 20], ...\n 'FontScale',0.5, 'Color',[0 255 0], 'LineType','AA');\n set(h.img(2), 'CData',out);\n drawnow;\nend\n\nfunction h = buildGUI(img)\n %BUILDGUI Creates the UI\n\n % parameters\n a = 1.0; % alpha gain (contrast)\n b = 0; % beta bias (brightness)\n g = 1.0; % gamma correction\n sz = size(img);\n sz(2) = max(sz(2), 300); % minimum figure width\n\n % build the user interface (no resizing to keep it simple)\n h = struct();\n h.src = img;\n h.fig = figure('Name','Linear Transform Demo', ...\n 'NumberTitle','off', 'Menubar','none', 'Resize','off', ...\n 'Position',[200 200 sz(2)*2 sz(1)+80-1]);\n if ~mexopencv.isOctave()\n %HACK: not implemented in Octave\n movegui(h.fig, 'center');\n end\n h.ax(1) = axes('Parent',h.fig, 'Units','pixels', 'Position',[1 80 sz(2) sz(1)]);\n h.ax(2) = axes('Parent',h.fig, 'Units','pixels', 'Position',[sz(2)+1 80 sz(2) sz(1)]);\n if ~mexopencv.isOctave()\n h.img(1) = imshow(img, 'Parent',h.ax(1));\n h.img(2) = imshow(img, 'Parent',h.ax(2));\n else\n %HACK: https://savannah.gnu.org/bugs/index.php?45473\n axes(h.ax(1)); h.img(1) = imshow(img);\n axes(h.ax(2)); h.img(2) = imshow(img);\n end\n h.txt(1) = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n 'Position',[5 5 130 20], 'String',sprintf('Contrast: %.2f',a));\n h.txt(2) = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n 'Position',[5 30 130 20], 'String',sprintf('Brightness: %2d',b));\n h.txt(3) = uicontrol('Parent',h.fig, 'Style','text', 'FontSize',11, ...\n 'Position',[5 55 130 20], 'String',sprintf('Gamma: %.2f',g));\n h.slid(1) = uicontrol('Parent',h.fig, 'Style','slider', 'Value',a, ...\n 'Min',0.1, 'Max',3, 'SliderStep',[0.01 0.2]./(3-0.1), ...\n 'Position',[135 5 sz(2)-135-5 20]);\n h.slid(2) = uicontrol('Parent',h.fig, 'Style','slider', 'Value',b, ...\n 'Min',-100, 'Max',100, 'SliderStep',[1 20]./(100+100), ...\n 'Position',[135 30 sz(2)-135-5 20]);\n h.slid(3) = uicontrol('Parent',h.fig, 'Style','slider', 'Value',g, ...\n 'Min',0.1, 'Max',3, 'SliderStep',[0.01 0.2]./(3-0.1), ...\n 'Position',[135 55 sz(2)-135-5 20]);\n\n % hook event handlers, and trigger default start\n opts = {'Interruptible','off', 'BusyAction','cancel'};\n set(h.slid(1:2), 'Callback',{@onLinearTransform,h}, opts{:});\n set(h.slid(3), 'Callback',{@onGammaCorrection,h}, opts{:});\n onLinearTransform([],[],h);\n onGammaCorrection([],[],h);\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/linear_transform_demo_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.6018258940665606}} {"text": "function partition_count_values_test ( )\n\n%*****************************************************************************80\n%\n%% PARTITION_COUNT_VALUES_TEST demonstrates the use of PARTITION_COUNT_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARTITION_COUNT_VALUES_TEST:\\n' );\n fprintf ( 1, ' PARTITION_COUNT_VALUES returns values of \\n' );\n fprintf ( 1, ' the integer partition count function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N P(N)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, fn ] = partition_count_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %4d %10d\\n', n, fn );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/partition_count_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.6018258847423681}} {"text": "classdef MOEADM2M_F3 < PROBLEM\n% \n% Benchmark MOP for testing MOEA/D-M2M\n\n%------------------------------- Reference --------------------------------\n% H. Liu, F. Gu, and Q. Zhang, Decomposition of a multiobjective\n% optimization problem into a number of simple multiobjective subproblems,\n% IEEE Transactions on Evolutionary Computation, 2014, 18(3): 450-455.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n methods\n %% Default settings of the problem\n function Setting(obj)\n obj.M = 2;\n if isempty(obj.D); obj.D = 10; end\n obj.lower = zeros(1,obj.D);\n obj.upper = ones(1,obj.D);\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n t = X(:,2:end) - repmat(sin(pi/2*X(:,1)),1,size(X,2)-1);\n g = 10*sin(pi/2*X(:,1)).*sum(abs(t)./(1+exp(5*abs(t))),2);\n PopObj(:,1) = (1+g).*cos(pi/2*X(:,1));\n PopObj(:,2) = (1+g).*sin(pi/2*X(:,1));\n end\n %% Generate points on the Pareto front\n function R = GetOptimum(obj,N)\n R(:,1) = linspace(0,1,N)';\n R(:,2) = sqrt(1-R(:,1).^2);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n R = obj.GetOptimum(100);\n end\n end\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Problems/Multi-objective optimization/MOPs with variable linkages/MOEADM2M_F3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6018258827545676}} {"text": "function gX = ardKernGradX(kern, X, X2)\n\n% ARDKERNGRADX Gradient of ARD kernel with respect to a point x.\n% FORMAT\n% DESC computes the gradient of the pre-built RBF and linear ARD\n% kernel with respect to the input positions. \n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x : locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData x numInputs x numData. Where numData is\n% the number of data points and numInputs is the number of input\n% dimensions in X.\n%\n% FORMAT\n% DESC computes the gradident of the pre-built RBF and linear ARD\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO ardKernParamInit, kernGradX, ardKernDiagGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n\n% KERN\n\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\nfor i = 1:size(X, 1);\n gX(:, :, i) = ardKernGradXpoint(kern, X(i, :), X2);\nend\n\nfunction gX = ardKernGradXpoint(kern, x, X2)\n\n% ARDKERNGRADXPOINT Gradient with respect to one point of x.\n\nscales = sparse(diag(kern.inputScales));\n\ngX = kern.linearVariance.*X2*scales;\n\nscales = sqrt(scales);\n\nn2 = dist2(X2*scales, x*scales);\nwi2 = (.5 .* kern.inverseWidth);\nrbfPart = kern.rbfVariance*exp(-n2*wi2);\nfor i = 1:size(x, 2)\n gX(:, i) = gX(:, i) + kern.inverseWidth*kern.inputScales(i)*(X2(:, i) - x(i)).*rbfPart;\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/ardKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6018258769722072}} {"text": "%DEMO_SVI_CLASSIFIC Classification problem demonstration for SVI GP\n%\n% Description\n% The demonstration program is based on synthetic two class data\n% used by B.D. Ripley (Pattern Recognition and Neural Networks,\n% 1996}. The data consists of 2-dimensional vectors that are\n% divided into two classes, labeled 0 or 1. Each class has a\n% bimodal distribution generated from equal mixtures of Gaussian\n% distributions with identical covariance matrices. A Bayesian\n% approach is used to find the decision line and predict the\n% classes of new data points. The result can be compared to the \n% ones from the DEMO_CLASSIFIC.\n%\n% The probability of y being one is assumed to be \n%\n% p(y=1|f) = normcdf(f)\n%\n% The latent values f are given a zero mean Gaussian process\n% prior. This implies that at the observed input locations\n% latent values have prior\n%\n% f ~ N(0, K),\n%\n% where K is the covariance matrix, whose elements are given as\n% K_ij = k(x_i, x_j | th). The function k(x_i, x_j | th) is\n% covariance function and th its parameters.\n% \n% Here we demonstarte use of stochastic variational inference\n% methods to find the posterior of the latent values and parameters.\n% With these we can make predictions on the class probability of\n% future observations. See Hensman et. al. (2013) for the\n% detailed treatment.\n%\n% See also\n% DEMO_SVI_REGRESSION, DEMO_CLASSIFIC\n%\n%\n% References:\n% Hensman, J., Fusi, N. and Lawrence, N. D. (2013). Gaussian\n% processes for big data. arXiv preprint arXiv:1309.6835.\n\n% Copyright (c) 2014 Tuomas Sivula\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% This demonstration is based on the dataset used in the book Pattern\n% Recognition and Neural Networks by B.D. Ripley (1996), Cambridge\n% University Press.\n\n% Training data\nS = which('demo_classific');\nL = strrep(S,'demo_classific.m','demodata/synth.tr');\nx=load(L);\ny=x(:,end);\ny = 2.*y-1;\nx(:,end)=[];\n[n, nin] = size(x);\n\n% Test data\nxt1=repmat(linspace(min(x(:,1)),max(x(:,1)),20)',1,20);\nxt2=repmat(linspace(min(x(:,2)),max(x(:,2)),20)',1,20)';\nxt=[xt1(:) xt2(:)];\n\n% Create likelihood function\nlik = lik_probit();\n%lik = lik_logit();\n\n% Create covariance functions\ngpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 10);\n% Set the prior for the parameters of covariance functions \npl = prior_t();\npm = prior_sqrtt('s2',0.5);\ngpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pm);\n\n% Create the GP structure (type is by default FULL)\nfprintf('SVI GP classification model with probit likelihood\\n')\ngp = gp_set('lik', lik, 'cf', gpcf, ...\n 'latent_method', 'SVI', 'jitterSigma2', 1e-6);\n\n% Select 20 inducing inputs by clustering 10 from both training class\n% inputs\nfprintf(['Select 20 inducing inputs by clustering 10 points ', ...\n 'from both training classes ...'])\nSw = warning('off','stats:kmeans:EmptyCluster');\n[~,X_u1] = kmeans(x(y==1,:), 10,'Start','uniform',...\n 'EmptyAction','singleton');\n[~,X_u2] = kmeans(x(y==-1,:), 10,'Start','uniform',...\n 'EmptyAction','singleton');\nwarning(Sw);\nX_u = [X_u1 ; X_u2];\nfprintf(' done\\n')\n\n% Optimise\nmaxi = 1000; % The maximum number of iteration rounds\ngp = svigp(gp,x,y,'X_u',X_u,'maxiter',maxi,'mu2',1e-7);\n% Make predictions\n[Eft, Varft, lpyt, Eyt, Varyt] = ...\n gpsvi_pred(gp, x, y, xt, 'yt', ones(size(xt,1),1) );\n\n% Visualise predictive probability p(ystar = 1) with grayscale\nfigure, hold on;\nn_pred=size(xt,1);\nh1=pcolor(reshape(xt(:,1),20,20),reshape(xt(:,2),20,20),reshape(exp(lpyt),20,20));\nset(h1, 'edgealpha', 0), set(h1, 'facecolor', 'interp')\ncolormap(repmat(linspace(1,0,64)', 1, 3).*repmat(ones(1,3), 64,1))\naxis([-inf inf -inf inf]), %axis off\nplot(x(y==-1,1),x(y==-1,2),'o', 'markersize', 8, 'linewidth', 2);\nplot(x(y==1,1),x(y==1,2),'rx', 'markersize', 8, 'linewidth', 2);\nplot(gp.X_u(:,1),gp.X_u(:,2),'gs', 'markersize', 8, 'linewidth', 1);\nset(gcf, 'color', 'w'), title('predictive probability, training cases and inducing inputs with SVIGP', 'fontsize', 14)\n\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/demo_svi_classific.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6017859059992587}} {"text": "function y=scInv(z, LinCol)\n%scInv : Inverts a given impedance (admitance) by mirroring it about the origin\n%\n% SYNOPSIS:\n% This function inverts the given impedance (admittance) by mirroring it about\n% the origin of the smith chart.\n%\n% See also scDraw, scMove, scConCirc, scMatchCirc \n% \n% SYNTAX:\n% [y] = scInv(z)\n%\n% INPUT ARGUMENTS:\n% z : Impedance (or admittance)\n%\n% OUTPUT ARGUMENT:\n% y : Inverted admittance (or impedance)\n%\n% EXAMPLE:\n% y = scInv([2 3])\n% y =\n% 0.1538 -0.2308\n% \n%\n% Mohammad Ashfaq - (31-05-2000)\n% Mohammad Ashfaq - (13-04-2006) Modified (example included)\n%\n\n if nargin < 1\n error('scInv.m: One input argument required...You may give LinCol as second argument as well');\n end\n\n if nargin == 1\n LinCol = 'm';\n end\n\n if (size(z)==[1, 1])\n if conj(z) == z\n r = z;\n x = 0;\n else\n r = real (z);\n x = imag (z);\n end\n elseif max(size(z)) == 2 && min(size(z)) == 1\n r = z(1);\n x = z(2);\n else\n error('scInv.m: Input must either be a complex number or a 1x2 vector [r x]');\n end\n\n if (r+j*x)~=0\n y1 = 1/(r+j*x);\n y(1) = real(y1);\n y(2) = imag(y1);\n\n else\n y = inf;\n end\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/324-smithchart/scInv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6016635437438662}} {"text": "%% TOMLAB PROPT Parameter Estimation Problems\n% http://tomdyn.com/parameter_estimation_dynamic_systems.html\nclc\nclear\n\n%% http://tomdyn.com/examples/catalyticCracking.html\nclc\node = @(t,z,p) [-(p(1)+p(3))*z(1).^2\n p(1)*z(1).^2-p(2)*z(2)];\nz0 = [1;0]; %ic\n\n\n% Various constants and expressions\ny1meas = [1.0;0.8105;0.6208;0.5258;0.4345;0.3903;...\n 0.3342;0.3034;0.2735;0.2405;0.2283;0.2071;0.1669;...\n 0.153;0.1339;0.1265;0.12;0.099;0.087;0.077;0.069];\ny2meas = [0;0.2;0.2886;0.301;0.3215;0.3123;0.2716;...\n 0.2551;0.2258;0.1959;0.1789;0.1457;0.1198;0.0909...\n ;0.0719;0.0561;0.046;0.028;0.019;0.014;0.010];\ntmeas = [0;0.025;0.05;0.075;0.1;0.125;...\n 0.15;0.175;0.2;0.225;0.25;0.3;0.35;0.4;...\n 0.45;0.5;0.55;0.65;0.75;0.85;0.95];\n\n%Build OPTI Object\ntheta0 = [10;8;1]; %inital parameter guess\nopts = optiset('display','iter');\nOpt = opti('ode',ode,'data',tmeas,[y1meas' y2meas'],'theta0',theta0,'z0',z0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\nplot(Opt)\n\n%% http://tomdyn.com/examples/isometrizationAlpha.html\nclc\node = @(t,z,p) [-(p(1)+p(2))*z(1)\n p(1)*z(1)\n p(2)*z(1)-(p(3)+p(4))*z(3)+p(5)*z(5)\n p(3)*z(3)\n p(4)*z(3)-p(5)*z(5)];\nz0 = [100;0;0;0;0]; %ic\n\n\ny1meas = [88.35; 76.4; 65.1; 50.4; 37.5; 25.9; 14.0; 4.5];\ny2meas = [7.3; 15.6; 23.1; 32.9; 42.7; 49.1; 57.4; 63.1];\ny3meas = [2.3; 4.5; 5.3; 6.0; 6.0; 5.9; 5.1; 3.8];\ny4meas = [0.4; 0.7; 1.1; 1.5; 1.9; 2.2; 2.6; 2.9];\ny5meas = [1.75; 2.8; 5.8; 9.3; 12.0; 17.0; 21.0; 25.7];\ntmeas = [1230; 3060; 4920; 7800; 10680; 15030; 22620; 36420];\n\n%Build OPTI Object\ntheta0 = [0;0;0;0;0]; %inital parameter guess\nopts = optiset('display','iter','dynamicOpts',optidynset('sensitivity','cs','initialT',0));\nOpt = opti('ode',ode,'data',tmeas,[y1meas' y2meas' y3meas' y4meas' y5meas'],'theta0',theta0,'z0',z0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\nplot(Opt)\n\n%% http://tomdyn.com/examples/marinePopulation.html\nclc\node = @(t,z,p) [[0; p(9:end)].*[0; z(1:7)] - (p(1:8)+[p(9:end);0]).*z];\n\nymeas = [20000 17000 10000 15000 12000 9000 7000 3000\n 12445 15411 13040 13338 13484 8426 6615 4022\n 7705 13074 14623 11976 12453 9272 6891 5020\n 4664 8579 12434 12603 11738 9710 6821 5722\n 2977 7053 11219 11340 13665 8534 6242 5695\n 1769 5054 10065 11232 12112 9600 6647 7034\n 943 3907 9473 10334 11115 8826 6842 7348\n 581 2624 7421 10297 12427 8747 7199 7684\n 355 1744 5369 7748 10057 8698 6542 7410\n 223 1272 4713 6869 9564 8766 6810 6961\n 137 821 3451 6050 8671 8291 6827 7525\n 87 577 2649 5454 8430 7411 6423 8388\n 49 337 2058 4115 7435 7627 6268 7189\n 32 228 1440 3790 6474 6658 5859 7467\n 17 168 1178 3087 6524 5880 5562 7144\n 11 99 919 2596 5360 5762 4480 7256\n 7 65 647 1873 4556 5058 4944 7538\n 4 44 509 1571 4009 4527 4233 6649\n 2 27 345 1227 3677 4229 3805 6378\n 1 20 231 934 3197 3695 3159 6454\n 1 12 198 707 2562 3163 3232 5566];\ntmeas = 0:0.5:10;\n\nz0 = ymeas(1,:); %ic\n\n%Build OPTI Object\ntheta0 = [zeros(8,1);zeros(7,1)]; %inital parameter guess\nopts = optiset('display','iter','dynamicOpts',optidynset('sensitivity','cs'));\nOpt = opti('ode',ode,'data',tmeas,ymeas,'theta0',theta0,'z0',z0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\nplot(Opt)\n\n\n%% http://tomdyn.com/examples/methanolToHydrocarbons.html\nclc\node = @(t,z,p) [-(2*p(2)-(p(1)*z(2))./((p(2)+p(5))*z(1)+z(2))+p(3)+p(4)).*z(1)\n (p(1)*z(1).*(p(2)*z(1)-z(2)))./((p(2)+p(5))*z(1)+z(2))+p(3)*z(1)\n (p(1)*z(1).*(z(2)+p(5)*z(1)))./((p(2)+p(5))*z(1)+z(2))+p(4)*z(1)];\n\ny1meas = [0.7085;0.5971;0.5537;0.3684;0.1712;...\n 0.1198;0.0747;0.0529;0.0415;0.0261;0.0208;...\n 0.0085;0.0053;0.0019;0.0018];\ny2meas = [0.1621;0.1855;0.1989;0.2845;0.3491;...\n 0.3098;0.3576;0.3347;0.3388;0.3557;0.3483;...\n 0.3836;0.3611;0.3609;0.3485];\ny3meas = [0.0811;0.0965;0.1198;0.1535;0.2097;...\n 0.2628;0.2467;0.2884;0.2757;0.3167;0.2954;...\n 0.295;0.2937;0.2831;0.2846];\ntmeas = [0.05;0.065;0.08;0.123;0.233;0.273;...\n 0.354;0.397;0.418;0.502;0.553;...\n 0.681;0.75;0.916;0.937];\n\nz0 = [1;0;0]; %ic\nlb = ones(5,1)*sqrt(eps);\nub = 10*ones(5,1);\n\n%Build OPTI Object\ntheta0 = [1;1;1;1;1]; %inital parameter guess\nopts = optiset('display','iter','solver','nl2sol','dynamicOpts',optidynset('initialT',0,'sensitivity','cs'));\nOpt = opti('ode',ode,'bounds',lb,ub,'data',tmeas,[y1meas y2meas y3meas],'theta0',theta0,'z0',z0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\nplot(Opt)\n\n%% http://tomdyn.com/examples/parameterEstimation.html\nclc\node = @(t,z,p) [p(1)*z(2); 1-2*z(2)-z(1)];\n\ny1meas = [0.264;0.594;0.801;0.959];\ntmeas = [1;2;3;5];\n\nz0 = [NaN;NaN]; %ic\n\nlb = -1.5*ones(3,1); lb(1)=1; %not actually interested in p1, but needed for OPTI\nub = 1.5*ones(3,1); ub(1)=1;\n\n%Build OPTI Object\ntheta0 = [1;0;0]; %inital parameter guess\nopts = optiset('display','iter','solver','nl2sol','dynamicOpts',optidynset('stateIndex',1,'initialT',0,'sensitivity','cs'));\nOpt = opti('ode',ode,'bounds',lb,ub,'data',tmeas,y1meas,'theta0',theta0,'z0',z0,'options',opts)\n\n[x,f,e,i] = solve(Opt)\nplot(Opt)\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/math/opti/Test Problems/Development/test_propt_ex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6015953261408798}} {"text": "function [px,py,pz,tx,ty,tz,bx,by,bz,ierr] = nd2pt(wanx,wany,wanz,wdx,wdy,wdz)\n\n%% c compute Cartesian component of P, T and B axes from outward normal\n%% c and slip vectors\n%% c\n%% c usage:\n%% c call nd2pt(anx,any,anz,dx,dy,dz,px,py,pz,tx,ty,tz,bx,by,bz,ierr)\n%% c\n%% c arguments:\n%% c anx,any,anz components of fault plane outward normal vector in the\n%% c Aki-Richards Cartesian coordinate system (INPUT)\n%% c dx,dy,dz components of slip vector in the Aki-Richards\n%% c Cartesian coordinate system (INPUT)\n%% c px,py,pz components of downward P (maximum dilatation) axis versor\n%% c in the Aki-Richards Cartesian coordinate system (OUTPUT)\n%% c tx,ty,tz components of downward T (maximum tension) axis versor\n%% c in the Aki-Richards Cartesian coordinate system (OUTPUT)\n%% c bx,by,bz components of downward B (neutral) axis versor in the\n%% c Aki-Richards Cartesian coordinate system (OUTPUT)\n%% c ierr error indicator (OUTPUT)\n%% c\n%% c errors:\n%% c 1 input vectors not perpendicular among each other\n\n%% c\n%% c implicit none\n%% c-------------------------------------------------------------------------------\n%% integer io\n%% real amistr,amastr,amidip,amadip,amirak,amarak,amitre,amatre\n%% 1,amiplu,amaplu,orttol,ovrtol,tentol,dtor,c360,c90,c0,c1,c2,c3\n%% common /fpscom/amistr,amastr,amidip,amadip,amirak,amarak,amitre\n%% 1,amatre,amiplu,amaplu,orttol,ovrtol,tentol,dtor,c360,c90,c0,c1,c2\n%% 2,c3,io\n%% c-------------------------------------------------------------------------------\n%% real wanx,wany,wanz,amn,anx,any,anz,wdx,wdy,wdz,amd,dx,dy,dz\n%% 1,ang,px,py,pz,tx,ty,tz,bx,by,bz,amp\n%% integer ierr\n%% c\n\n\n\n%% call fpsset\n amistr=-360.;\n amastr=360.;\n amidip=0.;\n amadip=90.;\n amirak=-360.;\n amarak=360.;\n amitre=-360.;\n amatre=360.;\n amiplu=0.;\n amaplu=90.;\n orttol=2.;\n ovrtol=0.001;\n tentol=0.0001;\n dtor=0.017453292519943296;\n c360=360.;\n c90=90.;\n c0=0.;\n c1=1.;\n c2=2.;\n c3=3.;\n io=6;\n\n ierr=0;\n [amn,anx,any,anz] = focal_norm(wanx,wany,wanz);\n [amd,dx,dy,dz] = focal_norm(wdx,wdy,wdz);\n [ang] = focal_angle(anx,any,anz,dx,dy,dz);\n if (abs(ang-c90) > orttol)\n disp(['ND2PT: input vectors not perpendicular, angle=' num2str(ang)]);\n ierr=1;\n end\n px=anx-dx;\n py=any-dy;\n pz=anz-dz;\n [amp,px,py,pz] = focal_norm(px,py,pz);\n if (pz < c0)\n [px,py,pz] = focal_invert(px,py,pz);\n end\n tx=anx+dx;\n ty=any+dy;\n tz=anz+dz;\n [amp,tx,ty,tz] = focal_norm(tx,ty,tz);\n if (tz < c0)\n [tx,ty,tz] = focal_invert(tx,ty,tz);\n end\n [bx,by,bz] = focal_vecpro(px,py,pz,tx,ty,tz);\n if(bz < c0)\n [bx,by,bz] = focal_invert(bx,by,bz);\n end\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/danijel/focal/focal_nd2pt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6015953143913908}} {"text": "function [f] = elec_sphere_fit_optim(r, X, Y, Z, xo, yo, zo)\n\n% elec_sphere_fit_optim - Optimization for elec_sphere_fit.m\n%\n% Called from elec_sphere_fit.m\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence: GNU GPL, no implied or express warranties\n% History: 02/2002, Darren.Weber_at_radiology.ucsf.edu\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% with center (Xo,Yo,Zo) and radius r, the equation of a sphere is:\n%\n% r^2 = (x-xo)^2 + (y-yo)^2 + (z-zo)^2\n%\n% This function below creates a scalar value to\n% return to the fminsearch function in elec_sphere_fit.\n\nS = (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2 - r^2;\n\nf = sum( S.^2 );\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/elec_sphere_fit_optim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6015953106187645}} {"text": "function [NABF]=analysis_nabf(f,I1,I2)\n% function [QABF,LABF,NABF,NABF1]=objective_fusion_perform_fn(f,I1,I2)\n% \n%%% objective_fusion_perform_fn: Computes the Objective Fusion Performance Parameters proposed by Petrovic\n%%% and modified Fusion Artifacts (NABF) measure proposed by B. K. Shreyamsha Kumar\n%%% \n%%% Inputs: \n%%% xrcw -> fused image\n%%% x -> source images, x{1}, x{2}\n%%%\n%%% Outputs:\n%%% QABF -> Total information transferred from source images to fused image measure proposed by Petrovic\n%%% LABF -> Total loss of information measure proposed by Petrovic\n%%% NABF1 -> Fusion Artifacts measure proposed by Petrovic\n%%% NABF -> Modified Fusion Artifacts measure proposed by B. K. Shreyamsha Kumar\n%%%\n%%% Author : B. K. SHREYAMSHA KUMAR \n%%% Created on 28-10-2011.\n%%% Updated on 08-11-2011.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Petrovic Metrics %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%% Parameters for Petrovic Metrics Computation.\nTd=2; \nwt_min=0.001;\nP=1; \nLg=1.5; \nNrg=0.9999; \nkg=19; \nsigmag=0.5; \nNra=0.9995; \nka=22; \nsigmaa=0.5; \n\nxrcw = (f);\nx1 = (I1);\nx2 = (I2);\n\n%%% Edge Strength & Orientation.\n[gvA,ghA]=sobel_fn(x1);\ngA=sqrt(ghA.^2+gvA.^2);\n\n[gvB,ghB]=sobel_fn(x2);\ngB=sqrt(ghB.^2+gvB.^2);\n\n[gvF,ghF]=sobel_fn(xrcw);\ngF=sqrt(ghF.^2+gvF.^2);\n\n%%% Relative Edge Strength & Orientation.\n[p,q]=size(xrcw);\nfor ii=1:p\n for jj=1:q\n if(gA(ii,jj)==0 | gF(ii,jj)==0)\n gAF(ii,jj)=0;\n elseif(gA(ii,jj)>gF(ii,jj))\n gAF(ii,jj)=gF(ii,jj)/gA(ii,jj);\n else\n gAF(ii,jj)=gA(ii,jj)/gF(ii,jj);\n end\n if(gB(ii,jj)==0 | gF(ii,jj)==0)\n gBF(ii,jj)=0; \n elseif(gB(ii,jj)>gF(ii,jj))\n gBF(ii,jj)=gF(ii,jj)/gB(ii,jj);\n else\n gBF(ii,jj)=gB(ii,jj)/gF(ii,jj);\n end\n if(gvA(ii,jj)==0 & ghA(ii,jj)==0)\n aA(ii,jj)=0;\n else\n aA(ii,jj)=atan(gvA(ii,jj)/ghA(ii,jj));\n end \n if(gvB(ii,jj)==0 & ghB(ii,jj)==0)\n aB(ii,jj)=0;\n else\n aB(ii,jj)=atan(gvB(ii,jj)/ghB(ii,jj));\n end\n if(gvF(ii,jj)==0 & ghF(ii,jj)==0)\n aF(ii,jj)=0;\n else\n aF(ii,jj)=atan(gvF(ii,jj)/ghF(ii,jj));\n end \n end\nend\naAF=abs(abs(aA-aF)-pi/2)*2/pi;\naBF=abs(abs(aB-aF)-pi/2)*2/pi;\n\n\n%%% Edge Preservation Coefficient.\nQgAF=Nrg./(1+exp(-kg*(gAF-sigmag)));\nQaAF=Nra./(1+exp(-ka*(aAF-sigmaa)));\nQAF=sqrt(QgAF.*QaAF);\nQgBF=Nrg./(1+exp(-kg*(gBF-sigmag)));\nQaBF=Nra./(1+exp(-ka*(aBF-sigmaa)));\nQBF=sqrt(QgBF.*QaBF);\n\n%%% Total Fusion Performance (QABF).\nwtA=wt_min*ones(p,q);\nwtB=wt_min*ones(p,q);\ncA=ones(p,q); cB=ones(p,q);\nfor ii=1:p\n for jj=1:q\n if(gA(ii,jj)>=Td)\n wtA(ii,jj)=cA(ii,jj)*gA(ii,jj)^Lg;\n end\n if(gB(ii,jj)>=Td)\n wtB(ii,jj)=cB(ii,jj)*gB(ii,jj)^Lg;\n end\n end\nend\nwt_sum=sum(sum(wtA+wtB));\nQAF_wtsum=sum(sum(QAF.*wtA))/wt_sum; %% Information Contributions of A.\nQBF_wtsum=sum(sum(QBF.*wtB))/wt_sum; %% Information Contributions of B.\nQABF=QAF_wtsum+QBF_wtsum; %% QABF=sum(sum(QAF.*wtA+QBF.*wtB))/wt_sum -> Total Fusion Performance.\n\n%%% Fusion Gain (QdeltaABF).\nQdelta=abs(QAF-QBF);\nQCinfo=(QAF+QBF-Qdelta)/2;\nQdeltaAF=QAF-QCinfo;\nQdeltaBF=QBF-QCinfo;\nQdeltaAF_wtsum=sum(sum(QdeltaAF.*wtA))/wt_sum;\nQdeltaBF_wtsum=sum(sum(QdeltaBF.*wtB))/wt_sum;\nQdeltaABF=QdeltaAF_wtsum+QdeltaBF_wtsum; %% Total Fusion Gain.\nQCinfo_wtsum=sum(sum(QCinfo.*(wtA+wtB)))/wt_sum;\nQABF11=QdeltaABF+QCinfo_wtsum; %% Total Fusion Performance.\n\n%%% Fusion Loss (LABF).\nrr=zeros(p,q);\nfor ii=1:p\n for jj=1:q\n if(gF(ii,jj)<=gA(ii,jj) | gF(ii,jj)<=gB(ii,jj))\n rr(ii,jj)=1;\n else\n rr(ii,jj)=0;\n end\n end\nend\nLABF=sum(sum(rr.*((1-QAF).*wtA+(1-QBF).*wtB)))/wt_sum;\n\n%%% Fusion Artifacts (NABF) by Petrovic.\nfor ii=1:p\n for jj=1:q\n if(gF(ii,jj)>gA(ii,jj) & gF(ii,jj)>gB(ii,jj))\n na1(ii,jj)=2-QAF(ii,jj)-QBF(ii,jj);\n else\n na1(ii,jj)=0; \n end\n end\nend\nNABF1=sum(sum(na1.*(wtA+wtB)))/wt_sum;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Fusion Artifacts (NABF) changed by B. K. Shreyamsha Kumar .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfor ii=1:p\n for jj=1:q\n if(gF(ii,jj)>gA(ii,jj) & gF(ii,jj)>gB(ii,jj))\n na(ii,jj)=1;\n else\n na(ii,jj)=0; \n end\n end\nend\nNABF=sum(sum(na.*((1-QAF).*wtA+(1-QBF).*wtB)))/wt_sum;\n\nQABF+LABF+NABF1;\nQABF+LABF+NABF;", "meta": {"author": "Linfeng-Tang", "repo": "Image-Fusion", "sha": "9e6159f4a09ece3d3a1da6f9ca444436b7012c64", "save_path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion", "path": "github-repos/MATLAB/Linfeng-Tang-Image-Fusion/Image-Fusion-9e6159f4a09ece3d3a1da6f9ca444436b7012c64/General Evaluation Metric/Evaluation/analysis_nabf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.6015020356380555}} {"text": "function d=meansqtf(b,a)\n%AVEPSPEC calculates the mean square transfer function for a filter D=(B,A)\n%\n% Inputs: B,A Numerator and denominator filter coefficients.\n%\n% Output: D The mean square transfer function of the filter B/A. This equals\n% the average otuput power when the filter is fed with unit variance\n% white noise.\n%\n% D may be obtained approximately by:\n% N=1024; D=sum(filter(B,A,[1 zeros(1,N)]).^2)\n\n% Since the power spectrum is the fourier transform of the autocorrelation, we can calculate\n% the average value of pb/pa by taking the 0'th order term of the convolution of the autocorrelation\n% functions associated with b and 1/a. Since b is an FIR filter, this convolution is\n% a finite sum even though the autocorrelation function of 1/a is infinite in extent.\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: meansqtf.m 713 2011-10-16 14:45:43Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif length(a)==1\n d=(b(:)')*b(:);\nelse\n m=lpcar2ra(b(:)');\n m(1)=m(1)*0.5;\n d=2*lpcar2rr(a(:)',length(m)-1)*m';\nend\n", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/voicebox/meansqtf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6015020167340598}} {"text": "function [X, R, S] = snapshot_gen_sto(design, doas, wavelength, t, ncov, scov)\n%SNAPSHOT_GEN_STO Generates snapshots for the stochastic model.\n%Syntax:\n% X = STO_SNAPSHOT_GEN(design, doas, wavelength[, t, ncov, scov]);\n% [X, R] = STO_SNAPSHOT_GEN(design, doas, wavelength[, t, ncov, scov]);\n% [X, R, S] = STO_SNAPSHOT_GEN(design, doas, wavelength[, t, ncov, scov]);\n%Inputs:\n% design - Array design.\n% doas - DOA vector. For 2D DOAs, each column represents a DOA pair.\n% wavelength - Wavelength.\n% t - Number of snapshots.\n% ncov - Covariance matrix of the additive complex circular-symmetric\n% Gaussian noise. Can be a scalar, vector (for uncorrelated noise\n% with different powers), or a matrix.\n% scov - Covariance matrix of the source signals. Can be a scalar, vector\n% (for uncorrelated sources with different powers), or a matrix.\n%Outputs:\n% X - Snapshots, where each columns is a single snapshot.\n% R - Sample covariance matrix (averaged by the number of snapshots).\n% S - A source_count x snapshot_count matrix consists of source signal\n% vectors.\nif nargin <= 5\n scov = 1;\nend\nif nargin <= 4\n ncov = 1;\nend\nif nargin <= 3\n t = 1;\nend\nA = steering_matrix(design, wavelength, doas);\n[m, k] = size(A);\nS_internal = gen_ccsg(k, t, scov);\nX = A * S_internal + gen_ccsg(m, t, ncov);\nif nargout >= 2\n R = (X*X')/t;\n if nargout == 3\n S = S_internal;\n end\nend\nend\n\nfunction X = gen_ccsg(m, n, cov)\nX0 = randn(m, n) + 1j * randn(m, n);\nif isscalar(cov)\n X = sqrt(cov/2) * X0;\nelseif isvector(cov)\n X = bsxfun(@times, X0, cov(:));\nelse\n C = sqrtm(cov/2);\n X = C*X0;\nend\nend", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/array/snapshot_gen_sto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6014463722698261}} {"text": "\nfunction [GAmp,GTime]=GySpiral(p)\n\nglobal VCtl;\nglobal VObj;\nglobal VVar;\n\ntStart=p.tStart;\ndt = p.dt;\n\n% 2D spiral encoding\nFOV = VCtl.FOVFreq; % choose FOVFreq as FOV\nRes = VCtl.ResFreq; % choose ResFreq as effective resolution\n\nKMax = Res/ (2*FOV);\nThetaMax = KMax / VCtl.S_Lamda;\nBeta = (VObj.Gyro/(2*pi))*(VCtl.S_SlewRate / VCtl.S_Lamda);\na2 = (9*Beta/4)^(1/3);\nCLamda = VCtl.S_SlewRate/VCtl.S_SlewRate0;\nTs = ((3*VObj.Gyro*VCtl.S_Gradient)/(4*pi*VCtl.S_Lamda*a2^2))^3;\n\nThetaTs = (0.5 * Beta * Ts^2)/(CLamda + (Beta/(2 * a2)) * Ts^(4/3));\nif ThetaTs < ThetaMax\n t1 = 0:dt:Ts;\n Theta1 = (0.5 * Beta * t1.^2)./(CLamda + (Beta/(2 * a2)) * t1.^(4/3));\n \n Tacq = t1(end) + ((pi*VCtl.S_Lamda)/(VObj.Gyro * VCtl.S_Gradient))*(ThetaMax^2 - Theta1(end)^2);\n t2 = t1(end):dt:Tacq;\n Theta2 = sqrt(Theta1(end)^2 + (VObj.Gyro / (pi * VCtl.S_Lamda))*VCtl.S_Gradient*(t2 - t1(end)));\n \n Theta = [Theta1(1:end-1) Theta2];\n t = [t1(1:end-1) t2];\n \nelse\n Tacq = ((2*pi*FOV)/(3*VCtl.S_ShotNum))*sqrt(pi/(VObj.Gyro*VCtl.S_SlewRate*VCtl.RFreq^3));\n t1 = 0:dt:Tacq;\n Theta1 = (0.5 * Beta * t1.^2)./(CLamda + (Beta/(2 * a2)) * t1.^(4/3));\n \n Theta = Theta1;\n t = t1;\nend\n\nDTheta = [0 diff(Theta)./diff(t)];\n\nGAmp = ((2*pi)/(VObj.Gyro))*VCtl.S_Lamda*DTheta.*(sin(Theta + (VVar.PhaseCount-1)*(2*pi/VCtl.S_ShotNum)) ...\n + Theta.*cos(Theta + (VVar.PhaseCount-1)*(2*pi/VCtl.S_ShotNum)));\nGTime = tStart + VCtl.TEAnchorTime + t;\n\nGTime = [GTime GTime(end) + max(VCtl.MinUpdRate,abs(GAmp(end)/VCtl.S_SlewRate))];\nGAmp = [GAmp 0];\n\n[GTime,m,n]=unique(GTime);\nGAmp=GAmp(m);\n\n\nend\n", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Macro/SeqElem/GyPE/GySpiral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.6014349802301527}} {"text": "function R = AngleAxis2RotationMatrix(angle_axis)\n\ntheta2 = dot(angle_axis,angle_axis);\nif (theta2 > 0.0)\n % We want to be careful to only evaluate the square root if the\n % norm of the angle_axis vector is greater than zero. Otherwise\n % we get a division by zero.\n \n theta = sqrt(theta2);\n wx = angle_axis(1) / theta;\n wy = angle_axis(2) / theta;\n wz = angle_axis(3) / theta;\n \n costheta = cos(theta);\n sintheta = sin(theta);\n \n R(1+0, 1+0) = costheta + wx*wx*(1 - costheta);\n R(1+1, 1+0) = wz*sintheta + wx*wy*(1 - costheta);\n R(1+2, 1+0) = -wy*sintheta + wx*wz*(1 - costheta);\n R(1+0, 1+1) = wx*wy*(1 - costheta) - wz*sintheta;\n R(1+1, 1+1) = costheta + wy*wy*(1 - costheta);\n R(1+2, 1+1) = wx*sintheta + wy*wz*(1 - costheta);\n R(1+0, 1+2) = wy*sintheta + wx*wz*(1 - costheta);\n R(1+1, 1+2) = -wx*sintheta + wy*wz*(1 - costheta);\n R(1+2, 1+2) = costheta + wz*wz*(1 - costheta);\nelse\n % At zero, we switch to using the first order Taylor expansion.\n R(1+0, 1+0) = 1;\n R(1+1, 1+0) = -angle_axis(3);\n R(1+2, 1+0) = angle_axis(2);\n R(1+0, 1+1) = angle_axis(3);\n R(1+1, 1+1) = 1;\n R(1+2, 1+1) = -angle_axis(1);\n R(1+0, 1+2) = -angle_axis(2);\n R(1+1, 1+2) = angle_axis(1);\n R(1+2, 1+2) = 1;\nend\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/depthImproveStructureIO/AngleAxis2RotationMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.6014349620509087}} {"text": "function basis_11_t6_test ( )\n\n%*****************************************************************************80\n%\n%% BASIS_11_T6_TEST verifies BASIS_11_T6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 February 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% None\n%\n node_num = 6;\n\n t = [ ...\n 2.0, 0.0; ...\n 4.0, 3.0; ...\n 0.0, 4.0; ...\n 3.0, 1.5; ...\n 2.0, 3.5; ...\n 1.0, 2.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BASIS_11_T6_TEST:\\n' );\n fprintf ( 1, ' Verify basis functions for element T6.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Physical Nodes:\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : node_num\n fprintf ( 1, ' %8d %7f %7f\\n', j, t(1:2,j) );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The basis function values at basis nodes\\n' );\n fprintf ( 1, ' should form the identity matrix.\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : node_num\n for j = 1 : node_num\n [ phi(i,j), dphidx(i,j), dphidy(i,j) ] = basis_11_t6 ( t, i, t(1:2,j) );\n end\n end\n\n for i = 1 : node_num\n for ( j = 1 : node_num )\n fprintf ( 1, ' %7f', phi(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The X and Y derivatives should sum to 0.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' dPhidX sum dPhidY sum\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : node_num\n sum_x = sum ( dphidx(1:node_num,j) );\n sum_y = sum ( dphidy(1:node_num,j) );\n fprintf ( 1, ' %14f %14f\\n', sum_x, sum_y );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/basis_11_t6_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6013174060756433}} {"text": "function nz_num = wathen_st_size ( nx, ny )\n\n%*****************************************************************************80\n%\n%% WATHEN_ST_SIZE: Size of Wathen matrix stored in sparse triplet format.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 June 2014\n%\n% Author:\n%\n% John Burkardt.\n%\n% Reference:\n%\n% Nicholas Higham,\n% Algorithm 694: A Collection of Test Matrices in MATLAB,\n% ACM Transactions on Mathematical Software,\n% Volume 17, Number 3, September 1991, pages 289-305.\n%\n% Andrew Wathen,\n% Realistic eigenvalue bounds for the Galerkin mass matrix,\n% IMA Journal of Numerical Analysis,\n% Volume 7, Number 4, October 1987, pages 449-457.\n%\n% Parameters:\n%\n% Input, integer NX, NY, values which determine the size of the matrix.\n%\n% Output, integer NZ_NUM, the number of items of data used to describe\n% the matrix.\n%\n nz_num = nx * ny * 64;\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/wathen/wathen_st_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.601317400980356}} {"text": "function log_L = Kalman_Estimation(y, psi, matur, dt, a0, P0, N, nobs, locked_parameters)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Extracting initial parameter values from initial psi \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nk = psi(1,1);\nsigmax = psi(2,1);\nlambdax = psi(3,1);\nmu = psi(4,1);\nsigmae = psi(5,1);\nrnmu = psi(6,1);\npxe = psi(7,1);\n\nif sum(locked_parameters) == 0\n k = psi(1,1);\n sigmax = psi(2,1);\n lambdax = psi(3,1);\n mu = psi(4,1);\n sigmae = psi(5,1);\n rnmu = psi(6,1);\n pxe = psi(7,1);\n \n s = zeros(1, size(psi,1)-7);\n for i = 1:size(s,2)\n s(1, i) = psi(i+7,1);\n end\nend\n \nif sum(locked_parameters) ~= 0 \n s = zeros(1, size(psi,1)-7+size(locked_parameters,1));\n j = 1;\n for i = 1:size(s,2)\n if all(abs(i-(locked_parameters))) == 1\n s(1, i) = psi(7+j,1);\n j = j+1;\n end\n end\nend\n\n\n \n% m = Number of state variables (number of rows in a0)\nm = size(a0,1);\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% THE TRANSITION EQUATION \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% S&S NOTATION: x(t)=c+G*x(t-1)+w(t) w~N(0,W) Equation (14)\n% NEW NOTATION: a(t)=c+T*a(t-1)+R(t)*n(t) n~N(0,Q)\n\n% c is a {m x 1} Vector\n% T is a {m x m} Matrix\nc=[0;mu*dt];\nT=[exp(-k*dt),0;0,1];\n\n% Defining Q = var[n(t)] and R\nxx=(1-exp(-2*k*dt))*(sigmax)^2/(2*k);\nxy=(1-exp(-k*dt))*pxe*sigmax*sigmae/k;\nyx=(1-exp(-k*dt))*pxe*sigmax*sigmae/k;\nyy=(sigmae)^2*dt;\nQ=[xx,xy;yx,yy];\nR=eye(size(Q,1));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% THE MEASUREMENT EQUATION \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% S&S NOTATION: y(t)=d(t)+F(t)'x(t)+v(t) v~N(0,V) Equation (15)\n% NEW NOTATION: y(t)=d(t)+Z(t)a(t)+e(t) e~N(0,H)\n\n% d is a {N x 1} Vector\n% Z is a {N x m} Matrix\n for i=1:N\n p1=(1-exp(-2*k*matur(i)))*(sigmax)^2/(2*k);\n p2=(sigmae)^2*matur(i);\n p3=2*(1-exp(-k*matur(i)))*pxe*sigmax*sigmae/k;\n d(i,1)=rnmu*matur(i)-(1-exp(-k*matur(i)))*lambdax/k+.5*(p1+p2+p3);\n Z(i,1)=exp(-k*matur(i));\n Z(i,2)=1;\n end\n\n% Measurment errors Var-Cov Matrix: Cov[e(t)]=H\nH=diag(s);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RUNNING THE KALMAN FILTER\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Creating placeholder vectors/matrices for variables to be stored in\nglobal save_vt save_att save_dFtt_1 save_vFv save_vtt save_Ptt_1 save_Ftt_1 save_Ptt\n\nsave_ytt_1 = zeros(nobs,N);\nsave_vtt = zeros(nobs,N);\nsave_vt = zeros(nobs,N);\nsave_att_1 = zeros(nobs,m);\nsave_att = zeros(nobs,m); \nsave_Ptt_1 = zeros(nobs,m*m); \nsave_Ptt = zeros(nobs,m*m);\nsave_Ftt_1 = zeros(nobs,N*N);\nsave_dFtt_1 = zeros(nobs,1);\nsave_vFv = zeros(nobs,1);\n%save_log_Lt = zeros(nobs,1);\n\nPtt = P0;\natt = a0; \n\n% Running the kalman filter for t = 1,...,nobs\n for t = 1:nobs\n Ptt_1 = T*Ptt*T'+R*Q*R';\n Ftt_1 = Z*Ptt_1*Z'+H;\n dFtt_1 = det(Ftt_1);\n \n %Ptt_1_test = [Ptt_1(1,1) 0; 0 Ptt_1(2,2)];\n %Ftt_1_test = Z*Ptt_1_test*Z'+H;\n %dFtt_1_test = det(Ftt_1_test);\n \n \n att_1 = T*att + c;\n yt = y(t,:)';\n ytt_1 = Z*att_1+d;\n vt = yt-ytt_1;\n\n att = att_1 + Ptt_1*Z'*inv(Ftt_1)*(vt);\n Ptt = Ptt_1 - Ptt_1*Z'*inv(Ftt_1)*Z*Ptt_1;\n \n ytt = Z*att+d;\n vtt = yt-ytt;\n\n % save_ytt_1(t,:) = ytt_1';\n save_vtt(t,:) = vtt';\n save_vt(t,:) = (vt)';\n % save_att_1(t,:) = att_1';\n save_att(t,:) = att';\n save_Ptt_1(t,:) = [Ptt_1(1,1), Ptt_1(1,2), Ptt_1(2,1), Ptt_1(2,2)]; \n save_Ptt(t,:) = [Ptt(1,1), Ptt(1,2), Ptt(2,1), Ptt(2,2)];\n % save_Ftt_1(t,:) = [Ftt_1(1,1), Ftt_1(1,2), Ftt_1(1,3), Ftt_1(1,4), Ftt_1(1,5), Ftt_1(2,1), Ftt_1(2,2), Ftt_1(2,3), Ftt_1(2,4), Ftt_1(2,5), Ftt_1(3,1), Ftt_1(3,2), Ftt_1(3,3), Ftt_1(3,4), Ftt_1(3,5), Ftt_1(4,1), Ftt_1(4,2), Ftt_1(4,3), Ftt_1(4,4), Ftt_1(5,5), Ftt_1(5,1), Ftt_1(5,2), Ftt_1(5,3), Ftt_1(5,4), Ftt_1(5,5)];\n \n %save_dFtt_1(t,:)= dFtt_1_test;\n %save_vFv(t,:) = vt'*inv(Ftt_1_test)*vt;\n save_dFtt_1(t,:)= dFtt_1;\n save_vFv(t,:) = vt'*inv(Ftt_1)*vt;\n \n end\n\n \nlogL = -(N*nobs/2)*log(2*pi)-0.5*sum(log(save_dFtt_1))-0.5*sum(save_vFv);\n% logL = -(N*nobs/2)*log(2*pi)-0.5*sum(save_vFv);\n% logL = sum(diag(save_vt'*save_vt));\nlog_L = -logL;\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/43352-schwartz-smith-2-factor-model-parameter-estimation/ss2000estim/Kalman_Estimation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6013139654397791}} {"text": "function [out] = soilmoisture_1(S1,S1max,S2,S2max)\n%soilmoisture_1 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Water rebalance to equal relative storage (2 stores)\n% Constraints: -\n% @(Inputs): S1 - current storage in S1 [mm]\n% S1max - maximum storage in S1 [mm]\n% S2 - current storage in S2 [mm]\n% S2max - maximum storage in S2 [mm]\n\nout = ((S2.*S1max-S1.*S2max)/(S1max+S2max)).*smoothThreshold_storage_logistic(S1./S1max,S2./S2max);\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/soilmoisture_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6012955426650484}} {"text": "function [f,G,H] = self_collision_barrier(V,E,tol)\n % SELF_COLLISION_BARRIER Compute the a barrier function (and its derivatives)\n % for point-edge collisions of a given *strictly feasible** line-complex in\n % 2D. See \"Bijective Parameterization with Free Boundaries\" [Smith and\n % Schaefer 2015] or for a similar barrier \"Incremental Potential Contact:\n % Intersection- and Inversion-free, Large-Deformation Dynamics\" [Li et al.\n % 2020].\n % \n % [f,G,H] = self_collision_barrier(V,E,tol)\n %\n % Inputs:\n % V #V by 2 list of input vertex positions\n % E #E by 2 list of edge indices into rows of V\n % tol distance at which barrier term becomes positive {1e-3}\n % Outputs:\n % f scalar total objective value\n % G #V*2 gradient \n % H #V*2 by #V*2 sparse Hessian matrix\n %\n % Note: this function uses a special symbolic library trick which generates\n % files self_collision_barrier_cap_sym.m and self_collision_barrier_line_sym.m\n % if they don't already exist. If your change the symbolic-math part of this\n % file, you must delete these automatically generated files.\n %\n\n function [sqrD,T] = point_segment_squared_distance(P,A,B)\n PA = P-A;\n BA = B-A;\n T = min(max(sum(PA.*BA,2)./sum(BA.^2,2),0),1);\n % vector to closest point\n PC = PA-BA.*T;\n sqrD = sum(PC.^2,2);\n end\n\n function [f,G,H] = self_collision_barrier_cap(V,E,IJ)\n % vertex i colliding with edge jk\n\n n = size(V,1);\n % [x x x y y y]\n IJ = [IJ n+IJ];\n X = V(IJ);\n\n %% Sanity check\n %p = X(:,1:2:end);\n %c = X(:,2:2:end);\n %pc = p-c;\n %d = sqrt(sum(pc.^2,2));\n %if ~isempty(d) && max(d) > tol && nargout > 1\n % error\n %end\n\n % Writing the symbol\n path = mfilename('fullpath');\n aux = [path '_cap_sym.m'];\n % should also check date...\n if ~exist(aux,'file')\n % From here, only touch X\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n sX = sym('X',[1 4]);\n stol = sym('tol',[1 1]);\n sp = sX(1:2:end);\n sc = sX(2:2:end);\n spc = sp-sc;\n sd = sqrt(sum(spc.^2,2));\n sf = barrier(sd,stol);\n\n hess = @(sf,sX) cell2sym(arrayfun(@(g) gradient(g,sX),gradient(sf,sX),'UniformOutput',false));\n\n aux_handle = ...\n matlabFunction(sf,gradient(sf,sX),hess(sf,sX),'vars',{sX,stol},'File',aux);\n else\n aux_name = [mfilename('func') '_cap_sym'];\n aux_handle = str2func(aux_name);\n end\n\n faux=[];gaux = [];Haux = [];\n switch nargout\n case {0,1}\n [faux] = aux_handle(X,tol);\n case 2\n [faux,gaux] = aux_handle(X,tol);\n case 3\n [faux,gaux,Haux] = aux_handle(X,tol);\n end\n\n % unnecessary indirection?\n f_fun = @(X) faux;\n dfdX_fun = @(X) gaux;\n d2fdX2_fun = @(X) Haux;\n f = sum(f_fun(X));\n if nargout<=1\n return;\n end\n dfdX = dfdX_fun(X);\n G = full_sparse(IJ,ones(size(IJ)),reshape(dfdX,size(IJ)),2*n,1);\n if nargout<=2\n return;\n end\n d2fdX2 = double(d2fdX2_fun(X));\n\n\n d2fdX2 = reshape(d2fdX2,[],4*4);\n if psd_project\n d2fdX2 = psd_project_rows(d2fdX2);\n end\n\n HI = repmat(IJ,[1 1 size(IJ,2)]);\n HJ = permute(repmat(IJ,[1 1 size(IJ,2)]),[1 3 2]);\n H = fast_sparse(HI(:),HJ(:),d2fdX2(:),2*n,2*n);\n end\n\n function [f,G,H] = self_collision_barrier_line(V,E,IJK)\n\n n = size(V,1);\n % [x x x y y y]\n IJK = [IJK n+[IJK]];\n X = V(IJK);\n\n %% Sanity check\n %p = X(:,1:3:end);\n %a = X(:,2:3:end);\n %b = X(:,3:3:end);\n %pa = p-a;\n %ba = b-a;\n %t = sum(pa.*ba,2)./sum(ba.^2,2);\n %pc = pa - ba.*t;\n %d = sqrt(sum(pc.^2,2));\n %if ~isempty(d) && max(d) > tol && nargout > 1\n % error\n %end\n\n % Writing the symbol\n path = mfilename('fullpath');\n aux = [path '_line_sym.m'];\n % should also check date...\n if ~exist(aux,'file')\n % From here, only touch X\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n sX = sym('X',[1 6]);\n stol = sym('tol',[1 1]);\n sp = sX(1:3:end);\n sa = sX(2:3:end);\n sb = sX(3:3:end);\n spa = sp-sa;\n sba = sb-sa;\n st = sum(spa.*sba,2)./sum(sba.^2,2);\n spc = spa - sba.*st;\n sd = sqrt(sum(spc.^2,2));\n sf = barrier(sd,stol);\n\n hess = @(sf,sX) cell2sym(arrayfun(@(g) gradient(g,sX),gradient(sf,sX),'UniformOutput',false));\n aux_handle = ...\n matlabFunction(sf,gradient(sf,sX),hess(sf,sX),'vars',{sX,stol},'File',aux);\n else\n aux_name = [mfilename('func') '_line_sym'];\n aux_handle = str2func(aux_name);\n end\n\n faux=[];gaux = [];Haux = [];\n switch nargout\n case {0,1}\n [faux] = aux_handle(X,tol);\n case 2\n [faux,gaux] = aux_handle(X,tol);\n case 3\n [faux,gaux,Haux] = aux_handle(X,tol);\n end\n\n % unnecessary indirection?\n f_fun = @(X) faux;\n dfdX_fun = @(X) gaux;\n d2fdX2_fun = @(X) Haux;\n f = sum(f_fun(X));\n if nargout<=1\n return;\n end\n dfdX = dfdX_fun(X);\n G = full_sparse(IJK,ones(size(IJK)),reshape(dfdX,size(IJK)),2*n,1);\n if nargout<=2\n return;\n end\n d2fdX2 = double(d2fdX2_fun(X));\n\n d2fdX2 = reshape(d2fdX2,[],6*6);\n if psd_project\n d2fdX2 = psd_project_rows(d2fdX2);\n end\n\n HI = repmat(IJK,[1 1 size(IJK,2)]);\n HJ = permute(repmat(IJK,[1 1 size(IJK,2)]),[1 3 2]);\n H = fast_sparse(HI(:),HJ(:),d2fdX2(:),2*n,2*n);\n\n end\n\n psd_project = true;\n % The max is not needed because we're handling that explicitly\n % \n % Smith and Schaefer\n %barrier = @(d,tol) (tol./d - 1).^2;\n % IPC\n barrier = @(D,tol) -(D-tol).^2.*log(D./tol);\n\n b = unique(E);\n [b1,b2] = box_each_element(V,b);\n [E1,E2] = box_each_element(V,E);\n I = box_intersect(b1-tol,b2+tol,E1-tol,E2+tol);\n I = I(~any(b(I(:,1))==E(I(:,2),:),2),:);\n BC = barycenter(V,E);\n\n [sqrD,T] = point_segment_squared_distance(V(b(I(:,1)),:),V(E(I(:,2),1),:),V(E(I(:,2),2),:));\n\n keep = find(sqrD= 1/C_1*beta^(1-C.exponent)\n % even Res < beta^(-INTLAB_LONG_PRECISION) because Newton iteration\n % stopped with Res==1 in precision INTLAB_LONG_PRECISION+1; this\n % is important if 1/C is exactly representable in fewer than\n % INTLAB_LONG_PRECISION+1 beta-digits (thanks to Kurt Zehetleitner)\n precCinv = size(Cinv.mantissa,2);\n Cmant = C.mantissa(:,1);\n if precC>1\n Cmant = Cmant + C.mantissa(:,2)/INTLAB_LONG_BETA;\n end\n Cinv.error = ...\n errorupdate( -Cmant , 1 , 1-C.exponent-INTLAB_LONG_PRECISION );\n\n % error introduced by B: B.error/(sqr(B)-sqr(B.error))\n Bmant = B.mantissa(:,1);\n if size(B.mantissa,2)>1\n Bmant = Bmant + B.mantissa(:,2)/INTLAB_LONG_BETA;\n end\n setround(1)\n N = ( B.error.mant .* INTLAB_LONG_BETA.^(B.error.exp-B.exponent) ) .^ 2;\n setround(-1)\n N = ( Bmant/INTLAB_LONG_BETA ) .^ 2 - N;\n % true denominator N*beta^(2*B.exponent)\n\n % check zero denominator (including error)\n if any( N<=0 )\n error('long division by zero')\n end\n\n % first part: B.error/(sqr(B)-sqr(B.error))\n Cinv.error = errorupdate( 1 , Cinv.error , 0 , ...\n -N , B.error , -2*B.exponent );\n Cinv.error = errornormalize(Cinv.error);\n end\n\n C = A*Cinv;\n\n end\n \n setround(rndold)\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/toolboxes/Intlab_V7.1/long/@long/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6011236860699416}} {"text": "% this is an experimentaal spiral sequence\n\nfov=256e-3; Nx=96; Ny=Nx; % Define FOV and resolution\nsliceThickness=3e-3; % slice thinckness\nNslices=1;\nOversampling=2; % by looking at the periphery of the spiral I would say it needs to be at least 2\nphi=pi/2; % orientation of the readout e.g. for interleaving\n\n% Set system limits\nsys = mr.opts('MaxGrad',30,'GradUnit','mT/m',...\n 'MaxSlew',120,'SlewUnit','T/m/s',...\n 'rfRingdownTime', 30e-6, 'rfDeadtime', 100e-6, 'adcDeadTime', 10e-6); \nseq=mr.Sequence(sys); % Create a new sequence object\nwarning('OFF', 'mr:restoreShape'); % restore shape is not compatible with spirals and will throw a warning from each plot() or calcKspace() call\n\n% Create fat-sat pulse \n% (in Siemens interpreter from January 2019 duration is limited to 8.192 ms, and although product EPI uses 10.24 ms, 8 ms seems to be sufficient)\nB0=2.89; % 1.5 2.89 3.0\nsat_ppm=-3.45;\nsat_freq=sat_ppm*1e-6*B0*sys.gamma;\nrf_fs = mr.makeGaussPulse(110*pi/180,'system',sys,'Duration',8e-3,...\n 'bandwidth',abs(sat_freq),'freqOffset',sat_freq);\ngz_fs = mr.makeTrapezoid('z',sys,'delay',mr.calcDuration(rf_fs),'Area',1/1e-4); % spoil up to 0.1mm\n\n% Create 90 degree slice selection pulse and gradient\n[rf, gz] = mr.makeSincPulse(pi/2,'system',sys,'Duration',3e-3,...\n 'SliceThickness',sliceThickness,'apodization',0.5,'timeBwProduct',4);\n\n% define k-space parameters\ndeltak=1/fov;\nkRadius = round(Nx/2);\nkSamples=round(2*pi*kRadius)*Oversampling;\nreadoutTime = 4.2e-4;\n\n% calculate a raw Archimedian spiral trajectory\nclear ka;\nka(kRadius*kSamples+1)=1i; % init as complex\nfor c=0:kRadius*kSamples\n r=deltak*c/kSamples;\n a=mod(c,kSamples)*2*pi/kSamples;\n ka(c+1)=r*exp(1i*a);\nend\nka=[real(ka); imag(ka)];\n% calculate gradients and slew rates\n[ga, sa]=mr.traj2grad(ka);\n\n% limit analysis\nsafety_magrin=0.94; % we need that otherwise we just about violate the slew rate due to the rounding errors\ndt_gcomp=abs(ga)/(sys.maxGrad*safety_magrin)*sys.gradRasterTime;\ndt_gabs=abs(ga(1,:)+1i*ga(2,:))/(sys.maxGrad*safety_magrin)*sys.gradRasterTime;\ndt_scomp=sqrt(abs(sa)/(sys.maxSlew*safety_magrin))*sys.gradRasterTime;\ndt_sabs=sqrt(abs(sa(1,:)+1i*sa(2,:))/(sys.maxSlew*safety_magrin))*sys.gradRasterTime;\n\nfigure;plot([dt_gabs; max(dt_gcomp); dt_sabs; max(dt_scomp)]');title('time stepping defined by gradient and slew-rate');\n\ndt_smooth=max([dt_gabs;dt_sabs]);\ndt_rough=max([dt_gcomp;dt_scomp]);\n\n% apply the lower limit not to lose the trajectory detail\ndt_min=4*sys.gradRasterTime/kSamples; % we want at least 4 points per revolution\ndt_smooth0=dt_smooth;\ndt_rough0=dt_rough;\ndt_smooth(dt_smootheps \n error('ADC segmentation model results in incorrect segment duration');\nend\n% update segment count\nadcSegments=floor(adcTime/adcSegmentDuration);\nadcSamples=adcSegments*adcSamplesPerSegment;\nadc = mr.makeAdc(adcSamples,'Dwell',adcDwell,'Delay',mr.calcDuration(gzReph));%lims.adcDeadTime);\n\n% extend spiral_grad_shape by repeating the last sample\n% this is needed to accomodate for the ADC tuning delay\nspiral_grad_shape = [spiral_grad_shape spiral_grad_shape(:,end)];\n\n% readout grad \ngx = mr.makeArbitraryGrad('x',spiral_grad_shape(1,:),'Delay',mr.calcDuration(gzReph));\ngy = mr.makeArbitraryGrad('y',spiral_grad_shape(2,:),'Delay',mr.calcDuration(gzReph));\n\n% spoilers\ngz_spoil=mr.makeTrapezoid('z',sys,'Area',deltak*Nx*4);\ngx_spoil=mr.makeExtendedTrapezoid('x','times',[0 mr.calcDuration(gz_spoil)],'amplitudes',[spiral_grad_shape(1,end),0]); %todo: make a really good spoiler\ngy_spoil=mr.makeExtendedTrapezoid('y','times',[0 mr.calcDuration(gz_spoil)],'amplitudes',[spiral_grad_shape(2,end),0]); %todo: make a really good spoiler\n\n% because of the ADC alignment requirements the sampling window possibly\n% extends past the end of the trajectory (these points will have to be\n% discarded in the reconstruction, which is no problem). However, the\n% ramp-down parts and the Z-spoiler now have to be added to the readout\n% block otherwise there will be a gap inbetween\n% gz_spoil.delay=mr.calcDuration(gx);\n% gx_spoil.delay=gz_spoil.delay;\n% gy_spoil.delay=gz_spoil.delay;\n% gx_combined=mr.addGradients([gx,gx_spoil], lims);\n% gy_combined=mr.addGradients([gy,gy_spoil], lims);\n% gz_combined=mr.addGradients([gzReph,gz_spoil], lims);\n \n% Define sequence blocks\nfor s=1:Nslices\n seq.addBlock(rf_fs,gz_fs); % fat-sat \n rf.freqOffset=gz.amplitude*sliceThickness*(s-1-(Nslices-1)/2);\n seq.addBlock(rf,gz);\n seq.addBlock(mr.rotate('z',phi,gzReph,gx,gy,adc));\n seq.addBlock(mr.rotate('z',phi,gx_spoil,gy_spoil,gz_spoil));\n %seq.addBlock(gx_combined,gy_combined,gz_combined,adc);\nend\n\n% check whether the timing of the sequence is correct\n[ok, error_report]=seq.checkTiming;\n\nif (ok)\n fprintf('Timing check passed successfully\\n');\nelse\n fprintf('Timing check failed! Error listing follows:\\n');\n fprintf([error_report{:}]);\n fprintf('\\n');\nend\n\n%\nseq.setDefinition('FOV', [fov fov sliceThickness]);\nseq.setDefinition('Name', 'spiral');\nseq.setDefinition('MaxAdcSegmentLength', adcSamplesPerSegment);\n\nseq.write('spiral.seq'); % Output sequence for scanner\n\n% the sequence is ready, so let's see what we got \nseq.plot(); % Plot sequence waveforms\n\n%% k-space trajectory calculation\n[ktraj_adc, t_adc, ktraj, t_ktraj, t_excitation, t_refocusing] = seq.calculateKspacePP();\n\n% plot k-spaces\nfigure; plot(t_ktraj, ktraj'); title('k-space components as functions of time'); % plot the entire k-space trajectory\nfigure; plot(ktraj(1,:),ktraj(2,:),'b'); % a 2D plot\nhold;plot(ktraj_adc(1,:),ktraj_adc(2,:),'r.'); title('2D k-space');\n\n% seq.install('siemens');\n", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/demoSeq/writeSpiral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6011236673923699}} {"text": "function im_ext = bound_extension(im,By,Bx,type);\n\n% im_ext = bound_extension(im,B,type);\n%\n% Extend an image for avoiding boundary artifacts,\n%\n% By, Bx: widths of the added stripes.\n% type: 'mirror' Mirror extension\n% 'mirror_nr': Mirror without repeating the last pixel\n% 'circular': fft2-like\n% 'zeros'\n\n% Javier Portilla, Universidad de Granada, Jan 2004\n\n[Ny,Nx,Nc] = size(im);\n\nim_ext = zeros(Ny+2*By,Nx+2*Bx,Nc);\nim_ext(By+1:Ny+By,Bx+1:Nx+Bx,:) = im;\n\nif strcmp(type,'mirror'),\n\n im_ext(1:By,:,:) = im_ext(2*By:-1:By+1,:,:);\n im_ext(:,1:Bx,:) = im_ext(:,2*Bx:-1:Bx+1,:);\n im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(Ny+By:-1:Ny+1,:,:);\n im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Nx+Bx:-1:Nx+1,:);\n im_ext(1:By,1:Bx,:) = im_ext(2*By:-1:By+1,2*Bx:-1:Bx+1,:);\n im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+By:-1:Ny+1,Nx+Bx:-1:Nx+1,:);\n im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(2*By:-1:By+1,Nx+Bx:-1:Nx+1,:);\n im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(Ny+By:-1:Ny+1,2*Bx:-1:Bx+1,:);\n\nelseif strcmp(type,'mirror_nr'), \n \n im_ext(1:By,:,:) = im_ext(2*By+1:-1:By+2,:,:);\n im_ext(:,1:Bx,:) = im_ext(:,2*Bx+1:-1:Bx+2,:);\n im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(Ny+By-1:-1:Ny,:,:);\n im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Nx+Bx-1:-1:Nx,:);\n im_ext(1:By,1:Bx,:) = im_ext(2*By+1:-1:By+2,2*Bx+1:-1:Bx+2,:);\n im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+By-1:-1:Ny,Nx+Bx-1:-1:Nx,:);\n im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(2*By+1:-1:By+2,Nx+Bx-1:-1:Nx,:);\n im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(Ny+By-1:-1:Ny,2*Bx+1:-1:Bx+2,:);\n \nelseif strcmp(type,'circular'), \n \n im_ext(1:By,:,:) = im_ext(Ny+1:Ny+By,:,:);\n im_ext(:,1:Bx,:) = im_ext(:,Nx+1:Nx+Bx,:);\n im_ext(Ny+1+By:Ny+2*By,:,:) = im_ext(By+1:2*By,:,:);\n im_ext(:,Nx+1+Bx:Nx+2*Bx,:) = im_ext(:,Bx+1:2*Bx,:);\n im_ext(1:By,1:Bx,:) = im_ext(Ny+1:Ny+By,Nx+1:Nx+Bx,:);\n im_ext(Ny+1+By:Ny+2*By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(By+1:2*By,Bx+1:2*Bx,:);\n im_ext(1:By,Nx+1+Bx:Nx+2*Bx,:) = im_ext(Ny+1:Ny+By,Bx+1:2*Bx,:);\n im_ext(Ny+1+By:Ny+2*By,1:Bx,:) = im_ext(By+1:2*By,Nx+1:Nx+Bx,:);\n \nend \n ", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Packages/BLS-GSM/Added_PyrTools/bound_extension.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6011135972036693}} {"text": "function hf = r8_hyper_2f1 ( a, b, c, x )\n\n%*****************************************************************************80\n%\n%% R8_HYPER_2F1 evaluates the hypergeometric function F(A,B,C,X).\n%\n% Discussion:\n%\n% A minor bug was corrected. The HW variable, used in several places as\n% the \"old\" value of a quantity being iteratively improved, was not\n% being initialized. JVB, 11 February 2008.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 11 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Shanjie Zhang, Jianming Jin.\n% MATLAB version by John Burkardt.\n%\n% The F77 original version of this routine is copyrighted by\n% Shanjie Zhang and Jianming Jin. However, they give permission to\n% incorporate this routine into a user program provided that the copyright\n% is acknowledged.\n%\n% Reference:\n%\n% Shanjie Zhang, Jianming Jin,\n% Computation of Special Functions,\n% Wiley, 1996,\n% ISBN: 0-471-11963-6,\n% LC: QA351.C45\n%\n% Parameters:\n%\n% Input, real A, B, C, X, the arguments of the function.\n% C must not be equal to a nonpositive integer.\n% X < 1.\n%\n% Output, real HF, the value of the function.\n%\n el = 0.5772156649015329;\n\n l0 = ( c == floor ( c ) ) && ( c < 0.0 );\n l1 = ( 1.0 - x < 1.0E-15 ) && ( c - a - b <= 0.0 );\n l2 = ( a == floor ( a ) ) && ( a < 0.0 );\n l3 = ( b == floor ( b ) ) && ( b < 0.0 );\n l4 = ( c - a == floor ( c - a ) ) && ( c - a <= 0.0 );\n l5 = ( c - b == floor ( c - b ) ) && ( c - b <= 0.0 );\n\n if ( l0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_HYPER_2F1 - Fatal error!\\n' );\n fprintf ( 1, ' The hypergeometric series is divergent.\\n' );\n fprintf ( 1, ' C is integral and negative.\\n' );\n fprintf ( 1, ' C = %f\\n', c );\n error ( 'R8_HYPER_F1 - Fatal error!' );\n end\n\n if ( l1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_HYPER_2F1 - Fatal error!\\n' );\n fprintf ( 1, ' The hypergeometric series is divergent.\\n' );\n fprintf ( 1, ' 1 = X < 0, C - A - B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' C = %f\\n', c );\n fprintf ( 1, ' X = %f\\n', x );\n error ( 'R8_HYPER_F1 - Fatal error!' );\n end\n\n if ( 0.95 < x )\n eps = 1.0E-08;\n else\n eps = 1.0E-15;\n end\n\n if ( x == 0.0 || a == 0.0 || b == 0.0 )\n\n hf = 1.0;\n return\n\n elseif ( 1.0 - x == eps && 0.0 < c - a - b )\n\n gc = gamma ( c );\n gcab = gamma ( c - a - b );\n gca = gamma ( c - a );\n gcb = gamma ( c - b );\n hf = gc * gcab / ( gca * gcb );\n return\n\n elseif ( 1.0 + x <= eps && abs ( c - a + b - 1.0 ) <= eps )\n\n g0 = sqrt ( pi ) * 2.0^( - a );\n g1 = gamma ( c );\n g2 = gamma ( 1.0 + a / 2.0 - b );\n g3 = gamma ( 0.5 + 0.5 * a );\n hf = g0 * g1 / ( g2 * g3 );\n return\n\n elseif ( l2 || l3 )\n\n if ( l2 )\n nm = floor ( abs ( a ) );\n end\n\n if ( l3 )\n nm = floor ( abs ( b ) );\n end\n\n hf = 1.0;\n r = 1.0;\n\n for k = 1 : nm\n r = r * ( a + k - 1.0 ) * ( b + k - 1.0 ) ...\n / ( k * ( c + k - 1.0 ) ) * x;\n hf = hf + r;\n end\n\n return\n\n elseif ( l4 || l5 )\n\n if ( l4 )\n nm = floor ( abs ( c - a ) );\n end\n\n if ( l5 )\n nm = floor ( abs ( c - b ) );\n end\n\n hf = 1.0;\n r = 1.0;\n for k = 1 : nm\n r = r * ( c - a + k - 1.0 ) * ( c - b + k - 1.0 ) ...\n / ( k * ( c + k - 1.0 ) ) * x;\n hf = hf + r;\n end\n hf = ( 1.0 - x )^( c - a - b ) * hf;\n return\n\n end\n\n aa = a;\n bb = b;\n x1 = x;\n\n if ( x < 0.0 )\n x = x / ( x - 1.0 );\n if ( a < c && b < a && 0.0 < b )\n a = bb;\n b = aa;\n end\n b = c - b;\n end\n\n if ( 0.75 <= x )\n\n gm = 0.0;\n\n if ( abs ( c - a - b - floor ( c - a - b ) ) < 1.0E-15 )\n\n m = floor ( c - a - b );\n ga = gamma ( a );\n gb = gamma ( b );\n gc = gamma ( c );\n gam = gamma ( a + m );\n gbm = gamma ( b + m );\n\n pa = r8_psi ( a );\n pb = r8_psi ( b );\n\n if ( m ~= 0 )\n gm = 1.0;\n end\n\n for j = 1 : abs ( m ) - 1\n gm = gm * j;\n end\n\n rm = 1.0;\n for j = 1 : abs ( m )\n rm = rm * j;\n end\n\n f0 = 1.0;\n r0 = 1.0;\n r1 = 1.0;\n sp0 = 0.0;\n sp = 0.0;\n\n if ( 0 <= m )\n\n c0 = gm * gc / ( gam * gbm );\n c1 = - gc * ( x - 1.0 )^m / ( ga * gb * rm );\n\n for k = 1 : m - 1\n r0 = r0 * ( a + k - 1.0 ) * ( b + k - 1.0 ) ...\n / ( k * ( k - m ) ) * ( 1.0 - x );\n f0 = f0 + r0;\n end\n\n for k = 1 : m\n sp0 = sp0 + 1.0 / ( a + k - 1.0 ) ...\n + 1.0 / ( b + k - 1.0 ) - 1.0 / k;\n end\n\n f1 = pa + pb + sp0 + 2.0 * el + log ( 1.0 - x );\n hw = f1;\n\n for k = 1 : 250\n\n sp = sp + ( 1.0 - a ) / ( k * ( a + k - 1.0 ) ) ...\n + ( 1.0 - b ) / ( k * ( b + k - 1.0 ) );\n\n sm = 0.0;\n for j = 1 : m\n sm = sm + ( 1.0 - a ) ...\n / ( ( j + k ) * ( a + j + k - 1.0 ) ) ...\n + 1.0 / ( b + j + k - 1.0 );\n end\n\n rp = pa + pb + 2.0 * el + sp + sm + log ( 1.0 - x );\n\n r1 = r1 * ( a + m + k - 1.0 ) * ( b + m + k - 1.0 ) ...\n / ( k * ( m + k ) ) * ( 1.0 - x );\n\n f1 = f1 + r1 * rp;\n\n if ( abs ( f1 - hw ) < abs ( f1 ) * eps )\n break\n end\n\n hw = f1;\n\n end\n\n hf = f0 * c0 + f1 * c1;\n\n elseif ( m < 0 )\n\n m = - m;\n c0 = gm * gc / ( ga * gb * ( 1.0 - x )^m );\n c1 = - ( - 1 )^m * gc / ( gam * gbm * rm );\n\n for k = 1 : m - 1\n r0 = r0 * ( a - m + k - 1.0 ) * ( b - m + k - 1.0 ) ...\n / ( k * ( k - m ) ) * ( 1.0 - x );\n f0 = f0 + r0;\n end\n\n for k = 1 : m\n sp0 = sp0 + 1.0 / k;\n end\n\n f1 = pa + pb - sp0 + 2.0 * el + log ( 1.0 - x );\n hw = f1;\n\n for k = 1 : 250\n\n sp = sp + ( 1.0 - a ) ...\n / ( k * ( a + k - 1.0 ) ) ...\n + ( 1.0 - b ) / ( k * ( b + k - 1.0 ) );\n\n sm = 0.0;\n for j = 1 : m\n sm = sm + 1.0 / ( j + k );\n end\n\n rp = pa + pb + 2.0 * el + sp - sm + log ( 1.0 - x );\n\n r1 = r1 * ( a + k - 1.0 ) * ( b + k - 1.0 ) ...\n / ( k * ( m + k ) ) * ( 1.0 - x );\n\n f1 = f1 + r1 * rp;\n\n if ( abs ( f1 - hw ) < abs ( f1 ) * eps )\n break\n end\n\n hw = f1;\n\n end\n\n hf = f0 * c0 + f1 * c1;\n\n end\n\n else\n\n ga = gamma ( a );\n gb = gamma ( b );\n gc = gamma ( c );\n gca = gamma ( c - a );\n gcb = gamma ( c - b );\n gcab = gamma ( c - a - b );\n gabc = gamma ( a + b - c );\n c0 = gc * gcab / ( gca * gcb );\n c1 = gc * gabc / ( ga * gb ) * ( 1.0 - x )^( c - a - b );\n hf = 0.0;\n hw = hf;\n r0 = c0;\n r1 = c1;\n\n for k = 1 : 250\n\n r0 = r0 * ( a + k - 1.0 ) * ( b + k - 1.0 ) ...\n / ( k * ( a + b - c + k ) ) * ( 1.0 - x );\n\n r1 = r1 * ( c - a + k - 1.0 ) * ( c - b + k - 1.0 ) ...\n / ( k * ( c - a - b + k ) ) * ( 1.0 - x );\n\n hf = hf + r0 + r1;\n\n if ( abs ( hf - hw ) < abs ( hf ) * eps )\n break\n end\n\n hw = hf;\n\n end\n\n hf = hf + c0 + c1;\n\n end\n\n else\n\n a0 = 1.0;\n\n if ( a < c && c < 2.0 * a && b < c && c < 2.0 * b )\n\n a0 = ( 1.0 - x )^( c - a - b );\n a = c - a;\n b = c - b;\n\n end\n\n hf = 1.0;\n hw = hf;\n r = 1.0;\n\n for k = 1 : 250\n\n r = r * ( a + k - 1.0 ) * ( b + k - 1.0 ) ...\n / ( k * ( c + k - 1.0 ) ) * x;\n\n hf = hf + r;\n\n if ( abs ( hf - hw ) <= abs ( hf ) * eps )\n break\n end\n\n hw = hf;\n\n end\n\n hf = a0 * hf;\n\n end\n\n if ( x1 < 0.0 )\n x = x1;\n c0 = 1.0 / ( 1.0 - x )^aa;\n hf = c0 * hf;\n end\n\n if ( 120 < k )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_HYPER_2F1 - Warning!\\n' );\n fprintf ( 1, ' A large number of iterations were needed.\\n' );\n fprintf ( 1, ' The accuracy of the results should be checked.\\n' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/r8_hyper_2f1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.601068428312363}} {"text": "function [out] = melt_3(p1,p2,T,S1,S2,St,dt,varargin)\n%melt_3 \n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% Flux function\n% ------------------\n% Description: Glacier melt provided no snow is stored on the ice layer\n% Constraints: f <= S1/dt\n% @(Inputs): p1 - degree-day factor [mm/oC/d]\n% p2 - temperature threshold for snowmelt [oC]\n% T - current temperature [oC]\n% S1 - current storage in glacier [mm]\n% S2 - current storage in snowpack [mm]\n% St - storage in S2 threshold below which glacier melt occurs [mm]\n% dt - time step size [d]\n% varargin(1) - smoothing variable r (default 0.01)\n% varargin(2) - smoothing variable e (default 5.00)\n\nif size(varargin,2) == 0\n out = min(max(p1*(T-p2),0),S1/dt).*smoothThreshold_storage_logistic(S2,St);\nelseif size(varargin,2) == 1\n out = min(max(p1*(T-p2),0),S1/dt).*smoothThreshold_storage_logistic(S2,St,varargin(1));\nelseif size(varargin,2) == 2\n out = min(max(p1*(T-p2),0),S1/dt).*smoothThreshold_storage_logistic(S2,St,varargin(1),varargin(2)); \nend\n\nend\n\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Models/Flux files/melt_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.6010615157182725}} {"text": "function [nyear,ncoef]=decode_coeff_pointer(np);\n%USAGE: [nyear,ncoef]=decode_coeff_pointer(np); \n%\n% Decode igrf10syn gh pointer to extract year number and ncoef\n% 1<=ncoef<=120 for nyear=1:19\n% 1<=ncoef<=195 for nyear=20:24\n%\n% np=(nyear-1)*120+ncoef for np<=np1_max\n% np=np1_max+(nyear-19)*195+ncoef; for nyear=20:24\n%\n% year=1995+(nyear-1)*5;\n%\nnp1_max=2280;\nif np<=np1_max\n nyear=floor(np/120)+1;\n ncoef=np-(nyear-1)*120;\n if ncoef==0\n ncoef=120;\n nyear=nyear+1;\n end\nelseif np<=3255\n np2=np-np1_max;\n nyear=floor(np2/195)+1;\n ncoef=np2-(nyear-1)*195;\n if ncoef==0\n ncoef=195;\n nyear=nyear+1;\n end\n nyear=19+nyear;\nelse\n error('np>3255!')\nend\nreturn", "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/28874-igrf-magnetic-field/IGRF/decode_coeff_pointer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.6010615157182725}} {"text": "function [Fnew, obj, M,k,x,u,n,deg,linears,nonlinears,vecConstraints,isinequality,ulong] = momentmodel(F,obj,k,keepnonlinears)\n\nif nargin < 2\n obj = [];\nend\nif nargin < 3\n k = [];\nend\nif nargin < 4\n keepnonlinears = 0;\nend\n\nvecConstraints = [];\nsdpConstraints = [];\nisinequality = [];\nbinaries = [];\nxvars = [];\nFnew = ([]);\nfor i = 1:length(F)\n if is(F(i),'elementwise')\n X = sdpvar(F(i));\n vecConstraints = [vecConstraints;X(:)];\n isinequality = [isinequality ones(1,prod(size(X)))];\n xvars = [xvars depends(X(:))];\n elseif is(F(i),'equality')\n X = sdpvar(F(i));\n if is(X,'symmetric')\n X = X(find(triu(ones(length(X)))));\n end\n vecConstraints = [vecConstraints;-X(:)];\n isinequality = [isinequality zeros(1,prod(size(X)))];\n xvars = [xvars depends(X(:))];\n elseif is(F(i),'sdp')\n sdpConstraints{end+1} = sdpvar(F(i));\n xvars = [xvars depends(F(i))];\n elseif is(F(i),'binary')\n binaries = [binaries getvariables(F(i))];\n else\n Fnew = Fnew+F(i); % Should only be SOCP constraints\n end\nend\n\n% Recover the involved variables\nx = recover(unique([depends(obj) xvars]));\nn = length(x);\n\n% Check degrees of constraints\ndeg = [];\nfor i = 1:length(vecConstraints)\n deg(end+1) = degree(vecConstraints(i));\nend\nfor i = 1:length(sdpConstraints)\n deg(end+1) = degree(sdpConstraints{i});\nend\nif isempty(deg)\n deg = 0;\nend\n\n% Create lowest possible relaxation if k=[]\nd = ceil((max(degree(obj),max(deg)))/2);\nk_min = d;\nif isempty(k)\n k = k_min;\nelse\n if k=0);\nfor i = 1:length(vecConstraints) \n if isinequality(i)\n v_k = floor((degree(vecConstraints(i))+1)/2);\n Localizer = vecConstraints(i)*M{k-v_k+1};\n if isa(vecConstraints(i),'double')\n if vecConstraints(i)<0\n error('Problem is trivially infeasible due to negative constant')\n else\n continue\n end\n end\n Fmoments = Fmoments+(Localizer>=0);\n else\n if isa(vecConstraints(i),'double')\n if vecConstraints(i)~=0\n error('Problem is trivially infeasible due to non-zero constant in equality constraints')\n else\n continue\n end\n end \n Localizer = vecConstraints(i)*monolist(x,2*k-degree(vecConstraints(i))); \n Fmoments = Fmoments+(Localizer==0);\n end\nend\nfor i = 1:length(sdpConstraints)\n v_k = floor((degree(sdpConstraints{i})+1)/2);\n Fmoments = Fmoments+(kron(M{k-v_k+1},sdpConstraints{i})>=0);\nend\n\n% Add them all\nFnew = Fnew + Fmoments;\n\n% Get all binary and reduce problem\nbinaries = union(binaries,yalmip('binvariables'));\nif ~isempty(binaries)\n if isa(obj,'sdpvar') \n obj = eliminateBinary(obj,binaries);\n end\n for i = 1:length(Fmoments)\n Fnew(i) = eliminateBinary(Fnew(i),binaries);\n end\n for i = 2:1:k+1;\n M{i} = eliminateBinary(M{i},binaries);\n end\nend\n\nvars = getvariables(Fnew);\nfor i = 1:length(M)\n vars = [vars getvariables(M{i})];\nend\nvars = unique([vars getvariables(obj)]);\n[mt,variabletype] = yalmip('monomtable');\nnonlinears = vars(find(variabletype(vars)));\nnewLinear = sdpvar(length(nonlinears),1);\n\nif isa(obj,'sdpvar')\n obj = variablereplace(obj,nonlinears,getvariables(newLinear));\nend\nfor i = 1:length(M)\n if isa(M{i},'sdpvar')\n M{i} = variablereplace(M{i},nonlinears,getvariables(newLinear));\n end\nend\nlinears = getvariables(newLinear);\nFnew = variablereplace(Fnew,nonlinears,getvariables(newLinear));\nlinears = recover(linears);\nnonlinears = recover(nonlinears);\n\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/moment/momentmodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6010492605497352}} {"text": "function bessel_y1_spherical_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_Y1_SPHERICAL_VALUES_TEST tests BESSEL_Y1_SPHERICAL_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_Y1_SPHERICAL_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_Y1_SPHERICAL_VALUES stores values of\\n' );\n fprintf ( 1, ' the y1 spherical Bessel function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X FX\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_y1_spherical_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/bessel_y1_spherical_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6010112398669701}} {"text": " function ob = Godwt1(mask, varargin)\n%|function ob = Godwt1(mask, varargin)\n%| Construct Godwt1 object that computes orthonormal discrete wavelet\n%| decomposition of a signal with dimensions [(N)].\n%| This is useful for sparsity regularization (aka compressed sensing).\n%| (1D or 2D wavelets only)\n%|\n%| in\n%|\t'mask'\tlogical [(Nd)]\timage-domain mask, often true(nx,ny)\n%|\n%| options\n%|\t'level'\tint\tdecomposition level (default 1)\n%|\t'wname'\tchar\twavelet name. default: 'haar'\n%|\n%| out\n%|\tob\t[*N np]\tfatrix object, where np = sum(mask(:))\n%|\n%|\n%| Copyright 2012-05-17, Jeff Fessler, University of Michigan\n\nif nargin < 1, ir_usage, end\nif nargin == 1 && streq(mask, 'test'), Godwt1_test, return, end\n\narg.mask = mask;\narg.level = 1;\narg.wname = 'haar';\narg.abs = false;\narg = vararg_pair(arg, varargin);\n\nif isempty(arg.mask), fail 'must provide a mask', end\n\n% transform dimension\nidim = size(arg.mask);\nif idim(end) == 1\n\tidim = idim(1:end-1);\nend\n\nswitch numel(idim)\ncase 1\n\tforw = @(arg, x) ir_odwt1(x, ...\n\t\t'level', arg.level, 'wname', arg.wname, 'abs', arg.abs);\n\tback = @(arg, y) fatrix2_maskit(arg.mask, ir_odwt1(y, 'adj', 1, ...\n\t\t'level', arg.level, 'wname', arg.wname, 'abs', arg.abs));\n\tdoes_many = true;\ncase 2\n\tforw = @(arg, x) ir_odwt2(x, ...\n\t\t'level', arg.level, 'wname', arg.wname, 'abs', arg.abs);\n\tback = @(arg, y) fatrix2_maskit(arg.mask, ir_odwt2(y, 'adj', 1, ...\n\t\t'level', arg.level, 'wname', arg.wname, 'abs', arg.abs));\n\tdoes_many = false;\notherwise\n fail('dim %d unsupported', numel(idim))\nend\n\n% build fatrix2 object\narg.idim = idim;\nob = fatrix2('idim', idim, 'odim', idim, 'arg', arg, ...\n\t'abs', @Godwt1_abs, 'meth', {'codes', @Godwt1_codes, '()'}, ...\n\t'forw', forw, 'back', back, 'does_many', does_many);\n\n\n% Godwt1_abs()\nfunction ob = Godwt1_abs(ob)\nob.arg.abs = true;\n\n\n% Godwt1_codes()\nfunction codes = Godwt1_codes(arg)\n\nswitch numel(arg.idim)\ncase 1\n\t[dummy codes] = ir_odwt1(zeros([arg.idim 1]), ...\n\t\t'level', arg.level, 'wname', arg.wname);\ncase 2\n\t[dummy codes] = ir_odwt2(zeros(arg.idim), ...\n\t\t'level', arg.level, 'wname', arg.wname);\notherwise\n fail('dim %d unsupported', numel(idim))\nend\n\n\n% Godwt1_test()\nfunction Godwt1_test\n\nif 1 % 1d\n\tmask = true(8*3,1);\n\tmask(1:3) = false;\n\tlevel = 3;\n\tU = Godwt1(mask, 'level', level);\n%\tabs(U) % todo\n\n\tif im\n\t\tim plc 1 2\n\t\tim(1, full(U))\n\t\tim(2, U.codes)\n\t\tdrawnow\n\tend\n\n\tfatrix2_tests(U, 'complex', 1) % check complex data\n\ttest_adjoint(U, 'complex', 1, 'tolre', 1e-9);\nend\n\nif 1 % 2d\n\tmask = true(8*3,16);\n\tmask(1:3) = false;\n\tlevel = 3;\n\twname = 'haar';\n\twname = 'sym2';\n\tU = Godwt1(mask, 'level', level, 'wname', wname);\n\n\tx = ellipse_im(size(mask));\n\tif im\n\t\tim plc 1 2\n\t\tim(1, x)\n\t\tim(2, U * x)\n\t\tdrawnow\n\tend\n\n\tfatrix2_tests(U, 'complex', 1) % check complex data\n\ttest_adjoint(U, 'complex', 1, 'tolre', 1e-9, 'big', 1);\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/Godwt1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6009552806567672}} {"text": "function [ a, det ] = dpodi ( a, lda, n, job )\n\n%*****************************************************************************80\n%\n%% DPODI computes the determinant and inverse of a certain matrix.\n%\n% Discussion:\n%\n% The matrix is real symmetric positive definite.\n% DPODI uses the factors computed by DPOCO, DPOFA or DQRDC.\n%\n% A division by zero will occur if the input factor contains\n% a zero on the diagonal and the inverse is requested.\n% It will not occur if the subroutines are called correctly\n% and if DPOCO or DPOFA has set INFO == 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 June 2005\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(LDA,N), the output A from DPOCO or DPOFA, or the output \n% X from DQRDC. \n%\n% Input, integer LDA, the leading dimension of the array A.\n%\n% Input, integer N, the order of the matrix A.\n%\n% Input, integer JOB, specifies the task.\n% 11, both determinant and inverse.\n% 01, inverse only.\n% 10, determinant only.\n%\n% Output, real A(LDA,N), if DPOCO or DPOFA was used to factor A then \n% DPODI produces the upper half of inverse(A). If DQRDC was used to \n% decompose X then DPODI produces the upper half of inverse(X'*X) \n% where X' is the transpose. Elements of A below the diagonal are \n% unchanged. If the units digit of JOB is zero, A is unchanged.\n%\n% Output, real DET(2), the determinant of A or of X'*X\n% if requested.\n% determinant = DET(1) * 10.0**DET(2)\n% with 1.0 <= DET(1) < 10.0 or DET(1) == 0.0.\n%\n\n%\n% Compute the determinant.\n%\n if ( job / 10 ~= 0 )\n\n det(1) = 1.0;\n det(2) = 0.0;\n s = 10.0;\n\n for i = 1 : n\n\n det(1) = a(i,i) * a(i,i) * det(1);\n\n if ( det(1) == 0.0 )\n break\n end\n\n while ( det(1) < 1.0 )\n det(1) = s * det(1);\n det(2) = det(2) - 1.0;\n end\n\n while ( s <= det(1) )\n det(1) = det(1) / s;\n det(2) = det(2) + 1.0;\n end\n\n end\n\n end\n%\n% Compute inverse(R).\n%\n if ( mod ( job, 10 ) ~= 0 )\n\n for k = 1 : n\n\n a(k,k) = 1.0 / a(k,k);\n t = -a(k,k);\n a(1:k-1,k) = dscal ( k-1, t, a(1:k-1,k), 1 );\n\n for j = k+1 : n\n t = a(k,j);\n a(k,j) = 0.0;\n a(1:k,j) = daxpy ( k, t, a(1:k,k), 1, a(1:k,j), 1 );\n end\n\n end\n%\n% Form inverse(R) * (inverse(R))'.\n%\n for j = 1 : n\n for k = 1 : j-1\n t = a(k,j);\n a(1:k,k) = daxpy ( k, t, a(1:k,j), 1, a(1:k,k), 1 );\n end\n t = a(j,j);\n a(1:j,j) = dscal ( j, t, a(1:j,j), 1 );\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_d/dpodi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6009552754367454}} {"text": "dt = 0.02;\nsim_t = 20;\nx0 = [0;5;0];\n\nparams.v = 1; % velocity\nparams.u_max = 3; % max yaw rate (left)\nparams.u_min = -3; % min yaw rate (right)\n\n% Obstacle position\nparams.xo = 5;\nparams.yo = 4;\n% Obstacle radius\nparams.d = 2;\nparams.cbf_gamma0 = 1;\n% Desired target point\nparams.xd = 12;\nparams.yd = 0;\n\nparams.clf.rate = 0.5;\nparams.weight.slack = 10;\n\nparams.cbf.rate = 1;\n\ndubins = DubinsCar(params);\n\nodeFun = @dubins.dynamics;\ncontroller = @dubins.ctrlCbfClfQp;\nodeSolver = @ode45;\n\ntotal_k = ceil(sim_t / dt);\nx = x0;\nt = 0; \n% initialize traces.\nxs = zeros(total_k, dubins.xdim);\nts = zeros(total_k, 1);\nus = zeros(total_k-1, 1);\nVs = zeros(total_k-1, 1);\nhs = zeros(total_k-1, 1);\nxs(1, :) = x0';\nts(1) = t;\nfor k = 1:total_k-1\n t\n % Determine control input.\n % dV_hat: analytic Vdot based on model.\n [u, slack, h, V] = controller(x); \n us(k, :) = u';\n hs(k) = h;\n Vs(k) = V;\n\n % Run one time step propagation.\n [ts_temp, xs_temp] = odeSolver(@(t, s) odeFun(t, s, u), [t t+dt], x);\n x = xs_temp(end, :)';\n\n xs(k+1, :) = x';\n ts(k+1) = ts_temp(end);\n t = t + dt;\nend\n\nplot_results(ts, xs, us, hs, [params.xo;params.yo], params.d)\n\nfunction plot_results(t, xs, us, hs, p_o, r_o)\n\nfigure\nsubplot(3,1,1)\nplot(t, xs(:,1))\nxlabel('t')\nylabel('x [m]')\n\nsubplot(3,1,2)\nplot(t, xs(:,2))\nxlabel('t')\nylabel('y [m]')\n\nsubplot(3,1,3)\nplot(t, xs(:,3))\nxlabel('t')\nylabel('theta [rad]')\n\n\nfigure\nplot(t(1:end-1), us)\nxlabel('t')\nylabel('u [rad/s]')\n\n\nlim_min = min(min(xs(:, 1)), min(xs(:, 2)));\nlim_max = max(max(xs(:, 1)), max(xs(:, 2)));\nlim_min = min([lim_min, p_o(1)-r_o, p_o(2)-r_o]);\nlim_max = max([lim_max, p_o(1)+r_o, p_o(2)+r_o]);\n\nfigure\nplot(xs(:, 1), xs(:, 2));\ndraw_circle(p_o, r_o);\n\nxlim([lim_min, lim_max]);\nylim([lim_min, lim_max]);\nxlabel('x [m]')\nylabel('y [m]')\n\nfigure\nplot(t(1:end-1), hs)\nxlabel('t')\nylabel('cbf h(s)');\n\nend\n\nfunction h = draw_circle(center,r)\nhold on\nth = 0:pi/50:2*pi;\nxunit = r * cos(th) + center(1);\nyunit = r * sin(th) + center(2);\nh = plot(xunit, yunit);\nhold off\n\nend", "meta": {"author": "HybridRobotics", "repo": "CBF-CLF-Helper", "sha": "956c88bb1ed72b76feffd882df7e491893391c77", "save_path": "github-repos/MATLAB/HybridRobotics-CBF-CLF-Helper", "path": "github-repos/MATLAB/HybridRobotics-CBF-CLF-Helper/CBF-CLF-Helper-956c88bb1ed72b76feffd882df7e491893391c77/demos/run_cbf_clf_simulation_dubins_car.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6009552745510052}} {"text": "function amanatidesWooAlgorithm(origin, direction, grid3D, verbose)\n% A fast and simple voxel traversal algorithm through a 3D space partition (grid)\n% proposed by J. Amanatides and A. Woo (1987).\n%\n% Input:\n% origin.\n% direction.\n% grid3D: grid dimensions (nx, ny, nz, minBound, maxBound).\n% Author: \n% Jesús P. Mena-Chalco.\n\n if (verbose)\n figure;\n hold on;\n text(origin(1), origin(2), origin(3), 'origin');\n plot3(origin(1), origin(2), origin(3), 'k.', 'MarkerSize', 15);\n quiver3(origin(1), origin(2), origin(3), direction(1), direction(2), direction(3), 30);\n \n vmin = grid3D.minBound';\n vmax = grid3D.maxBound';\n BoxVertices = [vmax(1) vmin(2) vmin(3); vmax(1) vmax(2) vmin(3); vmin(1) vmax(2) vmin(3); vmin(1) vmax(2) vmax(3); vmin(1) vmin(2) vmax(3); vmax(1) vmin(2) vmax(3); vmin; vmax ];\n BoxFaces = [1 2 3 7; 1 2 8 6; 1 6 5 7; 7 5 4 3; 2 8 4 3; 8 6 5 4];\n h = patch('Vertices',BoxVertices,'Faces',BoxFaces,'FaceColor','yellow');\n set(h, 'FaceAlpha', 0.1);\n\n view(60,30);\n axis tight;\n xlabel('x');\n ylabel('y');\n zlabel('z');\n grid on;\n end;\n \n [flag, tmin] = rayBoxIntersection(origin, direction, grid3D.minBound, grid3D.maxBound);\n\n if (flag==0)\n disp('\\n The ray does not intersect the grid');\n else\n if (tmin<0)\n tmin = 0;\n end;\n\n start = origin + tmin*direction;\n boxSize = grid3D.maxBound-grid3D.minBound;\n \n if (verbose)\n plot3(start(1), start(2), start(3), 'r.', 'MarkerSize', 15);\n end;\n \n x = floor( ((start(1)-grid3D.minBound(1))/boxSize(1))*grid3D.nx )+1;\n y = floor( ((start(2)-grid3D.minBound(2))/boxSize(2))*grid3D.ny )+1;\n z = floor( ((start(3)-grid3D.minBound(3))/boxSize(3))*grid3D.nz )+1; \n\n if (x==(grid3D.nx+1)); x=x-1; end;\n if (y==(grid3D.ny+1)); y=y-1; end; \n if (z==(grid3D.nz+1)); z=z-1; end;\n \n if (direction(1)>=0)\n tVoxelX = (x)/grid3D.nx;\n stepX = 1;\n else\n tVoxelX = (x-1)/grid3D.nx;\n stepX = -1; \n end;\n \n if (direction(2)>=0)\n tVoxelY = (y)/grid3D.ny;\n stepY = 1;\n else\n tVoxelY = (y-1)/grid3D.ny;\n stepY = -1;\n end;\n \n if (direction(3)>=0)\n tVoxelZ = (z)/grid3D.nz; \n stepZ = 1;\n else\n tVoxelZ = (z-1)/grid3D.nz;\n stepZ = -1; \n end;\n \n voxelMaxX = grid3D.minBound(1) + tVoxelX*boxSize(1);\n voxelMaxY = grid3D.minBound(2) + tVoxelY*boxSize(2);\n voxelMaxZ = grid3D.minBound(3) + tVoxelZ*boxSize(3);\n\n tMaxX = tmin + (voxelMaxX-start(1))/direction(1);\n tMaxY = tmin + (voxelMaxY-start(2))/direction(2);\n tMaxZ = tmin + (voxelMaxZ-start(3))/direction(3);\n \n voxelSizeX = boxSize(1)/grid3D.nx;\n voxelSizeY = boxSize(2)/grid3D.ny;\n voxelSizeZ = boxSize(3)/grid3D.nz; \n \n tDeltaX = voxelSizeX/abs(direction(1));\n tDeltaY = voxelSizeY/abs(direction(2));\n tDeltaZ = voxelSizeZ/abs(direction(3));\n \n while ( (x<=grid3D.nx)&&(x>=1) && (y<=grid3D.ny)&&(y>=1) && (z<=grid3D.nz)&&(z>=1) )\n\n if (verbose)\n fprintf('\\nIntersection: voxel = [%d %d %d]', [x y z]);\n \n t1 = [(x-1)/grid3D.nx, (y-1)/grid3D.ny, (z-1)/grid3D.nz ]';\n t2 = [ (x)/grid3D.nx, (y)/grid3D.ny, (z)/grid3D.nz ]'; \n\n vmin = (grid3D.minBound + t1.*boxSize)';\n vmax = (grid3D.minBound + t2.*boxSize)';\n\n smallBoxVertices = [vmax(1) vmin(2) vmin(3); vmax(1) vmax(2) vmin(3); vmin(1) vmax(2) vmin(3); vmin(1) vmax(2) vmax(3); vmin(1) vmin(2) vmax(3); vmax(1) vmin(2) vmax(3); vmin; vmax ];\n smallBoxFaces = [1 2 3 7; 1 2 8 6; 1 6 5 7; 7 5 4 3; 2 8 4 3; 8 6 5 4];\n \n h = patch('Vertices', smallBoxVertices, 'Faces', smallBoxFaces, 'FaceColor', 'blue', 'EdgeColor', 'white');\n set(h,'FaceAlpha',0.2);\n end;\n \n % ---------------------------------------------------------- %\n % check if voxel [x,y,z] contains any intersection with the ray\n %\n % if ( intersection )\n % break;\n % end;\n % ---------------------------------------------------------- %\n \n if (tMaxX < tMaxY)\n if (tMaxX < tMaxZ)\n x = x + stepX;\n tMaxX = tMaxX + tDeltaX;\n else\n z = z + stepZ;\n tMaxZ = tMaxZ + tDeltaZ;\n end;\n else\n if (tMaxY < tMaxZ)\n y = y + stepY;\n tMaxY = tMaxY + tDeltaY; \n else\n z = z + stepZ;\n tMaxZ = tMaxZ + tDeltaZ;\n end;\n end;\n end; \n end;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26852-a-fast-voxel-traversal-algorithm-for-ray-tracing/amanatidesWooAlgorithm/amanatidesWooAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6008731151746864}} {"text": "\n%# NLP written by GAMS Convert at 06/20/02 11:29:54\n%# \n%# Equation counts\n%# Total E G L N X\n%# 3 2 1 0 0 0\n%# \n%# Variable counts\n%# x b i s1s s2s sc si\n%# Total cont binary integer sos1 sos2 scont sint\n%# 5 5 0 0 0 0 0 0\n%# FX 0 0 0 0 0 0 0 0\n%# \n%# Nonzero counts\n%# Total const NL DLL\n%# 12 6 6 0\n%# \n%# Reformualtion has removed 1 variable and 1 equation\n%\n%\n%var x1 := 50, >= 50, <= 200;\n%var x2 := 37.5, >= 37.5, <= 150;\n%var x3 := 45, >= 45, <= 180;\n%var x4;\n%\n%minimize obj: 0.00533*x1^2 + 11.669*x1 + 0.00889*x2^2 + 10.333*x2 + 0.00741*x3^\n% 2 + 10.833*x3 + 653.1;\n%\n%subject to\n%\n%e2: - (0.01*(0.0676*x1*x1 + 0.00953*x1*x2 - 0.00507*x1*x3 + 0.00953*x2*x1 + \n% 0.0521*x2*x2 + 0.00901*x2*x3 - 0.00507*x3*x1 + 0.00901*x3*x2 + 0.0294*x3*x3\n% ) - 0.000766*x1 - 3.42e-5*x2 + 0.000189*x3) + x4 = 0.040357;\n%\n%e3: x1 + x2 + x3 - x4 >= 210;\n\nfunction test_ipopt\n\n auxdata = {} ;\n\n options.lb = [ 50, 37.5, 45, -Inf ] ; % Lower bound on the variables.\n options.ub = [ 200, 150, 180, Inf ] ; % Upper bound on the variables.\n\n % The constraint functions are bounded to zero\n options.cl = [ 0, 0 ]; % constraints\n options.cu = [ 0, Inf ];\n \n % Set up the auxiliary data.\n options.auxdata = auxdata ;\n \n % Set the IPOPT options.\n options.ipopt.jac_d_constant = 'no';\n options.ipopt.hessian_constant = 'no';\n options.ipopt.mu_strategy = 'adaptive';\n options.ipopt.max_iter = 400;\n options.ipopt.tol = 1e-10;\n \n % The callback functions.\n funcs.objective = @objective;\n funcs.constraints = @constraints;\n funcs.gradient = @gradient;\n funcs.jacobian = @jacobian;\n funcs.jacobianstructure = @jacobianstructure;\n if true\n funcs.hessian = @hessian;\n funcs.hessianstructure = @hessianstructure;\n options.ipopt.derivative_test = 'second-order';\n else\n options.ipopt.hessian_approximation = 'limited-memory';\n %options.ipopt.limited_memory_update_type = 'bfgs' ; % {bfgs}, sr1 = 6; % {6}\n %options.ipopt.limited_memory_update_type = 'sr1' ;\n options.ipopt.limited_memory_update_type = 'bfgs' ; % {bfgs}, sr1 = 6; % {6}\n end\n\n % Run IPOPT.\n x0 = [50, 37.5, 45, 0] ; \n\n tic\n [x, info] = ipopt_auxdata(x0,funcs,options);\n elapsed = toc ;\n\n info;\n\n x\n\nend\n\n%%\n% map the indices with the corresponding index in the spase matrix\nfunction f = objective(x,auxdata)\n f = 0.00533*x(1)^2 + 11.669*x(1) + ...\n 0.00889*x(2)^2 + 10.333*x(2) + ...\n 0.00741*x(3)^2 + 10.833*x(3) + 653.1 ;\nend\n\n%% \n% map the indices with the corresponding index in the spase matrix\nfunction g = gradient(x,auxdata)\n g = [ 0.01066*x(1) + 11.669, 0.01778*x(2) + 10.333, 0.01482*x(3) + 10.833, 0 ] ;\nend\n\nfunction f = constraints(x,auxdata)\n f = zeros(2,1) ;\n f(1) = - (0.01*(0.0676*x(1)^2 + 0.00953*x(1)*x(2) - 0.00507*x(1)*x(3) + ...\n 0.00953*x(2)*x(1) + 0.0521*x(2)^2 + 0.00901*x(2)*x(3) - ...\n 0.00507*x(3)*x(1) + 0.00901*x(3)*x(2) + 0.0294*x(3)*x(3) ) ...\n - 0.000766*x(1) - 3.42e-5*x(2) + 0.000189*x(3)) + x(4) - 0.040357 ; % = 0\n f(2) = x(1) + x(2) + x(3) - x(4) - 210 ; % >= 0\nend\n\nfunction jac = jacobian(x,auxdata)\n jac = [ -0.001352*x(1) - 0.0001906*x(2) + 0.0001014*x(3) + 0.000766, ...\n -0.0001906*x(1) - 0.001042*x(2) - 0.0001802*x(3) + 0.0000342, ...\n 0.0001014*x(1) - 0.0001802*x(2) - 0.000588*x(3) - 0.000189, ...\n 1 ; 1, 1, 1, -1 ] ;\n jac = sparse(jac) ;\nend\n\nfunction jac = jacobianstructure(auxdata)\n jac = sparse(ones(2,4)) ;\nend\n\nfunction H = hessian(x, sigma, lambda, auxdata)\n H1 = [ 0.01066 0 0 0 ; ...\n 0 0.01778 0 0 ; ...\n 0 0 0.01482 0 ; ...\n 0 0 0 0 ] ;\n H2 = [ -0.1352e-2, 0, 0, 0 ; ...\n -0.1906e-3, -0.1042e-2, 0, 0 ; ...\n 0.0001014, -0.1802e-3, -0.588e-3, 0 ; ...\n 0, 0, 0, 0 ] ;\n H = sparse(sigma*H1 + lambda(1)*H2) ;\nend\n\nfunction H = hessianstructure(auxdata)\n H = sparse([ 1 0 0 0 ; 1 1 0 0 ; 1 1 1 0 ; 1 1 1 1 ]) ;\nend\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/math/ipopt/examples/test_ipopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6008731090481596}} {"text": "%FEATSELO Branch and bound feature selection\n% \n% [W,R] = FEATSELO(A,CRIT,K,T)\n% [W,R] = A*FEATSELO([],CRIT,K,T)\n% [W,R] = A*FEATSELO(CRIT,K,T)\n% [W,R] = FEATSELO(A,CRIT,K,N)\n% [W,R] = A*FEATSELO([],CRIT,K,N)\n% [W,R] = A*FEATSELO(CRIT,K,N)\n%\n% INPUT\t\n% A Input dataset\n% CRIT String name of the criterion or untrained mapping \n% (optional, def= 'maha-s')\n% K Numner of features to select (optional, def: K=2)\n% T Validation set (optional)\n% N Number of cross-validations (optional)\n%\n% OUTPUT\n% W Output feature selection mapping\n% R Matrix with step-by-step results\n% \n% DESCRIPTION\n% Backward selection of K features by baktracking using the branch \n% and bound procedure on the data set A. CRIT sets the criterion \n% used by the feature evaluation routine FEATEVAL. If the data set T \n% is given, it is used as test set for FEATEVAL. Alternatively a number\n% of cross-validations N may be supplied. The resulting W can be used for\n% the selecting features of a dataset B by B*W. \n% The selected features are stored in W.DATA and can be found by +W.\n% \n% This procedure finds the optimum feature set if a monotoneous \n% criterion is used. The use of a testset does not guarantee that.\n%\n% REFERENCE\n% P. M. Narendra and K. Fukunaga\n% A Branch and Bound Algorithm for Feature Subset Selection,\n% IEEE Trans. Computer, 26(9), pp. 917-922, September 1977\n% \n% SEE ALSO (PRTools Guide)\n% MAPPINGS, DATASETS, FEATEVAL, FEATSELF, FEATSELB, FEATSELI,\n% FEATSEL, FEATSELP, FEATSELM\n\n% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com\n% Faculty EWI, Delft University of Technology\n% P.O. Box 5031, 2600 GA Delft, The Netherlands\n\n% $Id: featselo.m,v 1.7 2009/07/01 09:33:23 duin Exp $\n\nfunction [W,R] = featselo(varargin)\n\n varargin = shiftargin(varargin,{'char','prmapping'});\n argin = setdefaults(varargin,[],'maha-s',2,[],[]);\n if mapping_task(argin,'definition')\n W = define_mapping(argin,'untrained','B&B FeatSel');\n return\n end\n \n [A,crit,kmin,T,fid] = deal(argin{:});\n\n\tisvaldfile(A,1,2); % at least 1 object per class, 2 classes\n\tA = testdatasize(A);\n\tif isdataset(T), iscomdset(A,T); end\n\n\t[m,k,c] = getsize(A);\n\tfeatlist = getfeatlab(A);\n A = setprior(A,getprior(A));\n\n\tif ((kmin < 1) | (kmin >= k))\n\t\terror('The desired feature size should be > 0 and < dataset feature size')\n\tend\n\t\n\t% space for criteria values\n\tfeat = zeros(1,k);\n\n % Get performance of the individual features:\n\tif isempty(T)\n\t\tfor j=1:k\n\t\t\tfeat(j) = feateval(A(:,j),crit);\n\t\tend\n\telseif is_scalar(T)\n\t\tfor j=1:k\n\t\t\tfeat(j) = feateval(A(:,j),crit,T);\n\t\tend\n\telse\n\t\tfor j=1:k\n\t\t\tfeat(j) = feateval(A(:,j),crit,T(:,j));\n\t\tend\n\tend\n\n % Get the kmin worst(?) individual features according to their\n % individual performance:\n\t[F,S] = sort(feat);\n\t\n\t%sometimes the above line is bad compared to the following two\n\t%w = featselb(A,crit,[]);\n\t%S = fliplr(+w);\n\t\n\tIopt = [k-kmin+1:k];\n\n\tI = [1:k];\n\tJ = [zeros(1,kmin),1:(k-kmin-1),k-kmin+1,k+1];\n\tlevel = k;\n\n % Get the performance of Iopt\n\tif isdataset(T)\n\t\tbound = feateval(A(:,S(Iopt)),crit,T(:,S(Iopt)));\n\telseif is_scalar(T)\n\t\tbound = feateval(A(:,S(Iopt)),crit,T);\n\telse\n\t\tbound = feateval(A(:,S(Iopt)),crit);\n\tend\n\n\tC = inf;\n\tprwaitbar(100,'Branch & Bound Feature Selection')\n\titer = 0;\n\twhile numel(I) > 0 && J(k+1) == k+1;\n\t\titer = iter+1; \n\t\tprwaitbar(100,100-100*exp(-iter/25),['Branch & Bound Feature Selection: ' num2str(iter)]);\n\t\tif J(level) == J(level+1) | level <= kmin | C <= bound\n\t\t\tJ(level) = level - kmin;\n\t\t\tlevel = level + 1;\n\t\t\tI = sort([I,J(level)]);\n\t\t\tJ(level) = J(level) + 1;\n\t\t\tC = inf;\n\t\telse\n\t\t\tI(J(level)) = [];\n\t\t\tlevel = level - 1;\n\t\t\tif J(level+1) < 3 & level == kmin+1 & 0 % never happens ??\n\t\t\t\t;\n\t\t\telse\n\t\t\t\tif isdataset(T)\n\t\t\t\t\tC = feateval(A(:,S(I)),crit,T(:,S(I)));\n\t\t\t\telseif is_scalar(T)\n\t\t\t\t\tC = feateval(A(:,S(I)),crit,T);\n\t\t\t\telse\n\t\t\t\t\tC = feateval(A(:,S(I)),crit);\n end\n\t\t\t\tif level == kmin & C > bound\n\t\t\t\t\tbound = C;\n\t\t\t\t\tIopt = I;\n disp([bound,iter,numel(I)])\n end\n\t\t\tend\n\t\tend\n end\n\tprwaitbar(0);\n\n % Store the optimal features in the mapping:\n\tW = featsel(k,S(Iopt));\n W = setmapping_type(W,'trained');\n W = setsize(W,[k length(S(Iopt))]);\n\tif ~isempty(featlist)\n\t\tW = setlabels(W,featlist(S(Iopt),:));\n\tend\n\tW = setname(W,'B&B FeatSel');\n\n\tR = []; %DXD I'm still not sure what to return\n\nreturn\n", "meta": {"author": "marianux", "repo": "ecg-kit", "sha": "c8e3de47c54a9214138143676d2aa546b0540dd2", "save_path": "github-repos/MATLAB/marianux-ecg-kit", "path": "github-repos/MATLAB/marianux-ecg-kit/ecg-kit-c8e3de47c54a9214138143676d2aa546b0540dd2/common/prtools/featselo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6008730979947706}} {"text": "function [r, R_r, R_v, R_a] = rpredict(r, v, a, dt)\n\n% RPREDICT Position prediction.\n% RPREDICT(R,V,DT) performs the time update R = R + V*DT.\n%\n% RPREDICT(R,V,A,DT) considers R = R + V*DT + 1/2*A*DT instead.\n%\n% [R,R_r,R_v,R_a] = ... returns Jacobian matrices wrt position R,\n% velocity V and acceleration A.\n%\n% See also VPREDICT, QPREDICT.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargin == 3\n dt = a;\n r = r + v*dt;\n R_r = eye(length(r));\n R_v = dt*R_r;\n R_a = zeros(3);\n\nelseif nargin == 4\n r = r + v*dt + .5*a*dt^2;\n R_r = eye(length(r));\n R_v = R_r*dt;\n R_a = 0.5*R_r*dt^2;\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/Kinematics/rpredict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6008730918682434}} {"text": "function [H s phi T] = RSTLS(X1, X2, normalization)\n\n% [H s phi T] = RSTLS(X1, X2, normalization)\n%\n% DESC:\n% computes the RST transformation between the point pairs X1, X2\n%\n% VERSION:\n% 1.0.1\n%\n% INPUT:\n% X1, X2 = point matches (cartesian coordinates)\n% normalization = true (default) or false to enable/disable point \n% normalzation\n%\n% OUTPUT:\n% H = homography representing the RST transformation\n% s = scaling\n% phi = rotation angle\n% T = translation vector\n\n\n% AUTHOR:\n% Marco Zuliani, email: marco.zuliani@gmail.com\n% Copyright (C) 2011 by Marco Zuliani \n% \n% LICENSE:\n% This toolbox is distributed under the terms of the GNU GPL.\n% Please refer to the files COPYING.txt for more information.\n\n\n% HISTORY\n% 1.0.0 08/27/08 - intial version\n% 1.0.1 06/09/09 - implemented closed form for the LS estimation\n% routines\n\nif (nargin < 3)\n normalization = true;\nend;\n\nN = size(X1, 2);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% checks\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif (size(X2, 2) ~= N)\n error('RSTLS:inputError', ...\n 'The set of input points should have the same cardinality')\nend;\nif N < 2\n error('RSTLS:inputError', ...\n 'At least 2 point correspondences are needed')\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% normalize the input\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif (normalization) && (N > 2)\n % fprintf('\\nNormalizing...')\n [X1, T1] = normalize_points(X1);\n [X2, T2] = normalize_points(X2);\nend;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% estimation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif (N == 2)\n \n % fast estimation\n Theta = zeros(4,1);\n \n % $\\mbox{\\texttt{MM}} \\eqdef M_{:,1} = \\vct{y}^{(1)}-\\vct{y}^{(2)} = \\left[\\begin{array}{c} y_1^{(1)}-y_1^{(2)} \\\\ y_2^{(1)}-y_2^{(2)} \\end{array}\\right]$\n % 2 additions\n MM = X1(:,1) - X1(:,2);\n % $ \\mbox{\\texttt{detMM}} \\eqdef |M|$\n % 1 additions, 2 multiplication\n detMM = MM(1)*MM(1) + MM(2)*MM(2);\n % $ \\mbox{\\texttt{MMi}} \\eqdef \\left[ \\begin{array}{c} \\left[M^{-1}\\right]_{1,1} \\\\ -\\left[M^{-1}\\right]_{2,1}\\end{array}\\right]$\n % 2 multiplications\n MMi = MM / detMM;\n\n % $ \\mbox{\\texttt{Delta}} \\eqdef \\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(1)})-\\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(2)})$\n % 2 additions\n Delta = X2(:,1) - X2(:,2);\n \n % $ \\mbox{\\texttt{Theta(1:2)}} = M^{-1}\\left(\\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(1)})-\\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(2)})\\right)$\n % 1 additions, 2 multiplications\n Theta(1) = MMi(1)*Delta(1) + MMi(2)*Delta(2);\n % 1 additions, 2 multiplications\n Theta(2) = MMi(1)*Delta(2) - MMi(2)*Delta(1);\n % $ \\mbox{\\texttt{Theta(3:4)}} = -S^{(2)}\\vct{\\theta}_{1:2}+\\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(2)})$ \n % 2 additions, 2 multiplications\n \n Theta(3) = X2(1,2) - Theta(1)*X1(1,2) + Theta(2)*X1(2,2);\n % 2 additions, 2 multiplications\n Theta(4) = X2(2,2) - Theta(1)*X1(2,2) - Theta(2)*X1(1,2);\n\n % total: 11 additions, 12 multiplications\nelse\n \n % Closed form LS solution. Using the tutorial notation.\n \n % Notation semplification:\n % $\\vct{p}^{(i)} = \\bar{\\vct{y}}^{(i)}$ and $\\vct{q}^{(i)} = \\overline{\\vct{T}_{\\vct{\\theta}} (\\vct{y}^{(i)})}$\n % $a = \\sum_{i=1}^N\\left( (p_1^{(i)})^2 + (p_2^{(i)})^2 \\right)$\n a = sum(X1(:).^2);\n \n % Explicit LS expansion:\n % $ \\theta_1 = \\frac{1}{a}\\sum_{i=1}^N p_1^{(i)} q_1^{(i)} + p_2^{(i)} q_2^{(i)} $\n % $ \\theta_2 = \\frac{1}{a}\\sum_{i=1}^N -p_2^{(i)} q_1^{(i)} + p_1^{(i)} q_2^{(i)} $\n % $ \\theta_3 = 0 $\n % $ \\theta_4 = 0 $\n Theta(1) = sum( X1(1, :).*X2(1, :) + X1(2, :).*X2(2, :) ) / a;\n Theta(2) = sum( -X1(2, :).*X2(1, :) + X1(1, :).*X2(2, :) ) / a;\n Theta(3) = 0;\n Theta(4) = 0;\n \n % Traditional LS\n %\n % A = zeros(2*N, 4);\n % b = zeros(2*N, 1);\n %\n % ind = 1:2;\n % for n = 1:N\n %\n % A(ind, 1:2) = [X1(1,n) -X1(2,n); X1(2,n) X1(1,n)];\n % A(ind, 3:4) = eye(2);\n %\n % b(ind) = X2(1:2, n);\n %\n % ind = ind + 2;\n %\n % end;\n %\n % % solve the linear system in a least square sense\n % Theta = A\\b;\n \nend;\n\n% compute the corresponding homography\nH = [Theta(1) -Theta(2) Theta(3); Theta(2) Theta(1) Theta(4); 0 0 1];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% de-normalize the parameters\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif (normalization) && (N > 2)\n H = T2\\H*T1;\nend;\nH = H/H(9);\n\n% prepare the output\nif nargout > 1\n \n s = sqrt(H(1,1)*H(1,1) + H(2,1)*H(2,1));\n phi = atan2(H(2,1), H(1,1));\n T = H(1:2, 3);\n \nend;\n\nreturn\n", "meta": {"author": "RANSAC", "repo": "RANSAC-Toolbox", "sha": "c08308bf61aaf669b00533409cb0daaa10c000aa", "save_path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox", "path": "github-repos/MATLAB/RANSAC-RANSAC-Toolbox/RANSAC-Toolbox-c08308bf61aaf669b00533409cb0daaa10c000aa/Models/RST/RSTLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6007456164217292}} {"text": "function [M,R] = spm_get_closest_affine(x,y,w1,w2)\n% Determine the affine transform mapping x to y\n% FORMAT [M,R] = spm_get_closest_affine(X,Y,W1,W2)\n% X - n1*n2*n3*3 array of floats representing coordinates.\n% Y - n1*n2*n3*3 array of floats representing coordinates.\n% W1 - n1*n2*n3 array of floats representing weights.\n% W2 - n1*n2*n3 array of floats representing weights.\n%\n% M - an affine transform\n% R - a rigid-body transform\n%\n% The code treats X and Y as reshaped versions (n1*n2*n3) x 3,\n% and W1 and W2 as column vectors.\n% \n% It generates XX = [diag(W1)*X W1]'*diag(W2)*[diag(W1)*X W1]\n% and XY = [diag(W1)*X W1]'*diag(W2)*[Y W1]\n% \n% These can then be used to compute an affine transform (M),\n% by M = (XX\\XY)'\n% A weighted procrustes decomposition is also performed,\n% so that a rigid-body transform matrix (R) is returned.\n%\n% If W1 or W2 are empty or not passed, then they are assumed\n% to be all ones.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_get_closest_affine.m 6137 2014-08-19 12:43:11Z john $\n \nXX = zeros(4);\nXY = zeros(4);\nd = size(x);\no = ones(d(1)*d(2),1);\nfor k=1:size(x,3),\n xk = reshape(x(:,:,k,:),[d(1)*d(2),3]);\n if (nargin<3 || isempty(w1)) && (nargin<4 || isempty(w2)),\n ox = o;\n oy = o;\n else\n if nargin>=4 && ~isempty(w1) && ~isempty(w2),\n oy = reshape(w2(:,:,k), [d(1)*d(2),1]);\n ox = reshape(w1(:,:,k), [d(1)*d(2),1]).*oy;\n elseif nargin>=3 && ~isempty(w1),\n ox = reshape(w1(:,:,k), [d(1)*d(2),1]);\n oy = ox;\n elseif nargin>=4 && ~isempty(w2),\n ox = reshape(w2(:,:,k), [d(1)*d(2),1]);\n end\n xk(:,1) = xk(:,1).*ox;\n xk(:,2) = xk(:,2).*ox;\n xk(:,3) = xk(:,3).*ox;\n end\n yk = reshape(y(:,:,k,:),[d(1)*d(2),3]);\n msk = find(all(isfinite(xk),2) & all(isfinite(yk),2));\n X = [xk(msk,:), ox(msk)];\n Y = [yk(msk,:), oy(msk)];\n XX = XX + double(X'*X);\n XY = XY + double(X'*Y);\nend\nM = (XX\\XY)';\n\nif nargout>1,\n % Procrustes decomposition\n XX1 = XX - XX(:,4)*XX(:,4)'/XX(4,4);\n XY1 = XY - XY(:,4)*XY(4,:) /XY(4,4);\n Z = (XX1(1:3,1:3)\\XY1(1:3,1:3))';\n [U,S,V] = svd(Z); % Decompose into rotate, zoom and rotate.\n R = [U*V' zeros(3,1);0 0 0 1]; % Pure rotation (by taking out the zoom)\n T1 = [eye(4,3) -XY(:,4) /XY(4,4)]; % Initial translation of centre of mass to origin.\n T2 = [eye(4,3) -XY(4,:)'/XY(4,4)]; % Final translation of origin to centre of mass.\n R = T2 * R * T1;\nend\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm12/spm_get_closest_affine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.6007366843581123}} {"text": "function Out = RiemannExpMap(P,X)\n\n[U Delta] = eig(P);\nG = U*sqrt(Delta);\nY = inv(G)*X*inv(G)';\n[V Sigma] = eig(Y);\nOut = (G*V)*diag(exp(diag(Sigma)))*(G*V)';", "meta": {"author": "alexandrebarachant", "repo": "covariancetoolbox", "sha": "f1c088566eda2b2b63857b6563d7be5525ea4768", "save_path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox", "path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox/covariancetoolbox-f1c088566eda2b2b63857b6563d7be5525ea4768/lib/riemann/RiemannExpMap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.6007366660787956}} {"text": "%This Matlab script can be used to reproduce Figure 3.4 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Define the range of BS antennas\nMvalues = [1 10 100];\n\n%Angular standard deviation in the local scattering model (in degrees)\nASD = 10;\n\n%Nominal angle of desired UE\nthetaDesired = pi/6;\n\n%Range of nominal angles of the interfering UE\nvarphiInterfererDegrees = -180:1:180;\nvarphiInterfererRadians = varphiInterfererDegrees*(pi/180);\n\n%Define the antenna spacing (in number of wavelengths)\nantennaSpacing = 1/2; %Half wavelength distance\n\n%Define the effective SNR in (3.13) for the desired UE\nSNR1dB = 10;\nSNR1 = 10.^(SNR1dB/10);\n\n%Define the effective SNR in (3.13) for the interfering UE\nSNR2dB = 0;\nSNR2 = 10.^(SNR2dB/10);\n\n\n%Preallocate matrices for storing the simulation results\ncorrelationcoeff = zeros(length(varphiInterfererRadians),length(thetaDesired),length(Mvalues));\n\n\n%Compute the spatial correlation matrix of the desired UE\nR1 = functionRlocalscattering(max(Mvalues),thetaDesired,ASD,antennaSpacing);\n\n\n%% Go through all angles of interfering UE\nfor n = 1:length(varphiInterfererRadians)\n \n %Output simulation progress\n disp([num2str(n) ' angles out of ' num2str(length(varphiInterfererRadians))]); \n \n %Compute the spatial correlation matrix of the interfering UE\n R2 = functionRlocalscattering(max(Mvalues),varphiInterfererRadians(n),ASD,antennaSpacing);\n \n %Go through all number of antennas\n for m = 1:length(Mvalues)\n \n %Extract correlation matrices of the specified dimension\n R1m = R1(1:Mvalues(m),1:Mvalues(m));\n R2m = R2(1:Mvalues(m),1:Mvalues(m));\n \n %Compute the denominator in (3.18)\n normalization = sqrt(SNR1*SNR2*abs(trace(R1m*((SNR1*R1m+SNR2*R2m+eye(Mvalues(m)))\\R1m)))*abs(trace(R2m*((SNR1*R1m+SNR2*R2m+eye(Mvalues(m)))\\R2m))));\n \n %Compute absolute value of antenna-averaged correlation coefficient in (3.18)\n correlationcoeff(n,m) = sqrt(SNR1*SNR2)*abs(trace(R1m*((SNR1*R1m+SNR2*R2m+eye(Mvalues(m)))\\R2m)))/normalization;\n \n end\n \nend\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\n\nplot(varphiInterfererDegrees,correlationcoeff(:,1),'k-','LineWidth',1);\nplot(varphiInterfererDegrees,correlationcoeff(:,2),'r--','LineWidth',1);\nplot(varphiInterfererDegrees,correlationcoeff(:,3),'b-.','LineWidth',1);\n\nxlabel('Angle of interfering UE [degree]');\nylabel('Antenna-averaged correlation coefficient');\nxlim([-180 180]);\nylim([0 1.1]);\n\nlegend('M=1','M=10','M=100','Location','Best');\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section3_figure4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.600654228547538}} {"text": "function [Dps_eff, Dns_eff] = solidPhaseDiffusionCoefficients(T,param)\n% solidPhaseDiffusionCoefficients evaluates diffusion coefficients of the solid phase [m^2 /s].\n% The user may modify the script to meet specific requirements.\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\nif(param.TemperatureEnabled>=1)\n Dps_eff = param.Dps*exp(-param.EaDps/param.R*(1./T(param.Nal+1:param.Nal+param.Np)-1/param.Tref));\nelse\n Dps_eff = param.Dps*ones(param.Np,1);\nend\n\nif(param.TemperatureEnabled>=1)\n Dns_eff = param.Dns*exp(-param.EaDns/param.R*(1./T(param.Nal+param.Np+param.Ns+1:param.Nal+param.Np+param.Ns+param.Nn)-1/param.Tref));\nelse\n Dns_eff = param.Dns*ones(param.Nn,1);\nend\n\nend\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/P2D_equations/solidPhaseDiffusionCoefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6006002405497562}} {"text": "classdef L1_ADMM_YZ < handle\n% Solver for various L1 minimization problems\n% based on the 2011 paper by \n% Junfeng Yang and Yin Zhang\n\nproperties\n % weight for the quadratic penalty term\n rho\n % verbosity\n verbose \n % Maximum number of ADMM iterations\n max_iterations\n % relative tolerance\n tolerance\n % additional scaling factor for x updates\n gamma\nend % properties\n\nproperties(SetAccess=private)\n % The sensing operator\n A\n % The signals being recovered\n B\n % The solution representation vectors\n X \n % The dimension of signal space\n M\n % The dimension of representation space\n N\n % Details of execution (intermediate values)\n details\nend % properties\n\n% Following properties are meant for implementation only\nproperties(Access=private)\n X0\n Y0\n Z0\nend\n\n\nmethods\n\nfunction self = L1_ADMM_YZ(A, options)\n if nargin < 1\n error('A must be specified.');\n end\n if isa(A, 'spx.dict.Operator')\n self.A = A;\n elseif ismatrix(A)\n self.A = spx.dict.MatrixOperator(A); \n else\n error('Unsupported operator.');\n end\n [self.M, self.N] = size(self.A);\n if nargin < 2\n options = struct;\n end\n self.init_options();\n self.process_options(options);\nend % function\n\nfunction [X] = solve_bp(self, B, options)\n % Solves the problem min ||x||_1 s.t. Ax = b\n if nargin < 2\n error('B must be specified.');\n end\n if nargin < 3\n options = struct;\n end\n self.process_options(options);\n num_problems = size(B, 2);\n if self.verbose > 0\n fprintf('Solving l1 minimization problem: BP.\\n');\n end\n self.init_details(num_problems);\n max_iterations = self.max_iterations;\n A = self.A;\n X = zeros(self.N, num_problems);\n % import relevant functions from other modules\n import spx.opt.projections.proj_linf_ball;\n % iterate over problems\n for prob=1:num_problems\n tstart = tic;\n b = B(:, prob);\n b_max = norm(b, 'inf');\n terminated = false;\n % Check for zero solution condition\n if b_max < self.tolerance\n % There is no need to proceed further\n % zero solution is best solution\n self.details.terminated(prob) = true;\n self.details.iterations(prob) = 0;\n self.details.elapsed_times(prob) = toc(tstart);\n X(:, prob) = zeros(self.N, 1);\n continue;\n end\n if self.rho > 0\n % we will use user defined quadratic term weight\n rho = self.rho;\n else\n rho = mean(abs(b));\n end\n gamma = self.gamma;\n % scale the problem\n b = b / b_max;\n % Initialize solution\n x = A.adjoint(b);\n z = zeros(self.N, 1);\n y = zeros(self.M, 1);\n % compute current primary residual\n r_primal = A.apply(x) - b;\n for iter=1:max_iterations\n % check if we need to iterate further\n if terminated; break; end;\n % update z\n z_prev = z;\n z = proj_linf_ball(A.adjoint(y) + (x / rho));\n % update y\n y_prev = y;\n Az = A.apply(z);\n y = (Az - r_primal / rho);\n % update dual residual\n Aty = A.adjoint(y);\n r_dual = Aty - z;\n % update x\n x_prev = x;\n x = x + (gamma * rho)*r_dual; \n % update primary residual\n r_primal = A.apply(x) - b;\n % primal objective\n primal_obj = sum(abs(x));\n % dual objective\n dual_obj = real(b' * y);\n terminated = self.check_termination(x, x_prev, y, z, ...\n r_primal, r_dual, primal_obj, dual_obj, iter, prob);\n end % iteration loop\n self.details.terminated(prob) = terminated;\n self.details.iterations(prob) = iter-1;\n self.details.elapsed_times(prob) = toc(tstart);\n % put the final solution back in result\n X(:, prob) = x * b_max;\n end % problem loop\nend % function\n\nfunction [X] = solve_bpic(self, B, delta, options)\n % Solves the problem min ||x||_1 s.t. ||Ax - b||_2 <= delta\n if nargin < 2\n error('B must be specified.');\n end\n if nargin < 3\n error('delta must be specified.');\n end\n if nargin < 4\n options = struct;\n end\n self.process_options(options);\n num_problems = size(B, 2);\n if self.verbose > 0\n fprintf('Solving constrained l1 minimization problem: BPIC.\\n');\n end\n self.init_details(num_problems);\n max_iterations = self.max_iterations;\n A = self.A;\n X = zeros(self.N, num_problems);\n % import relevant functions from other modules\n import spx.opt.projections.proj_linf_ball;\n import spx.opt.projections.proj_l2_ball;\n % iterate over problems\n for prob=1:num_problems\n tstart = tic;\n b = B(:, prob);\n b_max = norm(b, 'inf');\n terminated = false;\n % Check for zero solution condition\n if norm(b) < delta\n % There is no need to proceed further\n % zero solution is best solution\n self.details.terminated(prob) = true;\n self.details.iterations(prob) = 0;\n self.details.elapsed_times(prob) = toc(tstart);\n X(:, prob) = zeros(self.N, 1);\n continue;\n end\n if self.rho > 0\n % we will use user defined quadratic term weight\n rho = self.rho;\n else\n rho = mean(abs(b));\n end\n gamma = self.gamma;\n % scale the problem\n b = b / b_max;\n % Initialize solution\n x = A.adjoint(b);\n z = zeros(self.N, 1);\n y = zeros(self.M, 1);\n % compute current primary residual\n r_primal = A.apply(x) - b;\n delta_by_rho = delta / rho;\n for iter=1:max_iterations\n % check if we need to iterate further\n if terminated; break; end;\n % update z\n z_prev = z;\n z = proj_linf_ball(A.adjoint(y) + (x / rho));\n % update y\n y_prev = y;\n Az = A.apply(z);\n y = (Az - r_primal / rho);\n y = y - proj_l2_ball(y, delta_by_rho);\n % update dual residual\n Aty = A.adjoint(y);\n r_dual = Aty - z;\n % update x\n x_prev = x;\n x = x + (gamma * rho)*r_dual;\n % update primary residual\n r_primal = A.apply(x) - b;\n % primal objective\n primal_obj = sum(abs(x));\n % dual objective\n dual_obj = real(b' * y) - delta * norm(y);\n terminated = self.check_termination(x, x_prev, y, z, ...\n r_primal, r_dual, primal_obj, dual_obj, iter, prob);\n end % iteration loop\n self.details.terminated(prob) = terminated;\n self.details.iterations(prob) = iter-1;\n self.details.elapsed_times(prob) = toc(tstart);\n % put the final solution back in result\n X(:, prob) = x * b_max;\n end % problem loop\nend % function\n\nfunction [X] = solve_bpdn_l2(self, B, mu, options)\n % Solves the problem min ||x||_1 + ||Ax - b||_2 / (2 mu)\n if nargin < 2\n error('B must be specified.');\n end\n if nargin < 3\n error('mu must be specified.');\n end\n if nargin < 4\n options = struct;\n end\n self.process_options(options);\n num_problems = size(B, 2);\n if self.verbose > 0\n fprintf('Solving l1-l2 unconstrained minimization problem: BPDN l2.\\n');\n end\n\n self.init_details(num_problems);\n max_iterations = self.max_iterations;\n A = self.A;\n X = zeros(self.N, num_problems);\n % import relevant functions from other modules\n import spx.opt.projections.proj_linf_ball;\n % iterate over problems\n for prob=1:num_problems\n tstart = tic;\n b = B(:, prob);\n % Compute A' b\n Atb = A.adjoint(b);\n terminated = false;\n % Check for zero solution condition\n if norm(Atb, 'inf') <= mu\n % There is no need to proceed further\n % zero solution is best solution\n self.details.terminated(prob) = true;\n self.details.iterations(prob) = 0;\n self.details.elapsed_times(prob) = toc(tstart);\n X(:, prob) = zeros(self.N, 1);\n continue;\n end\n if self.rho > 0\n % we will use user defined quadratic term weight\n rho = self.rho;\n else\n rho = mean(abs(b));\n end\n gamma = self.gamma;\n % scale the problem\n b_max = norm(b, 'inf');\n b = b / b_max;\n mu = mu / b_max;\n % Initialize solution\n x = A.adjoint(b);\n z = zeros(self.N, 1);\n y = zeros(self.M, 1);\n % compute current primary residual\n r_primal = A.apply(x) - b;\n for iter=1:max_iterations\n % check if we need to iterate further\n if terminated; break; end;\n % update z\n z_prev = z;\n z = proj_linf_ball(A.adjoint(y) + (x / rho));\n % update y\n y_prev = y;\n Az = A.apply(z);\n y = (rho/(mu + rho)) * (Az - r_primal / rho);\n % update dual residual\n Aty = A.adjoint(y);\n r_dual = Aty - z;\n % update x\n x_prev = x;\n x = x + (gamma * rho)*r_dual; \n % update primary residual\n r_primal = A.apply(x) - b;\n % primal objective\n primal_obj = sum(abs(x)) + (1/(2*mu))*(r_primal'*r_primal);\n % dual objective\n dual_obj = real(b' * y) - (mu / 2) * (y' * y);\n terminated = self.check_termination(x, x_prev, y, z, ...\n r_primal, r_dual, primal_obj, dual_obj, iter, prob);\n end % iteration loop\n self.details.terminated(prob) = terminated;\n self.details.iterations(prob) = iter-1;\n self.details.elapsed_times(prob) = toc(tstart);\n % put the final solution back in result\n X(:, prob) = x * b_max;\n end % problem loop\nend % function\n\nfunction [X] = solve_bpdn_l1(self, B, nu, options)\n % Solves the problem min ||x||_1 + ||Ax - b||_1 / (nu)\nend % function\n\nend % methods\n\nmethods(Access=private)\n\nfunction init_options(self)\n self.rho = 0;\n self.verbose = 0;\n self.max_iterations = 100;\n % self.eps_abs = 1e-4;\n self.tolerance = 1e-2;\n self.gamma = 1;\nend % function\n\nfunction process_options(self, options)\n % weight for the quadratic penalty term\n if isfield(options, 'rho')\n self.rho = options.rho;\n end\n % verbosity\n if isfield(options, 'verbose')\n self.verbose = options.verbose;\n end\n % Maximum number of ADMM iterations\n if isfield(options, 'max_iterations')\n self.max_iterations = options.max_iterations;\n end\n % gamma for primal variable update\n if isfield(options, 'gamma')\n self.gamma = options.gamma;\n end\n % relative tolerance\n if isfield(options, 'tolerance')\n self.tolerance = options.tolerance;\n end\nend % function\n\nfunction init_xyz(self, num_problems, options)\n if isfield(options, 'X0')\n self.X0 = X0;\n else\n self.X0 = zeros(self.N, num_problems);\n end\n if isfield(options, 'Y0')\n self.Y0 = Y0;\n else\n self.Y0 = zeros(self.N, num_problems);\n end\n if isfield(options, 'Z0')\n self.Z0 = Z0;\n else\n self.Z0 = zeros(self.N, num_problems);\n end\nend % function\n\nfunction init_details(self, num_problems)\n max_iterations = self.max_iterations;\n self.details.iterations = zeros(1, num_problems);\n self.details.terminated = zeros(1, num_problems);\n self.details.elapsed_times = zeros(1, num_problems);\n self.details.x_norms = zeros(max_iterations, num_problems);\n self.details.z_norms = zeros(max_iterations, num_problems);\n self.details.r_primal_norms = zeros(max_iterations, num_problems);\n self.details.r_dual_norms = zeros(max_iterations, num_problems);\n self.details.primal_objectives = zeros(max_iterations, num_problems);\n self.details.dual_objectives = zeros(max_iterations, num_problems);\nend % function\n\nfunction terminate = check_termination(self, x, x_prev, y, z, ...\n r_primal, r_dual, primal_obj, dual_obj, iter, prob)\n terminate = false;\n % norm of primal variable x\n x_norm = norm(x);\n % norm of change in x\n x_diff_norm = norm(x - x_prev);\n % relative change in x\n x_rel_change = x_diff_norm / x_norm;\n % norm of dual variable z\n z_norm = norm(z);\n % primal residual norm\n r_primal_norm = norm(r_primal);\n % dual residual norm\n r_dual_norm = norm(r_dual);\n % relative change in dual norm\n r_dual_rel_change = r_dual_norm / z_norm;\n % gap in objectives\n gap = abs(primal_obj - dual_obj);\n relative_gap = gap / abs(primal_obj);\n\n self.details.x_norms(iter, prob) = x_norm;\n self.details.z_norms(iter, prob) = z_norm;\n self.details.r_primal_norms(iter, prob) = r_primal_norm;\n self.details.r_dual_norms(iter, prob) = r_dual_norm;\n self.details.primal_objectives(iter, prob) = primal_obj;\n self.details.dual_objectives(iter, prob) = dual_obj;\n\n\n if self.verbose > 1\n fprintf('Objective primal: %.4f, dual: %.4f\\n', primal_obj, dual_obj);\n end\n\n tolerance = self.tolerance;\n if x_rel_change < tolerance\n terminate = true;\n end\n if x_rel_change >= tolerance*1.1\n % we will continue for a while\n return;\n end\n if relative_gap < tolerance\n terminate = true;\n end\n if r_dual_rel_change < tolerance\n terminate = true;\n end\nend % function\n\nend % methods\n\nend % class\n\n\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+pursuit/+single/L1_ADMM_YZ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6005917294954907}} {"text": "classdef MatrixVectorizedInverter_2x2 < MatrixVectorizedInverter_Interface\n \n methods (Access = public)\n \n function B = computeInverse(obj,A)\n d(1,1,:) = A(2,2,:);\n d(1,2,:) = -A(1,2,:);\n d(2,1,:) = -A(2,1,:);\n d(2,2,:) = A(1,1,:);\n \n det = obj.computeDeterminant(A);\n \n B = zeros(size(A));\n for i = 1:2\n for j = 1:2\n B(i,j,:) = squeeze(d(i,j,:))./det;\n end\n end\n end\n \n function detA = computeDeterminant(~,A)\n detA = squeeze(A(1,1,:).*A(2,2,:)-A(1,2,:).*A(2,1,:));\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Operators/MatrixVectorizedInverter/MatrixVectorizedInverter_2x2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.6005917217008826}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cam.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function f = cam(x,y)\n% Four-hump camel\nfunction f = cam(x,y)\nif nargin == 1\n x1 = x(1);\n x2 = x(2);\nelse\n x1 = x;\n x2 = y;\nend\nf=(4-2.1.*x1.^2+x1.^4./3).*x1.^2+x1.*x2+(-4+4.*x2.^2).*x2.^2; \n\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/jones/cam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6005453697563637}} {"text": "%+========================================================================+\n%| |\n%| This script uses the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2019. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : nrtBmmAlgebra.m |\n%| # | VERSION : 0.61 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 05.09.2019 |\n%| ( === ) | SYNOPSIS : Block matrix algebra |\n%| `---' | |\n%+========================================================================+\n\n% Cleaning\nclear all\nclose all\nclc\n\n% Library path\nrun('../../addpathGypsilab')\n\n% Dimensions\nN = 200;\n\n% Accuracy\ntol = 1e-3;\n\n% Particles receptors X\nmesh = mshSphere(N,1);\nomega = dom(mesh,3);\nphi0 = fem(mesh,'P0');\nphi1 = fem(mesh,'P1');\n\n% Wave number or frequency (Hz)\nk = 5;\n\n% Green kernel -> exp(1i*k*r)/r\ngreen = '[exp(ikr)/r]';\nGxy = @(X,Y) femGreenKernel(X,Y,green,k) + ...\n sqrt(N).*(X(:,1)==Y(:,1)).*(X(:,2)==Y(:,2)).*(X(:,3)==Y(:,3)) ;\n\n% Particles charges (multiples)\nV0 = (-1+2*rand(length(phi0),2)) + (-1+2i*rand(length(phi0),2));\nV1 = (-1+2*rand(length(phi1),2)) + (-1+2i*rand(length(phi1),2));\n\n% Spatial representation of particles\nfigure\nplot(mesh)\naxis equal \n\n% All forms\ntic\nAh = integral(omega,omega,phi0,Gxy,phi0,tol);\nBv = integral(omega,omega,phi0,green,k,phi1,tol);\nCs = integral(omega,phi1,phi0);\nDf = integral(omega,omega,phi1,Gxy,phi1);\ntoc\n\n%%% Single Builder\ndisp('~~~~~~~~~~~~~ SINGLE BUILDERS ~~~~~~~~~~~~~')\nMb = bmm(Ah);\nsol = Mb * V0;\nref = Ah * V0;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nMb = bmm(Bv);\nsol = Mb * V1;\nref = Bv * V1;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nMb = bmm(Cs);\nsol = Mb * V0;\nref = Cs * V0;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nMb = bmm(Df);\nsol = Mb * V1;\nref = Df * V1;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Multi Builder\ndisp('~~~~~~~~~~~~~ MULTI BUILDERS ~~~~~~~~~~~~~')\nMb = bmm({Ah,Cs';Cs,Df});\nMr = [full(Ah) Cs' ; Cs Df];\nVb = [V0;V1];\nsol = Mb * Vb;\nref = Mr * Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nfigure\nspy(Mb)\n\ndisp(' ')\n\n\n%%% Full conversion\ndisp('~~~~~~~~~~~~~ FULL CONVERSION ~~~~~~~~~~~~~')\nsol = full(Mb) * Vb;\nref = Mr * Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Sparse conversion\ndisp('~~~~~~~~~~~~~ SPARSE CONVERSION ~~~~~~~~~~~~~')\nsol = sparse(Mb) * Vb;\nref = Mr * Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nfigure\nspy(sparse(Mb))\n\ndisp(' ')\n\n\n%%% Transposition\ndisp('~~~~~~~~~~~~~ TRANSPOSITION ~~~~~~~~~~~~~')\nsol = Vb.' * Mb.';\nref = (Mr * Vb).';\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Transposition\ndisp('~~~~~~~~~~~~~ CONJUGATE TRANSPOSITION ~~~~~~~~~~~~~')\nsol = Vb' * Mb';\nref = (Mr * Vb)';\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Concatenation\ndisp('~~~~~~~~~~~~~ CONCATENATION ~~~~~~~~~~~~~')\nAb = Mb;\nBb = bmm({Bv;Df});\nCb = bmm({Ah,Bv});\nDb = bmm(Cs');\nMb2 = [Ab , Bb ; Cb , Db];\nsol = Mb2 * [Vb;V1];\nref = [Ab*Vb + Bb*V1;Cb*Vb+Db*V1];\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nspy(Mb2)\n\ndisp(' ')\n\n\n%%% Scalar product\ndisp('~~~~~~~~~~~~~ SCALAR PRODUCT ~~~~~~~~~~~~~')\nsol = (-(3.*Mb.*2i)) * Vb;\nref = (-3*2i) * (Mr*Vb);\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Addition\ndisp('~~~~~~~~~~~~~ ADDITION ~~~~~~~~~~~~~')\nsol = (Mb+Mb) * Vb;\nref = 2*(Mr*Vb);\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Multiplication\ndisp('~~~~~~~~~~~~~ MULTIPLICATION ~~~~~~~~~~~~~')\nsol = (Mb.'*Mb) * Vb;\nref = Mr.'*(Mr*Vb);\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nfigure\nspy(Mb.'*Mb)\n\ndisp(' ')\n\n\n%%% LU factorization\ndisp('~~~~~~~~~~~~~ LU FACTORISATION ~~~~~~~~~~~~~')\n[Lb,Ub] = lu(Mb);\nsol = Lb * (Ub * Vb);\nref = Mb * Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nfigure\nsubplot(1,2,1); spy(Lb)\nsubplot(1,2,2); spy(Ub)\n\ndisp(' ')\n\n\n%%% Solve LU\ndisp('~~~~~~~~~~~~~ SOLVE LU SYSTEM ~~~~~~~~~~~~~')\nsol = Mb \\ Vb;\nref = Mr \\ Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\ndisp(' ')\n\n\n%%% Inversion\ndisp('~~~~~~~~~~~~~ INVERSION ~~~~~~~~~~~~~')\nMbm1 = inv(Mb);\nsol = Mbm1 * Vb;\nref = Mr \\ Vb;\nnorm(ref-sol,'inf')/norm(ref,'inf')\n\nfigure\nspy(Mbm1)\n\ndisp(' ')\n\n\n\n\ndisp('~~> Michto gypsilab !')\n\n\n\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/nonRegressionTest/blockMatrix/nrtBmmAlgebra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949104, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6005453554778818}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n%==============================================================================\n%\n% Tutorial for FAIR: compact version of matrix-free regularization\n%\n% S(y) = alpha/2 * norm(B*(y-yRef))^2,\n%\n% where\n% alpha regularization parameter, weights regularization versus \n% distance in the joint objective function, alpha = 1 here\n% yRef is a reference configuration, e.g. yRef = x or a \n% pre-registration result\n% B a discrete partial differential operator either in explicit\n% matrix form or as a structure containing the necessary\n% parameters to compute B*y\n% see also regularizer E8_regularization_MB\n%==============================================================================\n\nclear, close all, help(mfilename);\n\n\n% initialize the regularization and create a starting point\nregularizer('reset','regularizer','mfElastic','alpha',1,'mu',1,'lambda',0);\ny0 = @(omega,m) randn(size(getStaggeredGrid(omega,m)));\n\n% 2D example, initialize physical domain and number of discretization points\nomega = [0,1,0,1]; m = [16,12]; % \n\n% test derivative of 2D implementation\nfctn = @(yc) regularizer(yc,omega,m); checkDerivative(fctn,y0(omega,m));\n\n% 3D example, initialize physical domain and number of discretization points\nomega = [0,1,0,1,0,1]; m = [16,12,8];\n\n% test derivative of 3D implementation\nfctn = @(yc) regularizer(yc,omega,m); \ncheckDerivative(fctn,y0(omega,m));\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E8_regularizationElasticMF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.6004206592869592}} {"text": "function gd=gabdual(g,a,M,varargin)\n%GABDUAL Canonical dual window of Gabor frame\n% Usage: gd=gabdual(g,a,M);\n% gd=gabdual(g,a,M,L);\n% gd=gabdual(g,a,M,'lt',lt);\n%\n% Input parameters:\n% g : Gabor window.\n% a : Length of time shift.\n% M : Number of channels.\n% L : Length of window. (optional)\n% lt : Lattice type (for non-separable lattices).\n% Output parameters:\n% gd : Canonical dual window.\n%\n% `gabdual(g,a,M)` computes the canonical dual window of the discrete Gabor\n% frame with window *g* and parameters *a*, *M*.\n%\n% The window *g* may be a vector of numerical values, a text string or a\n% cell array. See the help of |gabwin| for more details.\n%\n% If the length of *g* is equal to *M*, then the input window is assumed\n% to be an FIR window. In this case, the canonical dual window also has\n% length of *M*. Otherwise the smallest possible transform length is chosen\n% as the window length.\n%\n% `gabdual(g,a,M,L)` returns a window that is the dual window for a system\n% of length *L*. Unless the dual window is a FIR window, the dual window\n% will have length *L*.\n%\n% `gabdual(g,a,M,'lt',lt)` does the same for a non-separable lattice\n% specified by *lt*. Please see the help of |matrix2latticetype| for a\n% precise description of the parameter *lt*.\n%\n% If $a>M$ then the dual window of the Gabor Riesz sequence with window\n% *g* and parameters *a* and *M* will be calculated.\n%\n% Examples:\n% ---------\n%\n% The following example shows the canonical dual window of the Gaussian\n% window:::\n%\n% a=20;\n% M=30;\n% L=300;\n% g=pgauss(L,a*M/L);\n% gd=gabdual(g,a,M);\n% \n% % Simple plot in the time-domain\n% figure(1);\n% plot(gd);\n%\n% % Frequency domain\n% figure(2);\n% magresp(gd,'dynrange',100);\n%\n% See also: gabtight, gabwin, fir2long, dgt\n\n% AUTHOR : Peter L. Søndergaard.\n% TESTING: TEST_DGT\n% REFERENCE: REF_GABDUAL.\n \n%% ---------- Assert correct input.\n\nif nargin<3\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\ndefinput.keyvals.L=[];\ndefinput.keyvals.lt=[0 1];\ndefinput.keyvals.nsalg=0;\n[flags,kv,L]=ltfatarghelper({'L'},definput,varargin);\n\n%% ------ step 2: Verify a, M and L\nif isempty(L)\n if isnumeric(g)\n % Use the window length\n Ls=length(g);\n else\n % Use the smallest possible length\n Ls=1;\n end;\n\n % ----- step 2b : Verify a, M and get L from the window length ----------\n L=dgtlength(Ls,a,M,kv.lt);\n\nelse\n\n % ----- step 2a : Verify a, M and get L\n\n Luser=dgtlength(L,a,M,kv.lt);\n if Luser~=L\n error(['%s: Incorrect transform length L=%i specified. Next valid length ' ...\n 'is L=%i. See the help of DGTLENGTH for the requirements.'],...\n upper(mfilename),L,Luser);\n end;\n\nend;\n\n%% ----- step 3 : Determine the window \n\n[g,info]=gabwin(g,a,M,L,kv.lt,'callfun',upper(mfilename));\n\nif LM*R\n % Handle the Riesz basis (dual lattice) case.\n % Swap a and M, and scale differently.\n scale=a/M;\n tmp=a;\n a=M;\n M=tmp;\nend;\n\n% -------- Compute ------------- \n\nif kv.lt(2)==1\n % Rectangular case\n if (info.gl<=M) && (R==1)\n \n % Diagonal of the frame operator\n d = gabframediag(g,a,M,L);\n gd=g./long2fir(d,info.gl);\n \n else\n \n % Long window case\n \n % Just in case, otherwise the call is harmless. \n g=fir2long(g,L);\n \n gd=comp_gabdual_long(g,a,M)*scale;\n \n end;\n\nelse\n % Non-separable case\n g=fir2long(g,L);\n\n if (kv.nsalg==1) || (kv.nsalg==0 && kv.lt(2)<=2) \n \n mwin=comp_nonsepwin2multi(g,a,M,kv.lt,L);\n \n gdfull=comp_gabdual_long(mwin,a*kv.lt(2),M)*scale;\n \n % We need just the first vector\n gd=gdfull(:,1);\n \n else \n \n [s0,s1,br] = shearfind(L,a,M,kv.lt); \n \n if s1 ~= 0\n p1 = comp_pchirp(L,s1);\n g = p1.*g; \n end\n \n b=L/M;\n Mr = L/br;\n ar = a*b/br;\n \n if s0 == 0\n gd=comp_gabdual_long(g,ar,Mr);\n else \n p0=comp_pchirp(L,-s0);\n g = p0.*fft(g);\n gd=comp_gabdual_long(g,L/Mr,L/ar)*L;\n gd = ifft(conj(p0).*gd); \n end\n \n if s1 ~= 0\n gd = conj(p1).*gd;\n end\n \n end;\n\n if (info.gl<=M) && (R==1)\n gd=long2fir(gd,M);\n end;\n \nend;\n \n% --------- post process result -------\n\nif isreal(g) && (kv.lt(2)==1 || kv.lt(2)==2)\n % If g is real and the lattice is either rectangular or quinqux, then\n % the output is known to be real.\n gd=real(gd);\nend;\n\nif info.wasrow\n gd=gd.';\nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabdual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6003737781083881}} {"text": "\n% Simulation code for [1], presented in ICIP'09 (http://www.icip2009.org/)\n%\n% [1] Paul Rodriguez and Brendt Wohlberg, \"A Generalized Vector-Valued Total \n% Variation Algorithm\", in Proceedings of IEEE International Conference \n% on Image Processing (ICIP), (Cairo, Egypt), doi:10.1109/ICIP.2009.5413587 , \n% pp. 1309--1312, Nov 2009\n%\n% Legal:\n% irnIcip09.m is based on NUMIPAD (http://numipad.sf.net). NUMIPAD is free\n% software, you can redistribute it and/or modify it under the terms of \n% the GNU General Public License (version 2).\n%\n% The NUMIPAD library is being developed under U.S. Government contract\n% W-7405-ENG-36 for Los Alamos National Laboratory.\n% \n% Authors\n% Paul Rodriguez prodrig@pucp.edu.pe\n% Brendt Wohlberg brendt@tmail.lanl.gov\n\n\n\nclear all; \n%close all;\n\nSHOW_IMGS = false;\n% SHOW_IMGS = true;\n\n% example = 'icip09'\n% example = 'l1deconv';\n% example = 'l2deconv';\nexample = 'l1denoise';\n% example = 'l2denoise';\n\n\nextreme = 0;\n\n\nnmppath;\n\nBKS_CODE = exist('MainRestoration');\nif( (BKS_CODE == 0) && ( strcmp(example, 'l1deconv') || strcmp(example, 'l2deconv') || strcmp(example, 'icip09') ) )\n disp('NOTE:');\n disp(' The function MainRestoration (code for [BKS]) is not in your path...');\n disp(sprintf(' disabling BKS simulations for %s.\\n',example));\n disp(' [BKS] L. Bar, A. Brook, N. Sochen and N. Kiryati');\n disp(' \"Deblurring of Color Images Corrupted by Impulsive Noise\" ');\n disp(' IEEE Transactions on Image Processing, 16 (1101-1111), 2007');\nend\n\nBnG_CODE = exist('tvdenoise');\nif( (BnG_CODE == 0) && ( strcmp(example, 'l2denoise') || strcmp(example, 'icip09') ) )\n disp('NOTE:');\n disp(' The function tvdenoise (code for [BnG]) is not in your path...');\n disp(sprintf(' disabling BnG simulations for %s.\\n',example));\n disp(' [BnG] an implementation of the fast dual minimization of VTV [1].');\n disp(' Code may be downloaded from:');\n disp(' http://www.mathworks.fr/matlabcentral/fileexchange/16236');\n disp(' [1] X. Bresson and T. Chan');\n disp(' \"Fast dual minimization of the vectorial total variation norm and');\n disp(' applications to color image processing\"');\n disp(' Journal of Inverse Problems and Imaging, 2:4(455--484), 2008');\nend\n\n\nif( exist('color_imgs/peppers_color.png') && exist('color_imgs/mandrill_color.png') ...\n && exist('color_imgs/lena_color_256.png') )\n disp(sprintf('\\nRunning %s simulation... \\n', example));\nelse\n disp(' ');\n disp('One or more test images are not in the current directory...');\n disp('You may download them from:');\n disp('http://sites.google.com/a/istec.net/prodrig/Home/en/pubs');\n disp('look for \"test images\" under \"A Generalized Vector-Valued Total ');\n disp('Variation Algorithm\"');\n disp(' ');\n disp('Exiting simulation code...');\n return;\nend\n\nif( strcmp(example, 'icip09') ) \n\n str_all = [];\n ICIP_FLAG = 1;\n\nelse\n\n ICIP_FLAG = 0;\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Input images %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\npepImg = imread('peppers_color.png');\npepImg = double(pepImg)/255.0;\n\nlenImg = imread('lena_color_256.png');\nlenImg = double(lenImg)/255.0;\n\nmdrilImg = imread('mandrill_color.png');\nmdrilImg = double(mdrilImg)/255.0;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Normalize %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nNormalize = @(x) (x - min(x(:)))/(max(x(:)) - min(x(:)));\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% kernels %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\nkernel_BSK = fspecial('disk',3.2);\n\nK_BSK = @(x) imfilter(x, kernel_BSK, 'symmetric','conv');\nKT_BSK = @(x) K_BSK(x);\nKC_BSK = {K_BSK, KT_BSK};\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Blurred & noisy images %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nlenImgBlur = K_BSK(lenImg);\n\nlenImgBlur_01L1 = imnoise(lenImgBlur, 'salt & pepper', 0.1);\nlenImgBlur_03L1 = imnoise(lenImgBlur, 'salt & pepper', 0.3);\n\n% ---\n\nlenImgBlur_01L2 = imnoise(lenImgBlur, 'gaussian', 0, ...\n 0.01*max(lenImgBlur(:)) ); %NOTE sigma^2 in imnoise\n\nlenImgBlur_005L2 = imnoise(lenImgBlur,'gaussian', 0, ...\n 0.0025*max(lenImgBlur(:)) );\n\nlenImgBlur_001L2 = imnoise(lenImgBlur,'gaussian', 0, ...\n 0.0001*max(lenImgBlur(:)) );\n% -- BSK example ---:\nlenImgBlur_bskL2 = imnoise(lenImgBlur,'gaussian', 0, ...\n 0.00001*max(lenImgBlur(:)) ); \n\n% ---\n\nmdrilImg_01L1 = imnoise(mdrilImg, 'salt & pepper', 0.1);\nmdrilImg_03L1 = imnoise(mdrilImg, 'salt & pepper', 0.3);\n\nmdrilImg_01L2 = imnoise(mdrilImg, 'gaussian', 0, ...\n 0.01*max(mdrilImg(:)) ); %NOTE sigma^2 in imnoise\nmdrilImg_005L2 = imnoise(mdrilImg, 'gaussian', 0, ...\n 0.0025*max(mdrilImg(:)) );\n\n% ---\n\npepImg_01L1 = imnoise(pepImg, 'salt & pepper', 0.1);\npepImg_03L1 = imnoise(pepImg, 'salt & pepper', 0.3);\n\npepImg_01L2 = imnoise(pepImg, 'gaussian', 0, 0.01*max(pepImg(:)) );\npepImg_005L2 = imnoise(pepImg, 'gaussian', 0, 0.0025*max(pepImg(:)) );\n\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l1deconv') || strcmp(example,'icip09') )\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% L1 Deconvolved %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%noise level: 0.1\n\n%-- IRN\nlambda = 0.035;\npars = irntvInputPars('l1tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 4;\n% pars.pcgtol_ini = 1e-4;\npars.U0 = lenImgBlur_01L1;\n\ntic;\nIRN_lenImgBlur_01L1 = irntv(lenImgBlur_01L1, KC_BSK, lambda, pars);\ntirn_01L1n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_01L1) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_01L1), tirn_01L1n0));\nend\n\nif(BKS_CODE)\n%-- BSK MSTV (Mumford-Shah TV)\n\nParams = SetParams;\nParams.beta=0.5; % check - same value as bar-2007-deblurring\nParams.alpha=0.1; % check\nParams.epsilon=0.1; % check\nParams.gamma = 2*10^(-3); % as \"\\mu in bar-2007-deblurring table IV\n\n% [uh_mstv,V] = MainRestoration(z, kernel, 'L1', 'MSTV', Params);\ntic;\n[MSTV_lenImgBlur_01L1, V_MSTV_01L1] = MainRestoration(lenImgBlur_01L1, ...\n kernel_BSK, 'L1', 'MSTV', Params);\ntbsk_01L1n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_01L1 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_01L1), tbsk_01L1n0));\nend\n\n%-- BSK 1^1-TV \nParams = SetParams;\nParams.beta=0.1; % check - same value as bar-2007-deblurring\n\ntic;\n[BKSL1_lenImgBlur_01L1, V_BKSL1_01L1] = MainRestoration(lenImgBlur_01L1, ...\n kernel_BSK, 'L1', 'L1', Params);\ntbsk_01L1n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( BKSL1_lenImgBlur_01L1 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - BKSL1. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, BKSL1_lenImgBlur_01L1), tbsk_01L1n1));\nend\n\nend % _END_ if(BKS_CODE)\n%------------------------------------------------------------------------------\n\n\n%noise level: 0.3\n\nlambda = 0.070;\npars = irntvInputPars('l1tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 6;\n% pars.pcgtol_ini = 1e-4;\npars.U0 = lenImgBlur_03L1;\n\n\ntic;\nIRN_lenImgBlur_03L1 = irntv(lenImgBlur_03L1, KC_BSK, lambda, pars);\ntirn_03L1n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_03L1) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_03L1), tirn_03L1n0));\nend\n\n\nif(BKS_CODE)\n%-- BSK MSTV (Mumford-Shah TV)\n\nParams = SetParams;\nParams.beta=1.1; % as describe in bar-2007-deblurring, table IV\nParams.alpha=0.5; % as describe in bar-2007-deblurring, table IV\nParams.epsilon=0.1; % check\nParams.gamma = 2*10^(-3);\n\n% [uh_mstv,V] = MainRestoration(z, kernel, 'L1', 'MSTV', Params);\ntic;\n[MSTV_lenImgBlur_03L1, V_MSTV_03L1] = MainRestoration(lenImgBlur_03L1, ...\n kernel_BSK, 'L1', 'MSTV', Params);\ntbsk_03L1n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_03L1 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_03L1), tbsk_03L1n0));\nend\n\n%-- BSK L1 \n\nParams = SetParams;\nParams.beta=0.2; % as describe in bar-2007-deblurring, table IV\n\ntic;\n[BKSL1_lenImgBlur_03L1, V_MSTV_03L1] = MainRestoration(lenImgBlur_03L1, ...\n kernel_BSK, 'L1', 'L1', Params);\ntbsk_03L1n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( BKSL1_lenImgBlur_03L1 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, BKSL1_lenImgBlur_03L1), tbsk_03L1n1));\nend\n\nend % _END_ if(BKS_CODE)\n\nif(ICIP_FLAG == 0)\n\n disp('L1 Deconvolve Vector TV'); \n disp(' ');\n disp(' SNR (db) Time (s)');\n disp(' Img Noise VTV-IRN MSTV BKSL1 VTV IRN MSTV BKSL1');\n disp(' ');\n if(BKS_CODE)\n disp(sprintf('Lena 0.1 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_01L1), snr(lenImg, MSTV_lenImgBlur_01L1), snr(lenImg, BKSL1_lenImgBlur_01L1), ...\n tirn_01L1n0, tbsk_01L1n0, tbsk_01L1n1));\n disp(sprintf(' 0.3 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_03L1), snr(lenImg, MSTV_lenImgBlur_03L1), snr(lenImg, BKSL1_lenImgBlur_03L1), ...\n tirn_03L1n0, tbsk_03L1n0, tbsk_03L1n1));\n else\n disp(sprintf('Lena 0.1 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_01L1), NaN, NaN, ...\n tirn_01L1n0, NaN, NaN));\n disp(sprintf(' 0.3 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_03L1), NaN, NaN, ...\n tirn_03L1n0, NaN, NaN));\n\n end % _END_ if(BKS_CODE)\n\nelse % IF(icip)\n\n str = sprintf('L1 Deconvolve Vector TV\\n\\n'); \n str_all = [str_all str];\n str = sprintf(' SNR (db) Time (s)\\n');\n str_all = [str_all str];\n str = sprintf(' Img Noise VTV-IRN MSTV BKSL1 VTV IRN MSTV BKSL1\\n\\n');\n str_all = [str_all str];\n\n if(BKS_CODE)\n str = sprintf('Lena 0.1 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_01L1), snr(lenImg, MSTV_lenImgBlur_01L1), snr(lenImg, BKSL1_lenImgBlur_01L1), ...\n tirn_01L1n0, tbsk_01L1n0, tbsk_01L1n1);\n str_all = [str_all str];\n str = sprintf(' 0.3 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(lenImg, IRN_lenImgBlur_03L1), snr(lenImg, MSTV_lenImgBlur_03L1), snr(lenImg, BKSL1_lenImgBlur_03L1), ...\n tirn_03L1n0, tbsk_03L1n0, tbsk_03L1n1);\n str_all = [str_all str];\n else\n str = sprintf('Lena 0.1 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_01L1), NaN, NaN, ...\n tirn_01L1n0, NaN, NaN);\n str_all = [str_all str];\n str = sprintf(' 0.3 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(lenImg, IRN_lenImgBlur_03L1), NaN, NaN, ...\n tirn_03L1n0, NaN, NaN);\n str_all = [str_all str];\n\n end % _END_ if(BKS_CODE)\n\nend\n\nend % _END_ if( strcmp(example,'l1deconv') || strcmp(example,'icip09') )\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l2deconv') || strcmp(example,'icip09') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% L2 Deconvolved %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif(extreme == 1)\n\n%noise level: 0.1\n\n%-- IRN\nlambda = 0.04;\npars = irntvInputPars('l2tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 3;\npars.pcgtol_ini = 1e-4;\n% pars.U0 = lenImgBlur_01L2;\n\n\ntic;\nIRN_lenImgBlur_01L2 = irntv(lenImgBlur_01L2, KC_BSK, lambda, pars);\ntirn_01L2n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_01L2) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_01L2), tirn_01L2n0));\nend\n\nif(BKS_CODE)\n%-- BSK MSTV (Mumford-Shah TV)\n\n\nParams = SetParams;\nParams.beta = 0.01*max(lenImgBlur(:));\n\ntic;\n[MSTV_lenImgBlur_01L2, V_MSTV_001L2] = MainRestoration(lenImgBlur_01L2, ...\n kernel_BSK, 'L2', 'MS', Params);\ntbsk_01L2n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_01L2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_01L2), tbsk_01L2n0));\nend\n\nend % _END_ if(BKS_CODE)\nend % _END_ if(extreme == 1)\n%-----------------------------------------------------------------------------\n\n%noise level: 0.05\n\n%-- IRN\nlambda = 0.01;\npars = irntvInputPars('l2tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 3;\n% pars.pcgtol_ini = 1e-4;\npars.U0 = lenImgBlur_005L2;\n\n\ntic;\nIRN_lenImgBlur_005L2 = irntv(lenImgBlur_005L2, KC_BSK, lambda, pars);\ntirn_005L2n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_005L2) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_005L2), tirn_005L2n0));\nend\n\nif(BKS_CODE)\n%-- BSK\n\nParams = SetParams;\nParams.beta = 0.0025*max(lenImgBlur(:));\n\ntic;\n[MSTV_lenImgBlur_005L2, V_MSTV_05L2] = MainRestoration(lenImgBlur_005L2, ...\n kernel_BSK, 'L2', 'MS', Params);\ntbsk_005L2n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_005L2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_005L2), tbsk_005L2n0));\nend\n\n%-- BSK l2-VTV\n\nParams = SetParams;\nParams.beta = 0.0025*max(lenImgBlur(:));\n\ntic;\n[BSKL2_lenImgBlur_005L2, V_MSTV_05L2] = MainRestoration(lenImgBlur_005L2, ...\n kernel_BSK, 'L2', 'L1', Params);\ntbsk_005L2n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( BSKL2_lenImgBlur_005L2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, BSKL2_lenImgBlur_005L2), tbsk_005L2n1));\nend\n\nend % _END_ if(BKS_CODE)\n\n%-----------------------------------------------------------------------------\n\n\n%noise level: 0.01\n\n%-- IRN\nlambda = 0.0005;\n\npars = irntvInputPars('l2tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 3;\n% pars.pcgtol_ini = 1e-4;\npars.U0 = lenImgBlur_001L2;\n\ntic;\nIRN_lenImgBlur_001L2 = irntv(lenImgBlur_001L2, KC_BSK, lambda, pars);\ntirn_001L2n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_001L2) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_001L2), tirn_001L2n0));\nend\n\nif(BKS_CODE)\n%-- BSK MSTV (Mumford-Shah TV)\n\n\nParams = SetParams;\nParams.beta = 0.0001;\n\ntic;\n[MSTV_lenImgBlur_001L2, V_MSTV_001L2] = ...\n MainRestoration(Normalize(lenImgBlur_001L2), kernel_BSK, 'L2', 'MS', Params);\ntbsk_001L2n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_001L2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_001L2), tbsk_001L2n0));\nend\n\n%-- BSK L2-VTV\n\n\nParams = SetParams;\nParams.beta = 0.0001;\n\ntic;\n[BSKL2_lenImgBlur_001L2, V_MSTV_001L2] = ...\n MainRestoration(Normalize(lenImgBlur_001L2), kernel_BSK, 'L2', 'L1', Params);\ntbsk_001L2n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( BSKL2_lenImgBlur_001L2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, BSKL2_lenImgBlur_001L2), tbsk_001L2n1));\nend\n\nend % _END_ if(BKS_CODE)\n\n%-----------------------------------------------------------------------------\n\n%noise level: sqrt(1e-5) BSK example\n\n%-- IRN\nlambda = 0.0001;\npars = irntvInputPars('l2tv');\n\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 3;\n% pars.pcgtol_ini = 1e-4;\npars.U0 = lenImgBlur_bskL2;\n\ntic;\nIRN_lenImgBlur_bskL2 = irntv(lenImgBlur_bskL2, KC_BSK, lambda, pars);\ntirn_bskL2n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_lenImgBlur_bskL2) );\n axis image; axis off;\n title(sprintf('Deconvolved Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, IRN_lenImgBlur_bskL2), tirn_bskL2n0));\nend\n\nif(BKS_CODE)\n\n%-- BSK MSTV (Mumford-Shah TV)\n\n\nParams = SetParams;\nParams.beta = 0.00001;\n\ntic;\n[MSTV_lenImgBlur_bskL2, V_MSTV_bskL2] = ...\n MainRestoration(Normalize(lenImgBlur_bskL2), kernel_BSK, 'L2', 'MS', Params);\ntbsk_bskL2n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( MSTV_lenImgBlur_bskL2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, MSTV_lenImgBlur_bskL2), tbsk_bskL2n0));\nend\n\n%-- BSK l2-VTV\n\n\nParams = SetParams;\nParams.beta = 0.00001;\n\ntic;\n[BSKL2_lenImgBlur_bskL2, V_MSTV_bskL2] = ...\n MainRestoration(Normalize(lenImgBlur_bskL2), kernel_BSK, 'L2', 'L1', Params);\ntbsk_bskL2n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( BSKL2_lenImgBlur_bskL2 );\n axis image; axis off;\n title(sprintf('Deconvolved Image - MSTV. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(lenImg, BSKL2_lenImgBlur_bskL2), tbsk_bskL2n1));\nend\n\nend % _END_ if(BKS_CODE)\n\n%-----------------------------------------------------------------------------\n\nif(ICIP_FLAG == 0)\n\n disp('L2 Deconvolve Vector TV');\n disp(' ');\n disp(' SNR (db) Time (s)');\n disp(' Img Noise VTV-IRN L2-MS(BSK) BSK-L2 VTV IRN L2-MS(BKS) BSK-L2');\n disp(' ');\n if(BKS_CODE)\n disp(sprintf('Lenna 0.05 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_005L2), snr(lenImg, MSTV_lenImgBlur_005L2), snr(lenImg, BSKL2_lenImgBlur_005L2), ...\n tirn_005L2n0, tbsk_005L2n0, tbsk_005L2n1));\n disp(sprintf('Lenna 0.01 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_001L2), snr(lenImg, MSTV_lenImgBlur_001L2), snr(lenImg, BSKL2_lenImgBlur_001L2), ...\n tirn_001L2n0, tbsk_001L2n0, tbsk_001L2n1));\n disp(sprintf('Lenna sqrt(1e-5) %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_bskL2), snr(lenImg, MSTV_lenImgBlur_bskL2), snr(lenImg, BSKL2_lenImgBlur_bskL2), ...\n tirn_bskL2n0, tbsk_bskL2n0, tbsk_bskL2n1));\n else\n disp(sprintf('Lenna 0.05 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_005L2), NaN, NaN, ...\n tirn_005L2n0, NaN, NaN));\n disp(sprintf('Lenna 0.01 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_001L2), NaN, NaN, ...\n tirn_001L2n0, NaN, NaN));\n disp(sprintf('Lenna sqrt(1e-5) %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f', ...\n snr(lenImg, IRN_lenImgBlur_bskL2), NaN, NaN, ...\n tirn_bskL2n0, NaN, NaN));\n end % _END_ if(BKS_CODE)\n\n\nelse\n\n str = sprintf('L2 Deconvolve Vector TV\\n\\n');\n str_all = [str_all str];\n str = sprintf(' SNR (db) Time (s)\\n');\n str_all = [str_all str];\n str = sprintf(' Img Noise VTV-IRN L2-MS(BSK) BSK-L2 VTV IRN L2-MS(BKS) BSK-L2\\n\\n');\n str_all = [str_all str];\n\n if(BKS_CODE)\n str = sprintf('Lena 0.05 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_005L2), snr(lenImg, MSTV_lenImgBlur_005L2), snr(lenImg, BSKL2_lenImgBlur_005L2), ...\n tirn_005L2n0, tbsk_005L2n0, tbsk_005L2n1);\n str_all = [str_all str];\n str = sprintf('Lena 0.01 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_001L2), snr(lenImg, MSTV_lenImgBlur_001L2), snr(lenImg, BSKL2_lenImgBlur_001L2), ...\n tirn_001L2n0, tbsk_001L2n0, tbsk_001L2n1);\n str_all = [str_all str];\n str = sprintf('Lena sqrt(1e-5) %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(lenImg, IRN_lenImgBlur_bskL2), snr(lenImg, MSTV_lenImgBlur_bskL2), snr(lenImg, BSKL2_lenImgBlur_bskL2), ...\n tirn_bskL2n0, tbsk_bskL2n0, tbsk_bskL2n1);\n str_all = [str_all str];\n else\n str = sprintf('Lena 0.05 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_005L2), NaN, NaN, ...\n tirn_005L2n0, NaN, NaN);\n str_all = [str_all str];\n str = sprintf('Lena 0.01 %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(lenImg, IRN_lenImgBlur_001L2), NaN, NaN, ...\n tirn_001L2n0, NaN, NaN);\n str_all = [str_all str];\n str = sprintf('Lena sqrt(1e-5) %5.1f %5.1f %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(lenImg, IRN_lenImgBlur_bskL2), NaN, NaN, ...\n tirn_bskL2n0, NaN, NaN);\n str_all = [str_all str];\n end % _END_ if(BKS_CODE)\n\nend\n\nend % _END_ if( strcmp(example,'l2deconv') || strcmp(example,'icp09') )\n\n%-----------------------------------------------------------------------------\n\n\n\n\nif( strcmp(example,'l1denoise') || strcmp(example,'icip09') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% L1 Denoise %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%noise level: 0.1\n\n%-- IRN\nlambda = 1.1;\n\npars = irntvInputPars('l1tv');\n\npars.pcgtol_ini = 1e-4;\npars.epsF = 1e-2; \npars.epsR = 1e-4;\npars.loops = 2;\n\n\n%-- peppers\ntic;\nIRN_pepImg_01L1 = irntv(pepImg_01L1, [], lambda, pars);\ntirn_01L1n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_pepImg_01L1) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, IRN_pepImg_01L1), tirn_01L1n0));\nend\n\n%-- mandrill\ntic;\nIRN_mdrilImg_01L1 = irntv(mdrilImg_01L1, [], lambda, pars);\ntirn_01L1n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_mdrilImg_01L1) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, IRN_mdrilImg_01L1), tirn_01L1n1));\nend\n\n%-----------------------------------------------------------------------------\n\n%noise level: 0.3\n\n%-- IRN\nlambda = 1.2;\n\npars = irntvInputPars('l1tv');\n\npars.pcgtol_ini = 1e-4;\npars.epsF = 1e-2; \npars.epsR = 1e-4;\npars.loops = 2;\n\n\n%-- peppers\ntic;\nIRN_pepImg_03L1 = irntv(pepImg_03L1, [], lambda, pars);\ntirn_03L1n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_pepImg_03L1) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, IRN_pepImg_03L1), tirn_03L1n0));\nend\n\n%-- mandrill\n\ntic;\nIRN_mdrilImg_03L1 = irntv(mdrilImg_03L1, [], lambda, pars);\ntirn_03L1n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_mdrilImg_03L1) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, IRN_mdrilImg_03L1), tirn_03L1n1));\nend\n\n%-----------------------------------------------------------------------------\n\nif(ICIP_FLAG == 0)\n\n disp('L1 Denoise Vector TV (Vector IRN algorithm)');\n disp(' ');\n disp(' SNR (db) Time (s)');\n disp(' Img Noise VTV IRN VTV IRN');\n disp(' ');\n disp(sprintf('Peppers 0.1 %5.1f %5.1f ', ...\n snr(pepImg, IRN_pepImg_01L1), tirn_01L1n0));\n disp(sprintf(' 0.3 %5.1f %5.1f ', ...\n snr(pepImg, IRN_pepImg_03L1), tirn_03L1n0));\n disp(sprintf('Mandrill 0.1 %5.1f %5.1f ', ...\n snr(mdrilImg, IRN_mdrilImg_01L1), tirn_01L1n1));\n disp(sprintf(' 0.3 %5.1f %5.1f ', ...\n snr(mdrilImg, IRN_mdrilImg_03L1), tirn_03L1n1));\n\nelse\n\n str = sprintf('L1 Denoise Vector TV (Vector IRN algorithm)\\n\\n');\n str_all = [str_all str];\n str = sprintf(' SNR (db) Time (s)\\n');\n str_all = [str_all str];\n str = sprintf(' Img Noise VTV IRN VTV IRN\\n\\n');\n str_all = [str_all str];\n \n str = sprintf('Peppers 0.1 %5.1f %5.1f \\n', ...\n snr(pepImg, IRN_pepImg_01L1), tirn_01L1n0);\n str_all = [str_all str];\n str = sprintf(' 0.3 %5.1f %5.1f \\n', ...\n snr(pepImg, IRN_pepImg_03L1), tirn_03L1n0);\n str_all = [str_all str];\n str = sprintf('Mandrill 0.1 %5.1f %5.1f \\n', ...\n snr(mdrilImg, IRN_mdrilImg_01L1), tirn_01L1n1);\n str_all = [str_all str];\n str = sprintf(' 0.3 %5.1f %5.1f \\n\\n\\n', ...\n snr(mdrilImg, IRN_mdrilImg_03L1), tirn_03L1n1);\n str_all = [str_all str];\n\nend\n\nend % _END_ if( strcmp(example,'l1denoise') || strcmp(example,'icip09') )\n\n\n%-----------------------------------------------------------------------------\n\n\nif( strcmp(example,'l2denoise') || strcmp(example,'icip09') )\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% L2 Denoise %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%noise level: 0.1\n\n%-- IRN\nlambda = 0.3;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\n% pars.epsF = 1e-1; \n% pars.epsR = 1e-2;\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 1;\n\n\ntic;\nIRN_pepImg_01L2 = irntv(pepImg_01L2, [], lambda, pars);\ntirn_01L2n0 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_pepImg_01L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, IRN_pepImg_01L2), tirn_01L2n0));\nend\n\nif(BnG_CODE)\n%% http://www.mathworks.fr/matlabcentral/fileexchange/16236\n%% Pascal Getreuer based on X. Bresson and T.F. Chan, \n%% \"Fast Minimization of the Vectorial Total Variation Norm and Applications \n%% to Color Image Processing\", CAM Report 07-25.\n\nlambda = 0.15;\n\ntic;\nBnG_pepImg_01L2 = tvdenoise(pepImg_01L2, 1/lambda);\ntirn_01L2n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(BnG_pepImg_01L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - BnG. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, BnG_pepImg_01L2), tirn_01L2n1));\nend\n\nend % _END_ if(BnG_CODE)\n\n%------------\n\n%-- IRN\nlambda = 0.3;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\n% pars.epsF = 1e-1; \n% pars.epsR = 1e-2;\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 1;\n\ntic;\nIRN_mdrilImg_01L2 = irntv(mdrilImg_01L2, [], lambda, pars);\ntirn_01L2n2 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_mdrilImg_01L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, IRN_mdrilImg_01L2), tirn_01L2n2));\nend\n\n\nif(BnG_CODE)\n%% http://www.mathworks.fr/matlabcentral/fileexchange/16236\n%% Pascal Getreuer based on X. Bresson and T.F. Chan, \n%% \"Fast Minimization of the Vectorial Total Variation Norm and Applications \n%% to Color Image Processing\", CAM Report 07-25.\n\nlambda = 0.15;\n\ntic;\nBnG_mdrilImg_01L2 = tvdenoise(mdrilImg_01L2, 1/lambda);\ntirn_01L2n3 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(BnG_mdrilImg_01L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - BnG. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, BnG_mdrilImg_01L2), tirn_01L2n3));\nend\n\nend % _END_ if(BnG_CODE)\n\n%-----------------------------------------------------------------------------\n\n\n%noise level: 0.05\n\n%-- IRN\nlambda = 0.1;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\n% pars.epsF = 1e-1; \n% pars.epsR = 1e-2;\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 1;\n\n\ntic;\nIRN_pepImg_005L2 = irntv(pepImg_005L2, [], lambda, pars);\ntirn_005L2n0 = toc;\n\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_pepImg_005L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, IRN_pepImg_005L2), tirn_005L2n0));\nend\n\nif(BnG_CODE)\n%% http://www.mathworks.fr/matlabcentral/fileexchange/16236\n%% Pascal Getreuer based on X. Bresson and T.F. Chan, \n%% \"Fast Minimization of the Vectorial Total Variation Norm and Applications \n%% to Color Image Processing\", CAM Report 07-25.\n\nlambda = 0.05;\n\ntic;\nBnG_pepImg_005L2 = tvdenoise(pepImg_005L2, 1/lambda);\ntirn_005L2n1 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(BnG_pepImg_005L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - BnG. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(pepImg, BnG_pepImg_005L2), tirn_005L2n1));\nend\n\n\nend % _END_ if(BnG_CODE)\n\n%------------\n\n%-- IRN\nlambda = 0.1;\n\npars = irntvInputPars('l2tv');\n\npars.pcgtol_ini = 1e-4;\n% pars.epsF = 1e-1; \n% pars.epsR = 1e-2;\npars.adapt_epsR = 1;\npars.epsR_cutoff = 0.01;\npars.adapt_epsF = 1;\npars.epsF_cutoff = 0.05;\npars.loops = 1;\n\n\ntic;\nIRN_mdrilImg_005L2 = irntv(mdrilImg_005L2, [], lambda, pars);\ntirn_005L2n2 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(IRN_mdrilImg_005L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - Vector IRN. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, IRN_mdrilImg_005L2), tirn_005L2n2));\nend\n\nif(BnG_CODE)\n%% http://www.mathworks.fr/matlabcentral/fileexchange/16236\n%% Pascal Getreuer based on X. Bresson and T.F. Chan, \n%% \"Fast Minimization of the Vectorial Total Variation Norm and Applications \n%% to Color Image Processing\", CAM Report 07-25.\n\nlambda = 0.05;\n\ntic;\nBnG_mdrilImg_005L2 = tvdenoise(mdrilImg_005L2, 1/lambda);\ntirn_005L2n3 = toc;\n\nif(SHOW_IMGS)\n figure; imagesc( Normalize(BnG_mdrilImg_005L2) );\n axis image; axis off;\n title(sprintf('Denoised Image - BnG. SNR: %4.1fdB.\\n Time %4.1f sec', ...\n snr(mdrilImg, BnG_mdrilImg_005L2), tirn_005L2n3));\nend\n\n\nend % _END_ if(BnG_CODE)\n\n%-----------------------------------------------------------------------------\n\nif(ICIP_FLAG == 0)\n\n disp('L2 Denoise Vector TV (Vector IRN algorithm)');\n disp(' ');\n disp(' SNR (db) Time (s)');\n disp(' Img Noise VTV-IRN bresson-2008-fast VTV IRN bresson-2008-fast');\n disp(' ');\n if(BnG_CODE)\n disp(sprintf('Peppers, 0.1 %5.1f %5.1f %5.1f %5.1f', ...\n snr(pepImg, IRN_pepImg_01L2), snr(pepImg, BnG_pepImg_01L2), ...\n tirn_01L2n0, tirn_01L2n1));\n disp(sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f', ...\n snr(pepImg, IRN_pepImg_005L2), snr(pepImg, BnG_pepImg_005L2), ...\n tirn_005L2n0, tirn_005L2n1));\n disp(sprintf('Mandrill, 0.1 %5.1f %5.1f %5.1f %5.1f', ...\n snr(mdrilImg, IRN_mdrilImg_01L2), snr(mdrilImg, BnG_mdrilImg_01L2), ...\n tirn_01L2n2, tirn_01L2n3));\n disp(sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f', ...\n snr(mdrilImg, IRN_mdrilImg_005L2), snr(mdrilImg, BnG_mdrilImg_005L2), ...\n tirn_005L2n2, tirn_005L2n3));\n else\n disp(sprintf('Peppers, 0.1 %5.1f %5.1f %5.1f %5.1f', ...\n snr(pepImg, IRN_pepImg_01L2), NaN, ...\n tirn_01L2n0, NaN));\n disp(sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f', ...\n snr(pepImg, IRN_pepImg_005L2), NaN, ...\n tirn_005L2n0, NaN));\n disp(sprintf('Mandrill, 0.1 %5.1f %5.1f %5.1f %5.1f', ...\n snr(mdrilImg, IRN_mdrilImg_01L2), NaN, ...\n tirn_01L2n2, NaN));\n disp(sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f', ...\n snr(mdrilImg, IRN_mdrilImg_005L2), NaN, ...\n tirn_005L2n2, NaN));\n end % _END_ if(BnG_CODE)\n\nelse\n\n str = sprintf('L2 Denoise Vector TV (Vector IRN algorithm)\\n\\n');\n str_all = [str_all str];\n str = sprintf(' SNR (db) Time (s)\\n');\n str_all = [str_all str];\n str = sprintf(' Img Noise VTV-IRN bresson-2008-fast VTV IRN bresson-2008-fast\\n\\n');\n str_all = [str_all str];\n\n if(BnG_CODE)\n str = sprintf('Peppers, 0.1 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(pepImg, IRN_pepImg_01L2), snr(pepImg, BnG_pepImg_01L2), ...\n tirn_01L2n0, tirn_01L2n1);\n str_all = [str_all str];\n str = sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(pepImg, IRN_pepImg_005L2), snr(pepImg, BnG_pepImg_005L2), ...\n tirn_005L2n0, tirn_005L2n1);\n str_all = [str_all str];\n str = sprintf('Mandrill, 0.1 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(mdrilImg, IRN_mdrilImg_01L2), snr(mdrilImg, BnG_mdrilImg_01L2), ...\n tirn_01L2n2, tirn_01L2n3);\n str_all = [str_all str];\n str = sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(mdrilImg, IRN_mdrilImg_005L2), snr(mdrilImg, BnG_mdrilImg_005L2), ...\n tirn_005L2n2, tirn_005L2n3);\n str_all = [str_all str];\n else\n str = sprintf('Peppers, 0.1 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(pepImg, IRN_pepImg_01L2), NaN, ...\n tirn_01L2n0, NaN);\n str_all = [str_all str];\n str = sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(pepImg, IRN_pepImg_005L2), NaN, ...\n tirn_005L2n0, NaN);\n str_all = [str_all str];\n str = sprintf('Mandrill, 0.1 %5.1f %5.1f %5.1f %5.1f\\n', ...\n snr(mdrilImg, IRN_mdrilImg_01L2), NaN, ...\n tirn_01L2n2, NaN);\n str_all = [str_all str];\n str = sprintf(' 0.05 %5.1f %5.1f %5.1f %5.1f\\n\\n\\n', ...\n snr(mdrilImg, IRN_mdrilImg_005L2), NaN, ...\n tirn_005L2n2, NaN);\n str_all = [str_all str];\n end % _END_ if(BnG_CODE)\n\n\nend\n\nend % _END_ if( strcmp(example,'l2denoise') || strcmp(example,'icp09') )\n\n%-----------------------------------------------------------------------------\n\nif(ICIP_FLAG == 1)\n\n disp(str_all);\nend\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/GTF/source/icip09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6002464841966467}} {"text": "function value = r8_sin ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIN evaluates the sine of an R8 argument.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real VALUE, the sine of X.\n%\n persistent ntsn\n persistent pi2rec\n persistent pihi\n persistent pilo\n persistent pirec\n persistent sincs\n persistent xmax\n persistent xsml\n persistent xwarn\n\n pi2rec = 0.63661977236758134307553505349006;\n pihi = 3.140625;\n pilo = 9.6765358979323846264338327950288E-04;\n pirec = 0.31830988618379067153776752674503;\n\n if ( isempty ( ntsn ) )\n\n sincs = [ ...\n -0.374991154955873175839919279977323464, ...\n -0.181603155237250201863830316158004754, ...\n +0.005804709274598633559427341722857921, ...\n -0.000086954311779340757113212316353178, ...\n +0.000000754370148088851481006839927030, ...\n -0.000000004267129665055961107126829906, ...\n +0.000000000016980422945488168181824792, ...\n -0.000000000000050120578889961870929524, ...\n +0.000000000000000114101026680010675628, ...\n -0.000000000000000000206437504424783134, ...\n +0.000000000000000000000303969595918706, ...\n -0.000000000000000000000000371357734157, ...\n +0.000000000000000000000000000382486123, ...\n -0.000000000000000000000000000000336623, ...\n +0.000000000000000000000000000000000256 ]';\n\n ntsn = r8_inits ( sincs, 15, 0.1 * r8_mach ( 3 ) );\n xsml = sqrt ( 2.0 * r8_mach ( 3 ) );\n xmax = 1.0 / r8_mach( 4 );\n xwarn = sqrt ( xmax );\n\n end\n\n y = abs ( x );\n\n if ( xmax < y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_SIN - Warning!\\n' );\n fprintf ( 1, ' No precision because |X| is big.\\n' );\n value = 0.0;\n return\n end\n\n if ( xwarn < y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_SIN - Warning!\\n' );\n fprintf ( 1, ' Answer < half precision because |X| is big.\\n' );\n end\n\n value = x;\n if ( y < xsml )\n return\n end\n\n xn = r8_aint ( y * pirec + 0.5 );\n n2 = r8_aint ( mod ( xn, 2.0 ) + 0.5 );\n\n sgn = x;\n if ( n2 ~= 0 )\n sgn = - sgn;\n end\n\n f = ( y - xn * pihi ) - xn * pilo;\n\n xn = 2.0 * ( f * pi2rec ) * ( f * pi2rec ) - 1.0;\n\n value = f + f * r8_csevl ( xn, sincs, ntsn );\n\n if ( sgn < 0.0 )\n value = - value;\n end\n\n if ( value < - 1.0 )\n value = - 1.0;\n elseif ( 1.0 < value )\n value = + 1.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r8_sin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6001973829130653}} {"text": "function value = r4_sqrt ( x )\n\n%*****************************************************************************80\n%\n%% R4_SQRT computes the square root of an R4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 September 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Wayne Fullerton,\n% Portable Special Function Routines,\n% in Portability of Numerical Software,\n% edited by Wayne Cowell,\n% Lecture Notes in Computer Science, Volume 57,\n% Springer 1977,\n% ISBN: 978-3-540-08446-4,\n% LC: QA297.W65.\n%\n% Parameters:\n%\n% Input, real X, the number whose square root is desired.\n%\n% Output, real VALUE, the square root of X.\n%\n persistent niter\n persistent sqrt2\n\n sqrt2 = [ 0.70710678118654752, 1.0, 1.41421356237309505 ]';\n\n if ( isempty ( niter ) )\n niter = 1.443 * r4_log ( - 0.104 * r4_log ( 0.1 * r4_mach ( 3 ) ) ) + 1.0;\n end\n\n if ( x < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_SQRT - Fatal error!\\n' );\n fprintf ( 1, ' X < 0.0\\n' );\n error ( 'R4_SQRT - Fatal error!' )\n elseif ( x == 0.0 )\n value = 0.0;\n else\n\n [ y, n ] = r4_upak ( x );\n ixpnt = floor ( n / 2 );\n irem = floor ( n - 2 * ixpnt + 2 );\n value = 0.261599 + y * ( 1.114292 + y * ( -0.516888 + y * 0.141067 ) );\n\n for iter = 1 : niter\n value = value + 0.5 * ( y - value * value ) / value;\n end\n\n value = r4_pak ( sqrt2(irem) * value, ixpnt );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fn/r4_sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6001973829130651}} {"text": "function [w,run] = train_bfgs(x,w,lambda)\n% TRAIN_BFGS Train a logistic regression model by BFGS.\n%\n% W = TRAIN_BFGS(X,W) returns maximum-likelihood weights given data and a\n% starting guess.\n% Data is columns of X, each column already scaled by the output (+1 or -1).\n% W is the starting guess for the parameters (a column).\n\n% Written by Thomas P Minka\n\nif nargin < 3\n lambda = 0;\nend\nflops(0);\n[d,n] = size(x);\nold_g = zeros(size(w));\nih = eye(d);\nfor iter = 1:1000\n old_w = w;\n % s1 = 1-sigma\n s1 = 1./(1+exp(w'*x));\n g = x*s1' - lambda*w;\n flops(flops + flops_mul(w',x) + n*(flops_exp+2) + flops_mul(x,s1') + 2*d);\n if iter > 1\n dw = w - prev_w;\n dg = g - old_g;\n dwdg = dw'*dg;\n ihdg = ih*dg;\n b = 1 + (dg'*ihdg)/dwdg;\n ihdgdw = ihdg*dw';\n ih = ih + (b*dw*dw' - ihdgdw' - ihdgdw)/dwdg;\n flops(flops + d + d + flops_mul(dw',dg) + flops_mul(ih,dg) + ...\n\tflops_mul(dg',ihdg)+2 + flops_mul(ihdg,dw') + ...\n\tflops_mul(b,dw) + flops_mul(dw,dw') + 4*d*d);\n end\n u = -ih*g;\n flops(flops + flops_mul(ih,g));\n prev_w = w;\n\n % line search along u\n ug = u'*g;\n ux = u'*x;\n a = s1.*(1-s1);\n uhu = (ux.^2)*a' + lambda*(u'*u);\n w = w + (ug/uhu)*u;\n old_g = g;\n flops(flops + flops_mul(u',g) + flops_mul(u',x) + 2*n + ...\n n+flops_mul(1,n,1) + 2*d+1);\n if lambda > 0\n flops(flops + 1+flops_mul(u',u));\n end\n\n run.w(:,iter) = w;\n run.flops(iter) = flops;\n run.e(iter) = logProb(x,w) -0.5*lambda*w'*w;\n\n if max(abs(w - old_w)) < 1e-5\n break\n end\nend\nfigure(2)\nplot(run.e)\nif iter == 1000\n warning('not enough iters')\nend\n", "meta": {"author": "FuzhenZhuang", "repo": "Transfer-Learning-Toolkit", "sha": "24b5323b354aee844b8b7df9fcad17fdfb191dc4", "save_path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit", "path": "github-repos/MATLAB/FuzhenZhuang-Transfer-Learning-Toolkit/Transfer-Learning-Toolkit-24b5323b354aee844b8b7df9fcad17fdfb191dc4/utilities/TLLibrary64/LR/logreg/train_bfgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6001973781571877}} {"text": "function N = tangentspacefactory(M, x)\n% Returns a manifold structure representing the tangent space to M at x.\n%\n% N = tangentspacefactory(M, x)\n%\n% N defines a (linear) manifold that is the tangent space to M at x. Points\n% are represented as tangent vectors to M at x. Tangent vectors are also\n% represented as tangent vectors to M at x.\n%\n% This is chiefly useful to solve optimization problems involving tangent\n% vectors to M at x, which notably comes up when solving linear systems\n% involving, for example, the Hessian of the cost on M at x. The Riemannian\n% (actually, Euclidean) structure on N is that of the tangent space to M,\n% that is, the inner product is inherited.\n%\n% See also: preconhessiansolve\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, April 9, 2015.\n% Contributors: \n% Change log: \n\n % N is the manifold we build. y will be a point on N, thus also a\n % tangent vector to M at x. This is a typical Euclidean space, hence it\n % will be easy to describe in terms of the tools available for M.\n N = struct();\n \n % u, u1 and u2 will be tangent vectors to N at y. The tangent space to\n % N at y is the tangent space to M at x, thus u, u1 and u2 are also\n % tangent vectors to M at x.\n \n N.dim = @() M.dim();\n N.inner = @(y, u1, u2) M.inner(x, u1, u2);\n N.norm = @(y, u) M.norm(x, u);\n N.proj = M.proj;\n N.typicaldist = @() N.dim();\n N.tangent = @(y, u) u;\n N.egrad2rgrad = @(x, g) g;\n N.ehess2rhess = @(x, eg, eh, d) eh;\n N.exp = @exponential;\n N.retr = @exponential;\n N.log = @(y1, y2) M.lincomb(x, 1, y2, -1, y1);\n N.pairmean = @(y1, y2) M.lincomb(x, 0.5, y1, 0.5, y2);\n N.rand = @() M.randvec(x);\n N.randvec = @(y) M.randvec(x);\n N.zerovec = M.zerovec;\n N.lincomb = M.lincomb;\n N.transp = @(y1, y2, u) u;\n N.hash = @(y) ['z' hashmd5(M.vec(x, y))];\n \n % In a Euclidean space, the exponential is merely the sum: y + tu.\n function yy = exponential(y, u, t)\n if nargin == 2\n t = 1;\n end\n yy = M.lincomb(x, 1, y, t, u);\n end\n \nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/tools/tangentspacefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6001880475514265}} {"text": "%This Matlab script can be used to reproduce Figure 4.10 in the monograph:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n%Empty workspace and close figures\nclose all;\nclear;\n\n\n%Define the range of BS antennas\nMvalues = [1 10 100];\n\n%Angular standard deviation in the local scattering model (in degrees)\nASDdeg = 10;\n\n%Nominal angle of the desired UE\nthetaDesired = pi/6;\n\n%Range of nominal angles of the interfering UE\nvarphiInterfererDegrees = -180:1:180;\nvarphiInterfererRadians = varphiInterfererDegrees*(pi/180);\n\n%Define the antenna spacing (in number of wavelengths)\nantennaSpacing = 1/2; %Half wavelength distance\n\n%Define the range of the effective SNR in (3.13) for the desired UE\nSNR1dB = 10;\nSNR1 = 10.^(SNR1dB/10);\n\n%Define the range of the effective SNR in (3.13) for the interfering UE\nSNR2dB = SNR1dB-10;\nSNR2 = 10.^(SNR2dB/10);\n\n\n%Preallocate matrices for storing the simulation results\nrelativeInterferenceCoherent = zeros(length(varphiInterfererRadians),length(thetaDesired),length(Mvalues));\n\n\n%Compute correlation matrix of the desired UE\nR1 = functionRlocalscattering(max(Mvalues),thetaDesired,ASDdeg,antennaSpacing);\n\n\n%% Go through all angles of the interfering UE\nfor n = 1:length(varphiInterfererRadians)\n \n %Compute correlation matrix of the interfering UE\n R2 = functionRlocalscattering(max(Mvalues),varphiInterfererRadians(n),ASDdeg,antennaSpacing);\n \n %Go through all numbers of antennas\n for m = 1:length(Mvalues)\n \n R1m = R1(1:Mvalues(m),1:Mvalues(m));\n R2m = R2(1:Mvalues(m),1:Mvalues(m));\n \n %Compute numerator and denominator of the ratio between desired\n %signal term and coherent interference term in (4.17)\n numerator = SNR2^2*abs(trace(R1m*((SNR1*R1m+SNR2*R2m+eye(Mvalues(m)))\\R2m)))^2;\n denominator = SNR1^2*abs(trace(R1m*((SNR1*R1m+SNR2*R2m+eye(Mvalues(m)))\\R1m)))^2;\n \n relativeInterferenceCoherent(n,m) = numerator/denominator;\n \n end\n \nend\n\n\n%% Plot the simulation results\nfigure;\nhold on; box on;\n\nplot(varphiInterfererDegrees,10*log10(relativeInterferenceCoherent(:,1)),'k-','LineWidth',1);\nplot(varphiInterfererDegrees,10*log10(relativeInterferenceCoherent(:,2)),'r--','LineWidth',1);\nplot(varphiInterfererDegrees,10*log10(relativeInterferenceCoherent(:,3)),'b-.','LineWidth',1);\n\nxlabel('Angle of interfering UE [degree]');\nylabel('Coherent interf. power over signal power [dB]');\nxlim([-180 180]);\nylim([-40 -10]);\n\nlegend('M=1','M=10','M=100','Location','NorthWest');\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/section4_figure10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6001880472395691}} {"text": "function [ n_data, x, y, fxy ] = beta_log_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BETA_LOG_VALUES returns some values of the logarithm of the Beta function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Log[Beta[x]]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, Y, the arguments of the function.\n%\n% Output, real FXY, the value of the function.\n%\n n_max = 17;\n\n fxy_vec = [ ...\n 0.1609437912434100E+01, ... \n 0.9162907318741551E+00, ... \n 0.5108256237659907E+00, ... \n 0.2231435513142098E+00, ... \n 0.1609437912434100E+01, ... \n 0.9162907318741551E+00, ... \n 0.0000000000000000E+00, ... \n -0.1791759469228055E+01, ... \n -0.3401197381662155E+01, ... \n -0.4941642422609304E+01, ... \n -0.6445719819385578E+01, ... \n -0.3737669618283368E+01, ... \n -0.5123963979403259E+01, ... \n -0.6222576268071369E+01, ... \n -0.7138866999945524E+01, ... \n -0.7927324360309794E+01, ... \n -0.9393661429103221E+01 ];\n\n x_vec = [ ...\n 0.2E+00, ...\n 0.4E+00, ...\n 0.6E+00, ...\n 0.8E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 6.0E+00, ...\n 6.0E+00, ...\n 6.0E+00, ...\n 6.0E+00, ...\n 6.0E+00, ...\n 7.0E+00 ];\n\n y_vec = [ ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 1.0E+00, ...\n 0.2E+00, ...\n 0.4E+00, ...\n 1.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 6.0E+00, ...\n 7.0E+00 ]; \n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n x = 0.0;\n y = 0.0;\n fxy = 0.0;\n else\n x = x_vec(n_data);\n y = y_vec(n_data);\n fxy = fxy_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/beta_log_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.600188040959871}} {"text": "% 机动车刹车距离\n%% 插值数据处理\nclear; clc;\nv = 20 : 10 : 150; % 速度,插值节点,单位:千米/小时\nd2=[3.15,7.08,12.59,19.68,28.34,38.57,50.4,63.75,...\n 78.71,95.22,113.29,132.93,154.12,176.87]; % 制动距离,插值节点\nvi = 20 : 1 : 150; % 速度,待插值点\nd2i = interp1(v, d2, vi, 'spline'); % 样条插值得到的制动距离\n\n%% 根据某驾驶员的实际视力和视觉习惯,其驾驶时的有效视距为120m,则其在该路面行车时,时速最高不能超过多少(结果取整)?\ndl = 120; % 某路段的有效视距,单位:米\ntime = 10; % 驾驶员的平均反应时间,单位:秒\nvs = vi * 1000 / 3600; % 速度,插值节点,单位:米/秒\nd1 = vs * time; % 驾驶员反应距离\nd3 = 10; % 预留安全距离,单位:米\ndi = d1 + d2i + d3; % 有效视距 = 驾驶员反应距离 + 制动距离 + 预留安全距离\nx = abs(di - dl); % 有效视距差的绝对值\n[y,i]=sort(x); % 排序,i是排序后元素的序号\nfprintf('有效视距%.4f米某路段的最高时速: %.f千米/小时\\n',dl,vi(i(1)));\nplot(vi,di,vi(i(1)),di(i(1)),'rp');\n\n%% 若以表中数据为参考,设计一条最高时速为125km/h的高速公路,则设计人员应该保 证驾驶者在公路上任一点的可视距离为多少米?\nv_max = 125; % 最高限速,单位:千米/小时\ni = find(vi - 125 == 0);\nfprintf('最高时速%.4f千米/小时的路段需保证有效视距: %.4f米\\n', v_max, di(i));", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/application_2_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6001880329543193}} {"text": "function sample = SamplePose(P, G, label)\n\n% sample from the distribution specified by P and G,\n% label == 0: class label unknown\n% label == k: class label = k; k=1,2,3, ...\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nsample = zeros(10,3);\n\nif label == 0\n k = SampleMultinomial(P.c); % sample label using P.c\nelse\n k = label;\nend\n\nvisited = zeros(10,1);\n\nwhile sum(visited) < 10\n \n for i=1:10 % for each body part\n \n par = G(i,2); % parent body part, if exists\n \n if G(i,1) == 0 % parametrized by (2),(3),(4)\n \n muy = P.clg(i).mu_y(k);\n mux = P.clg(i).mu_x(k);\n muangle = P.clg(i).mu_angle(k);\n sample(i,1) = SampleGaussian(muy, P.clg(i).sigma_y(k));\n sample(i,2) = SampleGaussian(mux, P.clg(i).sigma_x(k));\n sample(i,3) = SampleGaussian(muangle, P.clg(i).sigma_angle(k));\n visited(i) = 1;\n \n elseif G(i,1) == 1 % parametrized by (5),(6),(7)\n \n if visited(par)\n \n muy = P.clg(i).theta(k,1) + ...\n P.clg(i).theta(k,2) * sample(par,1) + ...\n P.clg(i).theta(k,3) * sample(par,2) + ...\n P.clg(i).theta(k,4) * sample(par,3);\n mux = P.clg(i).theta(k,5) + ...\n P.clg(i).theta(k,6) * sample(par,1) + ...\n P.clg(i).theta(k,7) * sample(par,2) + ...\n P.clg(i).theta(k,8) * sample(par,3);\n muangle = P.clg(i).theta(k,9) + ...\n P.clg(i).theta(k,10) * sample(par,1) + ...\n P.clg(i).theta(k,11) * sample(par,2) + ...\n P.clg(i).theta(k,12) * sample(par,3);\n sample(i,1) = SampleGaussian(muy, P.clg(i).sigma_y(k));\n sample(i,2) = SampleGaussian(mux, P.clg(i).sigma_x(k));\n sample(i,3) = SampleGaussian(muangle, P.clg(i).sigma_angle(k));\n visited(i) = 1;\n end\n \n elseif G(i,1) == 2 % parametrized by (8),(9),(10)\n \n if visited(par)\n \n muy = P.clg(i).gamma(k,1) + ...\n P.clg(i).gamma(k,2) * sample(par,1) + ...\n P.clg(i).gamma(k,3) * sample(par,2) + ...\n P.clg(i).gamma(k,4) * sin(sample(par,3)) + ...\n P.clg(i).gamma(k,5) * cos(sample(par,3));\n mux = P.clg(i).gamma(k,6) + ...\n P.clg(i).gamma(k,7) * sample(par,1) + ...\n P.clg(i).gamma(k,8) * sample(par,2) + ...\n P.clg(i).gamma(k,9) * sin(sample(par,3)) + ...\n P.clg(i).gamma(k,10) * cos(sample(par,3));\n muangle = P.clg(i).gamma(k,11) + ...\n P.clg(i).gamma(k,12) * sample(par,1) + ...\n P.clg(i).gamma(k,13) * sample(par,2) + ...\n P.clg(i).gamma(k,14) * sample(par,3);\n sample(i,1) = SampleGaussian(muy, P.clg(i).sigma_y(k));\n sample(i,2) = SampleGaussian(mux, P.clg(i).sigma_x(k));\n sample(i,3) = SampleGaussian(muangle, P.clg(i).sigma_angle(k));\n visited(i) = 1;\n end\n end\n \n end\nend\n\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/SamplePose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.6001475508076747}} {"text": "% Tow Thomas Biquad Bandpass Filter - Leverriers Algorithm\n% File: TowThomasLev.m\n% 9/22/02\nclc;clear;format short g;\nK=1e3;uF=1e-6;\nR1=200*K;R2=10*K;R3=20*K;R4=10*K;R5=20*K;R6=20*K;\nC1=0.0159*uF;C2=C1;\nX=[R1 R2 R3 R4 R5 R6 C1 C2]; % Put components in vector form\n%\n[A,B,D,E]=tow(X); \n%\n% Uncomment following two lines to output arrays to text file qbout.txt\n%fid=fopen('c:\\M_files\\qbout.txt','w'); % Use local directory\n%diary c:\\M_Files\\qbout.txt; % Use local directory\nA\nB\nD\nE\n%\n% Display results of Leverrier's Algorithm\n%\nF1=eye(2);T1=-trace(A*F1)/1\nF0=A*F1+T1*F1\nT0=-trace(A*F0)/2\nY1=D*F1*B+E*T1\nY0=D*F0*B+E*T0\n%\n% Uncomment the following two lines to close text file.\n%diary off\n%status=fclose(fid);\n%\n% Get frequency sweep; BF = Beginning (Log) Frequency, ND = Number of Decades\n% PD = Points per Decade\nBF=2;ND=2;PD=50;Lit=ND*PD+1;L=linspace(BF,BF+ND,Lit);\nfor i=1:Lit\n F=10^L(i);s=2*pi*F*j;\n for k=1:3 % Get all three transfer functions from transfer matrix\n num=E(k)*s^2+Y1(k)*s+Y0(k);\n den=s^2+T1*s+T0;\n Vo(k,i)=20*log10(abs(num/den));\n end\nend\n%\n% Plot Vo\n%\nh=plot(L,Vo(1,:),'k',L,Vo(2,:),'r',L,Vo(3,:),'b');\nset(h,'LineWidth',2);\ngrid on\nxlabel('Log Freq(Hz)');\nylabel('dBV');\ntitle('Transfer Matrix Outputs');\nlegend('V2','V4','V6');\nfigure(1);\n\n\n \n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/TowThomasLev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6001075981852391}} {"text": "function [bval] = f2b(fval,bounds,bits)\n% function [bval] = f2b(fval,bounds,bits)\n%\n% Return the binary representation of the float number fval.\n%\n% fval - the float representation of the number\n% bval - the binary representation of the number\n% bounds - the bounds on the variables\n% bits - the number of bits to represent each variable\n\n% Binary and Real-Valued Simulation Evolution for Matlab \n% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay \n%\n% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function\n% optimization: A Matlab implementation. ACM Transactions on Mathmatical\n% Software, Submitted 1996.\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 1, or (at your option)\n% 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. A copy of the GNU \n% General Public License can be obtained from the \n% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nscale=(2.^bits-1)./ (bounds(:,2)-bounds(:,1))'; %The range of the variables\nnumV=size(bounds,1);\ncs=[0 cumsum(bits)];\nbval=[];\nfor i=1:numV\n fval(i)=(fval(i)-bounds(i,1)) * scale(i);\n bval=[bval rem(floor(fval(i)*pow2(1-bits(i):0)),2)];\nend", "meta": {"author": "HuangCongQing", "repo": "Algorithms_MathModels", "sha": "e15b0e9053b11f08b5ce1e3492c4acb444409c8b", "save_path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels", "path": "github-repos/MATLAB/HuangCongQing-Algorithms_MathModels/Algorithms_MathModels-e15b0e9053b11f08b5ce1e3492c4acb444409c8b/《MATLAB 神经网络30个案例分析》源程序 数据/chapter27/gaot/f2b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6001075833713296}} {"text": "function [g]=comp_iwfac(gf,L,a,M)\n%COMP_IWFAC Compute inverse window factorization\n% Usage: g=comp_iwfac(gf,a,M);\n%\n% Input parameters:\n% gf : Factored Window\n% a : Length of time shift.\n% M : Number of frequency bands.\n% Output parameters:\n% g : Window function.\n%\n% References: so07-2 st98-8\n\n% AUTHOR : Peter L. Søndergaard.\n% TESTING: OK\n% REFERENCE: OK\n\n% Calculate the parameters that was not specified\nR=prod(size(gf))/L;\n\nN=L/a;\nb=L/M;\n\n% The four factorization parameters.\nc=gcd(a,M);\np=a/c;\nq=M/c;\nd=N/q;\n\ngf=reshape(gf,p,q*R,c,d);\n\n% Scale by the sqrt(M) comming from Walnuts representation\ngf=gf/sqrt(M);\n\n\n% fft them\nif d>1\n gf=ifft(gf,[],4);\nend;\n\ng=zeros(L,R,assert_classname(gf));\n\n% Set up the small matrices\nfor w=0:R-1\n for s=0:d-1\n for l=0:q-1\n for k=0:p-1\n\tg((1:c)+mod(k*M-l*a+s*p*M,L),w+1)=reshape(gf(k+1,l+1+q*w,:,s+1),c,1);\n end;\n end;\n end;\nend;\n\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/comp/comp_iwfac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.6001075759586603}} {"text": "% GAMLPR = Gamma Distribution - Log Probability Density Ratio\n% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright\n% \n% [ lpr ] = gamlpr( g1, g2, alph, gam ) \n%\n% returns log ( p(g1)/p(g2) ) when g1 and g2 are\n% distributed gamma(alph,gam)\n%\n\nfunction [ lpr ] = gamlpr(g1, g2, alph, gam) \nlpr = (alph-1)*log(g1/g2) - (g1-g2)/gam ;\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/198-mcmc/mcmc/gamlpr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.600082477873413}}